Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
60188b0502 |
@@ -1,9 +1,5 @@
|
||||
# 印度占星 Skill 更新日志
|
||||
|
||||
## 2026-11-16 · 生时纠正 P0 复核统计修订
|
||||
|
||||
- BUG-1931(#296):新增聚合 SQL v2,补齐来源冲突、未知来源分组和按历史来源统计现存报告。附旧产物与消费入口检查清单。Skill 版本不变。
|
||||
|
||||
## 2026-11-16 — 生时纠正复跑逐臂核对并补齐 P0 证据
|
||||
|
||||
- 新增完整四臂比较、历史范围读回回归与只读聚合统计。占星 Skill 版本不变(BUG-1925)。
|
||||
|
||||
@@ -26035,39 +26035,3 @@
|
||||
- 验证与防复发:公开测试盘父母题本地样本(DeepSeek):改前 3 份每份 2 处「这条线」,改后 4 份合计 1 处;「底色」和补充套话改后 0 处。相关断言随新字句更新(原值 / 新值 / 原因写在测试注释里),问答测试 808 通过。未解决:「判断依据」里仍会出现 Narayana 的内部状态用语(该句受占星师裁定约束,未动)。Gemini 中转当天在本地只返回几百字的短答案(未改动的代码同样如此),因此没有 Gemini 的改后样本。
|
||||
- 关联记录:BUG-1929、BUG-1928、BUG-1920。
|
||||
- 修复版本:`claude/echo-words-1930`,待 staging 实测。
|
||||
|
||||
## BUG-1931 | 生时纠正聚合统计遗漏来源冲突与旧产物
|
||||
|
||||
- 状态:resolved(已在隔离 PostgreSQL 17 执行合成断言)。
|
||||
- 首次发现 / 最近更新:2026-11-16 / 2026-11-16。
|
||||
- 触发与现象:复核 #294 的 v1 统计时,重叠来源被首个匹配覆盖,已退回填报状态的档案名下旧报告漏计,零行与小样本用了同一显示。
|
||||
- 根因:来源用互斥分支判定,报告统计只关联当前采用且已完成的结果。旧独立合盘、未知来源与导出缺少足够的绑定信息。
|
||||
- 修复:保留 v1,新增只读 v2。逐项统计来源特征,单列冲突与未知明细。加入按有旧记录的主体统计现存报告,区分零行和小样本,并隐藏可减法反推小组的总计。
|
||||
- 验证与防复发:`frontend/tests/rectification-p0-aggregate-v2-20261116.test.ts` 验证手选和旧痕迹区分、旧报告统计、零值和遮蔽、总计抑制以及仅输出聚合值。新版已在使用仓内迁移的隔离数据库执行,生产统计留给负责人。
|
||||
- 关联记录:#294、#296、BUG-1890、BUG-1896、BUG-1925。
|
||||
- 修复版本:`codex/rect-p0-wrapup-20261116`。见 [旧产物清单](research/rect-p0-artifact-checklist-20261116.md) 和 [进度](tasks/PROGRESS-rect-p0-wrapup-20261116.md)。
|
||||
|
||||
## BUG-1935 | 后台「用量和成本」、上线配置的实测成本和毛利、订阅列表一直是空的
|
||||
|
||||
- 状态:fixed-pending-verify(待 staging 实测)。
|
||||
- 首次发现 / 最近更新:2026-11-16 / 2026-11-16。
|
||||
- 触发与现象:产品负责人在 staging 后台填好模型输入、输出单价后,上线配置页四项功能的实测成本都显示「还没有数据」、毛利「算不出」;用量和成本页也没有记录。当天他在同一环境完成过多次聊天。用量聚合接口返回八项功能 runs 全为 0。
|
||||
- 触发条件:self-hosted 环境(后台用 `admin_runtime` 角色读库)下,后台读取 `usage_ledger`、`usage_reservations`、`usage_events`、`user_subscriptions`、`user_product_redemptions`、`notification_templates`、`pricing_experiment_events`。
|
||||
- 根因:这些表启用了行级安全,迁移只给 `admin_runtime` 授了 SELECT,没有建它的 SELECT 策略;读取不报错,只是被静默过滤成 0 行。与 BUG-147 同一根因;当时只补了出问题的那几张表,没有检查其余授权表,之后 `feature_pricing`、`feature_flags` 又各补过一次,仍没有全量核对。
|
||||
- 修复:新迁移给上述七张表各建 `<表名>_admin_read` 策略(`for select to admin_runtime using (true)`)。
|
||||
- 验证与防复发:新增 `frontend/tests/admin-runtime-read-policies-20261116.test.ts`,扫描全部迁移:凡启用行级安全且授予 `admin_runtime` SELECT 的表都必须有它的策略,否则失败。线上效果待部署后由产品负责人在后台确认(本会话没有后台和数据库权限)。
|
||||
- 关联记录:BUG-147、BUG-135。
|
||||
- 修复版本:`claude/admin-usage-rls-1935`,待 staging 实测。
|
||||
|
||||
## BUG-1937 | 后台上线配置的成本和毛利在没有用量时是空的;功能开关页可以新增没人读的开关;对话质量页不说明何时有记录
|
||||
|
||||
- 状态:fixed-pending-verify(待 staging 实测)。
|
||||
- 首次发现 / 最近更新:2026-11-16 / 2026-11-16。
|
||||
- 触发与现象:产品负责人填好模型单价后,上线配置页成本显示「还没有数据」、毛利「算不出」(读不到用量是 BUG-1935;这里是页面本身在没有用量时不给任何数)。功能开关页有新增、编辑草稿、灰度百分比、配置 JSON 和发布,他不知道怎么用;对话质量记录页是空的,也没有说明。
|
||||
- 触发条件:上线前(没有实测用量)定价;任何管理员打开功能开关页或对话质量页。
|
||||
- 根因:上线配置页只在有结算记录时显示成本,而定价恰恰发生在没有记录的时候;单价填好之前结算的请求成本为 0,也被当成实测。功能开关页是通用编辑器,产品实际只读四个开关键,新增的键没有代码读取,且开关要「启用且灰度 100% 且已发布」才算开,页面没有说明。对话质量记录只在用户点踩时写入,页面没有说明。
|
||||
- 修复:上线配置页的成本改为「有带价格的实测用实测,否则按默认模型单价乘以一次成功生成的典型字数估算」,分别标(实测)(估算);实测为 0 时不采用。功能开关页改为固定列出产品实际读取的四个开关,每个一个开关按钮和一句「关掉会怎样」,拨动即保存并发布(开 = 启用且 100%);去掉新增、灰度和配置 JSON。对话质量页加一句说明。
|
||||
- 验证与防复发:`frontend/tests/admin-clarity-20261116.test.ts`:估算与实测的取舍;开关清单必须与代码里实际读取的开关键一致(以后新增读取点而不加到清单会失败);页面不再出现新增和配置 JSON。典型字数是 2026-11-16 本地各一份样本的量(聊天 10 万入 / 1.3 万出,个人报告 12.6 万 / 3.3 万,年运 10.8 万 / 8.6 万,合盘 36 万 / 10.2 万),不含失败重试,只作估算。后台页面本会话无登录权限,未在真实页面上操作过。
|
||||
- 补充(同日):估算成本原先只显示两位小数,0.008 元和 0.015 元都显示成 0.01、毛利出现「约 100%」;改为三位小数,与实测一致。
|
||||
- 关联记录:BUG-1935、BUG-1922。
|
||||
- 修复版本:`claude/admin-clarity-1936`(分支名沿用旧编号),待 staging 实测。
|
||||
|
||||
@@ -1,225 +0,0 @@
|
||||
-- Rectification P0 aggregate v2, 2026-11-16. Internal authorized audit only.
|
||||
-- Business schema through staging 052e8ab6, including the chart-choice records,
|
||||
-- adoption sources, annual report and marriage-match migrations.
|
||||
-- Counts describe stored state at execution time and existing reports. They
|
||||
-- cannot establish adoption frequency or which rule a report used at generation.
|
||||
-- Output sections are named by metric. unknown_breakdown is the separate
|
||||
-- unknown-profile table, grouped only by history, receipt and contract presence.
|
||||
-- Unknown means neither safe nor subject to automatic withdrawal.
|
||||
-- Zero is visible; 1–4 is masked. Suppress the unknown and conflict totals if
|
||||
-- any of their groups is masked. No other group totals are emitted. This does not
|
||||
-- guarantee anonymity. Review combined disclosure before sharing results.
|
||||
-- No profile-bound browser download ledger. Legacy standalone match rows have
|
||||
-- no status field; rows without a subject binding cannot be attributed.
|
||||
|
||||
begin transaction isolation level repeatable read read only;
|
||||
|
||||
with subjects as (
|
||||
select id as owner_id, null::uuid as subject_id, birth_time_status, birth_date,
|
||||
active_birth_date, active_birth_time, active_birth_provenance as provenance
|
||||
from public.profiles
|
||||
union all
|
||||
select user_id, id, birth_time_status, birth_date,
|
||||
active_birth_date, active_birth_time, active_birth_provenance
|
||||
from public.chart_profiles
|
||||
where role = 'other'
|
||||
), active as (
|
||||
select s.*, r.id as receipt_id,
|
||||
coalesce(jsonb_typeof(r.detail -> 'provenance') = 'object'
|
||||
or jsonb_typeof(r.detail -> 'decision') = 'object', false) as has_receipt,
|
||||
exists (
|
||||
select 1 from public.chart_choice_records h
|
||||
where h.user_id = s.owner_id and h.chart_profile_id is not distinct from s.subject_id
|
||||
) as has_history
|
||||
from subjects s
|
||||
left join public.chart_choice_records r
|
||||
on r.user_id = s.owner_id and r.chart_profile_id is not distinct from s.subject_id
|
||||
and r.saved_date = coalesce(s.active_birth_date, s.birth_date)
|
||||
and r.saved_time = s.active_birth_time
|
||||
and r.id = case when s.provenance ->> 'record_id' ~* '^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$'
|
||||
then (s.provenance ->> 'record_id')::uuid end
|
||||
where s.active_birth_time is not null and s.birth_time_status in ('accepted', 'confirmed')
|
||||
), record_evidence as (
|
||||
select r.id, r.user_id, r.chart_profile_id,
|
||||
r.detail #> '{provenance}' as provenance,
|
||||
r.detail #> '{decision}' as decision,
|
||||
coalesce(r.detail #>> '{provenance,contract}',
|
||||
case when jsonb_typeof(r.detail -> 'decision') = 'object'
|
||||
and r.detail #> '{decision,segment}' is null
|
||||
then 'chart-choice-v1' end) as contract,
|
||||
r.rule
|
||||
from public.chart_choice_records r
|
||||
), evidence as (
|
||||
-- Keep recorded, decision and active rules independent so one cannot mask another.
|
||||
select 'history' as scope, r.user_id as owner_id, r.chart_profile_id as subject_id,
|
||||
r.contract, r.provenance ->> 'source' as source, facts.rule, facts.decided_by, facts.rounds
|
||||
from record_evidence r
|
||||
cross join lateral (
|
||||
values (r.provenance ->> 'rule', r.provenance ->> 'decided_by', r.provenance -> 'rounds'),
|
||||
(r.decision ->> 'rule', r.decision ->> 'decided_by', r.decision -> 'rounds'),
|
||||
(r.rule, coalesce(r.decision ->> 'decided_by', r.provenance ->> 'decided_by'),
|
||||
coalesce(r.decision -> 'rounds', r.provenance -> 'rounds'))
|
||||
) facts(rule, decided_by, rounds)
|
||||
union all
|
||||
select 'active', a.owner_id, a.subject_id, facts.contract, facts.source, facts.rule, facts.decided_by, facts.rounds
|
||||
from active a
|
||||
left join record_evidence r on r.id = a.receipt_id
|
||||
cross join lateral (
|
||||
values (a.provenance ->> 'contract', a.provenance ->> 'source', a.provenance ->> 'rule',
|
||||
a.provenance ->> 'decided_by', a.provenance -> 'rounds'),
|
||||
(r.contract, r.provenance ->> 'source', r.provenance ->> 'rule',
|
||||
r.provenance ->> 'decided_by', r.provenance -> 'rounds'),
|
||||
(coalesce(r.contract, a.provenance ->> 'contract'), null, r.decision ->> 'rule',
|
||||
r.decision ->> 'decided_by', r.decision -> 'rounds'),
|
||||
(coalesce(r.contract, a.provenance ->> 'contract'), null, r.rule,
|
||||
coalesce(r.decision ->> 'decided_by', r.provenance ->> 'decided_by'),
|
||||
coalesce(r.decision -> 'rounds', r.provenance -> 'rounds'))
|
||||
) facts(contract, source, rule, decided_by, rounds)
|
||||
), signals as (
|
||||
select scope, owner_id, subject_id,
|
||||
coalesce(bool_or(source = 'user_choice_from_answers' or rule = 'chart_answers'), false) as old_questionnaire,
|
||||
coalesce(bool_or(contract = 'chart-choice-v1' and rule = 'evidence' and decided_by = 'event'), false) as old_event,
|
||||
coalesce(bool_or(contract = 'segment-v1' or source = 'server_segment_midpoint'), false) as old_segment,
|
||||
coalesce(bool_or(rule = 'user_override'), false) as manual_choice,
|
||||
coalesce(bool_or(contract = 'chart-choice-v2' and jsonb_typeof(rounds) = 'array' and rounds <> '[]'::jsonb),
|
||||
false) as chart_side,
|
||||
coalesce(bool_or(source in ('reported_time_default', 'window_midpoint_default')), false) as declared_default
|
||||
from evidence
|
||||
group by scope, owner_id, subject_id
|
||||
), active_features as (
|
||||
select a.owner_id, a.subject_id, a.provenance, a.has_history, a.has_receipt,
|
||||
s.old_questionnaire or (s.manual_choice and coalesce(h.old_questionnaire, false)) as old_questionnaire,
|
||||
s.old_event or (s.manual_choice and coalesce(h.old_event, false)) as old_event,
|
||||
s.old_segment or (s.manual_choice and coalesce(h.old_segment, false)) as old_segment,
|
||||
s.chart_side or (s.manual_choice and coalesce(h.chart_side, false)) as chart_side,
|
||||
s.manual_choice, s.declared_default
|
||||
from active a
|
||||
join signals s on s.scope = 'active' and s.owner_id = a.owner_id and s.subject_id is not distinct from a.subject_id
|
||||
-- Old traces on the same subject leave a manual choice open to review even
|
||||
-- without an active receipt. An audit conflict does not establish causality.
|
||||
left join signals h on h.scope = 'history' and h.owner_id = a.owner_id and h.subject_id is not distinct from a.subject_id
|
||||
), active_signals as (
|
||||
select f.*,
|
||||
(old_questionnaire::int + old_event::int + old_segment::int
|
||||
+ manual_choice::int + chart_side::int + declared_default::int) as matches
|
||||
from active_features f
|
||||
), features as (
|
||||
select f.category, count(*) filter (where f.matched) as n
|
||||
from (values (true)) as zero_fill(dummy)
|
||||
left join active_signals a on true
|
||||
cross join lateral (
|
||||
values ('old_questionnaire', a.old_questionnaire),
|
||||
('old_event', a.old_event),
|
||||
('segment-v1', a.old_segment),
|
||||
('explicit_manual_choice', a.manual_choice and a.matches = 1),
|
||||
('issue_229_chart_side', a.chart_side),
|
||||
('declared_default', a.declared_default),
|
||||
('conflict', a.matches >= 2),
|
||||
('conflict_manual_and_old', a.matches >= 2 and a.manual_choice
|
||||
and (a.old_questionnaire or a.old_event or a.old_segment or a.chart_side)),
|
||||
('conflict_other', a.matches >= 2 and not (a.manual_choice
|
||||
and (a.old_questionnaire or a.old_event or a.old_segment or a.chart_side))),
|
||||
('unknown', a.matches = 0)
|
||||
) f(category, matched)
|
||||
group by f.category
|
||||
), provenance_groups as (
|
||||
select case when provenance ->> 'contract' in ('segment-v1', 'chart-choice-v1', 'chart-choice-v2', 'agentic-rectification-v1')
|
||||
then provenance ->> 'contract' when provenance ->> 'contract' is null then 'missing' else 'other' end as contract,
|
||||
case when provenance ->> 'source' in ('user_choice', 'user_choice_from_answers', 'server_segment_midpoint',
|
||||
'reported_time_default', 'window_midpoint_default', 'certain')
|
||||
then provenance ->> 'source' when provenance ->> 'source' is null then 'missing' else 'other' end as source,
|
||||
case when provenance ->> 'rule' in ('chart_answers', 'evidence', 'user_override', 'reused_record', 'reported_time_default',
|
||||
'window_midpoint_default', 'majority', 'tie_keeps_reported', 'strong_override',
|
||||
'reported_kept', 'stopped', 'round_limit', 'no_line_in_range')
|
||||
then provenance ->> 'rule' when provenance ->> 'rule' is null then 'missing' else 'other' end as rule
|
||||
from active_signals
|
||||
), active_retired as (
|
||||
select owner_id, subject_id
|
||||
from active_signals
|
||||
where provenance ->> 'retired_reason' = 'BUG-1890' or old_questionnaire or old_event or old_segment
|
||||
), historical_subjects as (
|
||||
select q.owner_id, q.subject_id
|
||||
from signals q
|
||||
where q.scope = 'history' and (q.old_questionnaire or q.old_event or q.old_segment or q.chart_side)
|
||||
and exists (
|
||||
select 1 from subjects s where s.owner_id = q.owner_id and s.subject_id is not distinct from q.subject_id
|
||||
)
|
||||
), report_statuses(status) as (
|
||||
values ('generating'), ('ready'), ('failed')
|
||||
), report_types(report_type) as (
|
||||
values ('personal_full'), ('personal_thematic'), ('annual_full'), ('synastry_full')
|
||||
), statuses_by_type as (
|
||||
select t.report_type, s.status from report_types t cross join report_statuses s
|
||||
union all select 'legacy_synastry', 'not_recorded'
|
||||
), ready_reports as (
|
||||
select r.report_type
|
||||
from public.personal_reports r
|
||||
where r.status = 'ready' and r.report_type in (select report_type from report_types)
|
||||
and exists (
|
||||
select 1 from active_retired s where s.owner_id = r.user_id
|
||||
and (s.subject_id is not distinct from r.chart_profile_id
|
||||
or (r.report_type = 'synastry_full' and r.partner_chart_profile_id = s.subject_id))
|
||||
)
|
||||
), historical_reports as (
|
||||
select r.report_type, r.status
|
||||
from public.personal_reports r
|
||||
where r.report_type in (select report_type from report_types)
|
||||
and exists (
|
||||
select 1 from historical_subjects s where s.owner_id = r.user_id
|
||||
and (s.subject_id is not distinct from r.chart_profile_id
|
||||
or (r.report_type = 'synastry_full' and r.partner_chart_profile_id = s.subject_id))
|
||||
)
|
||||
union all
|
||||
select 'legacy_synastry', 'not_recorded'
|
||||
from public.synastry_reports r
|
||||
where exists (
|
||||
select 1 from historical_subjects s where s.owner_id = r.user_id
|
||||
and coalesce(s.subject_id::text, 'self') in (r.subject_low, r.subject_high)
|
||||
)
|
||||
), presence(flag) as (
|
||||
values (true), (false)
|
||||
), unknown_counts as (
|
||||
select h.flag as has_history, r.flag as has_receipt, m.flag as missing_contract, count(a.owner_id) as n
|
||||
from presence h cross join presence r cross join presence m
|
||||
left join active_signals a on a.matches = 0 and a.has_history = h.flag and a.has_receipt = r.flag
|
||||
and (a.provenance ->> 'contract' is null) = m.flag
|
||||
group by h.flag, r.flag, m.flag
|
||||
), counts as (
|
||||
select 'provenance' as metric, null::text as category, contract, source, rule,
|
||||
null::text as report_type, null::text as report_status, null::boolean as has_history,
|
||||
null::boolean as has_receipt, null::boolean as missing_contract, count(*) as n
|
||||
from provenance_groups
|
||||
group by contract, source, rule
|
||||
union all
|
||||
select 'feature', category, null, null, null, null, null, null, null, null, f.n
|
||||
from features f
|
||||
where (f.category <> 'unknown' or not exists (select 1 from unknown_counts u where u.n between 1 and 4))
|
||||
and (f.category <> 'conflict' or not exists (
|
||||
select 1 from features child where child.category in ('conflict_manual_and_old', 'conflict_other')
|
||||
and child.n between 1 and 4
|
||||
))
|
||||
union all
|
||||
select 'unknown_breakdown', null, null, null, null, null, null, has_history, has_receipt, missing_contract, n
|
||||
from unknown_counts
|
||||
union all
|
||||
select 'active_retired', null, null, null, null, null, null, null, null, null, count(*) from active_retired
|
||||
union all
|
||||
select 'ready_reports_on_retired', null, null, null, null, t.report_type, 'ready', null, null, null, count(r.report_type)
|
||||
from report_types t left join ready_reports r using (report_type)
|
||||
group by t.report_type
|
||||
union all
|
||||
select 'reports_on_historical_sources', null, null, null, null, t.report_type, t.status, null, null, null, count(r.report_type)
|
||||
from statuses_by_type t left join historical_reports r on r.report_type = t.report_type and r.status = t.status
|
||||
group by t.report_type, t.status
|
||||
)
|
||||
select metric, category, contract, source, rule, report_type, report_status,
|
||||
case has_history when true then 'yes' when false then 'no' end as has_history,
|
||||
case has_receipt when true then 'yes' when false then 'no' end as has_receipt,
|
||||
case missing_contract when true then 'yes' when false then 'no' end as missing_contract,
|
||||
case when n = 0 then 'no' else 'yes' end as has_any,
|
||||
case when n between 1 and 4 then '<5' else n::text end as count_display
|
||||
from counts
|
||||
order by metric, category, contract, source, rule, report_type, report_status,
|
||||
has_history, has_receipt, missing_contract;
|
||||
|
||||
commit;
|
||||
@@ -1,24 +0,0 @@
|
||||
# 生时纠正 P0 旧产物与消费入口检查清单
|
||||
|
||||
按 staging 052e8ab6 的源码、迁移和现有回归盘点。`readBirthRow` 是档案读取投影。它把可识别的停用采用结果替换为原报时或原填范围的代表分钟,并保留原范围。覆盖包括旧答题、segment-v1 和能与当前采用精确匹配的旧事件回执。读取投影不更新历史记录。
|
||||
|
||||
| 入口或产物 | 读的字段与代码位置 | 缓存键和撤回后的行为 | 已有保护 |
|
||||
| --- | --- | --- | --- |
|
||||
| 长报告新算、生成续跑 | `personal-report-worker-subject.ts` 的 `loadReportWorkerProfile` 经 `report-subject-birth.ts` 取当前指定主体。`personal-report-longform-birth.ts` 的 `buildLongformBirthPayload` 传出生时、时间来源、确认状态和范围。 | 已知请求以账号和请求号查找,`request_fingerprint` 用于幂等。`personal-report-longform-snapshot.ts` 以账号、请求号和 `longform-calculation-snapshot-v1` 读生成快照。`contentSha256` 校验正文完整性。新请求用当前投影,原请求可继续读取先前快照。快照查找键无停用来源或范围版本。 | `retired-birth-window-1890.test.ts` 的 `retired questionnaire and segment adoptions read the original chart, report window, and chat clock`。已排队旧快照的来源复核无。 |
|
||||
| 长报告重开 | `api/reports/[reportId]/route.ts` 按所有者及报告号取 `personal_reports.report_document`,按需读取快照中的阅读与英文版。报告文档可有 `subject.birthTimeStatus`、`subject.birthFingerprint`。 | `resolveReportRead` 校验存档的文档结构及证据哈希。重开读取生成时的快照,仍可能有旧采用结果。无统一的独立「已校正」标志,也无当前停用来源比对。 | `report-birth-binding.test.ts` 的 `documents without the field (old reports) still parse; a malformed fingerprint does not`、`GET /api/reports/:id no longer looks up the subject for a cover (M5)`。旧快照来源复核无。 |
|
||||
| 年运新算与重开 | `annual-report-server.ts` 取当前主体。`annualBirthTime` 生成 `birth_window` 及代表时刻。详情 API 经 `readAnnualSnapshot` 读 `annual-report-snapshot`,等候中的报告也可读已完成节。 | `findAnnualReport` 按账号、主体、报告类型和 `annual:<kind>:<anchor>` 查找生成中/现成报告,键无档案来源或范围版本。重开仍读取对应请求号的快照。旧区间、输入或判定可随既有快照继续显示,无统一「已校正」标志。 | `rectification-p0-evidence-20261116.test.ts` 的 `a retired profile reaches new chart and report readers with its declaration and leaves history intact`。旧同周期成果复用的来源保护无。 |
|
||||
| 完整合盘 | `synastry-full-create.ts` 的 `openSynastryPair` 与 `marriage-match-service.ts` 的 `loadSynastrySubjectBirth` 按双方当前主体读时刻和范围。详情 API 以账号、请求号及 `synastry-full-snapshot` 读 `publicSynastryView`。 | `pairQuery` 键含账号、规范化双主体、两份 `marriageMatchFingerprint` 和规则版本。指纹含计算时刻、坐标、时区、岁差、节点、有效范围和确认标记,无独立来源版本。有效输入变化会换键。直接打开原报告号仍读快照,可含旧时刻和附录。 | `marriage-match-service.test.ts` 的 `a changed birth fingerprint is not the stored row` 验证共用指纹的缓存区隔。已生成完整合盘的来源复核无。 |
|
||||
| 旧独立合盘 | `api/synastry-reports/route.ts` 的 GET 读账号自己的 `synastry_reports.report`(`rules_version` 为空)。同表有较新的可绑定配对快照,计算查询见 `marriage-match-service.ts`。 | 旧列表按账号、空规则版本、创建时间读取,未绑定主体的旧行无可用档案键、报告状态或通用「已校正」字段。已绑定的新配对按双主体、两份出生指纹和规则版本复用。旧列表仍可呈现历史结果。 | 新配对的 `swapped ids hit the same stored row` 和 `a changed birth fingerprint is not the stored row`。旧独立产物的撤回检查无。 |
|
||||
| 聊天取数卡 | `api/consult/route.ts` 取当前指定主体的时刻,经 `consultation-route-service.ts` 的 `prepareConsultationRoute` 产出 `serverChart` 或 `declared_birth_window`。历史会话已交付正文仍是旧消息。 | `consultation-tools.ts` 的计算/证据缓存限本次请求。历史会话以会话和消息读取,无档案来源或范围版本比对。新回合可用原报范围,旧取数卡仍可能包含旧结果。 | `retired-birth-window-1890.test.ts` 的 `retired questionnaire and segment adoptions read the original chart, report window, and chat clock`。已交付消息的来源复核无。 |
|
||||
| 星盘面板 | `chart-view-service.ts` 经主体读取调用 `prepareChartViewProfile`;`chart-view-profile-read.ts` 交付有效时刻、范围及档案指纹。 | `chartViewEngineCacheKey` 用账号、主体、计算路径和过运日期等调用作用域,以及日期、时刻、位置、时区、岁差和节点。无独立来源或范围版本。时刻变化时换键,时刻相同可以复用盘体。`use-chart-page.ts` 在账号或档案指纹改变时替换客户端页状态。 | P0 六入口合成测试与 `report-birth-binding.test.ts` 的 `the report fingerprint is the chart page's profileFingerprint (same function, stored row)`。来源撤回且时刻不变时的专门缓存回归无。 |
|
||||
| 导出与已下载文件 | `report-export-blocks.ts`、`annual-report-export.ts`、`synastry-report-export.ts` 和 `consultation-report-export.ts` 用当前已渲染的报告、存档快照或聊天答案构造 Markdown。 | 导出函数没有再次读取档案,也没有服务器下载台账或单独档案缓存键。旧快照可再次导出;下载到本地的文件服务器无法回收。 | `annual-md-export-20261113.test.tsx` 的 `annual export supports old snapshots with separate windows and a single-column audit` 覆盖兼容读取。快照来源复核与外部文件回收保护无。 |
|
||||
| 首页及今日卡 | `api/account/route.ts` 由 `readBirthRow` 投影本人资料,其他主体由 `api/chart-profiles/route.ts` 读取。`(app)/page.tsx` 用 `takeHomeWarmStart` 的初值和后续账号/档案刷新。 | `home-warm-start.ts` 的挂载记忆键是导航目标对象、URL 和 10 秒时限,读取上一次账号/档案投影。`daily-starlanguage.ts` 的卡片键含账号、主体、档案计算指纹与当地日。档案计算指纹含有效日期、时刻、时区、坐标和时间状态。两者没有独立的来源撤回版本。后续账号读取按当前档案投影。 | P0 六入口测试与 `birth-time-consultation-consent.test.ts` 的 `account refresh identities reject an older response after a newer case request starts`。撤回瞬间的内存暖启动复核无。 |
|
||||
| 聊天模型工具 | `mastra/consultation-tools.ts` 中 `run-jyotish-consultation` 和 `run-jyotish-window-consultation` 消费本次服务端选择的时间或范围。模型能用计算结果和证据回执。能打开纠正邀请,工具注册不含采用出生时刻的写接口。 | `read-consultation-evidence` 只查本回合内存计算回执,按请求和证据段访问,无跨回合档案键。邀请工具不会写回出生时刻;采用发生在独立用户操作。 | P0 测试覆盖聊天取原范围,`legacy choice requests reject individually, on repeat and concurrently without storage writes` 覆盖停用采用接口。回读旧已生成聊天证据时的来源复核无。 |
|
||||
|
||||
## 发现的缺口
|
||||
|
||||
- 没有把长报告、年运和合盘的历史快照与当前停用来源逐份复核的字段或读时检查。
|
||||
- 年运已有同主体同周期快照的匹配键没有纳入档案时间来源或范围版本。
|
||||
- 旧独立合盘中缺双主体绑定的行、浏览器导出和已下载文件不能按档案追溯。
|
||||
- 首页暖启动和已交付历史聊天内容可能保留上一次投影或当时的计算依据。
|
||||
- 星盘缓存按有效计算输入复用,来源撤回而有效时刻相同时缺少专门的回归证据。
|
||||
@@ -1,26 +0,0 @@
|
||||
# #296 生时纠正 P0 统计复核
|
||||
|
||||
- 开工基线 `052e8ab6add2155783155fc10616eac294caf271`。任务书提交 `7dfac594fac63e2ea4ff4409f66f35f5194aefa4`。关联 BUG-1931、#294、BUG-1890、BUG-1896、BUG-1925。
|
||||
- 保留 v1,新增 [只读聚合 v2](../operations/rect-p0-aggregate-20261116-v2.sql)。每个来源特征独立计数。只统计单独命中的手选为 `explicit_manual_choice`。当前采用与精确匹配的回执分别识别,不能用回执掩过已存来源,也不能用当前来源掩过回执中的旧痕迹。手选若在同主体历史中还有旧来源痕迹,也计冲突,即使没有当前回执指针。冲突表示需要核对,无法证明其中一次采用造成另一次采用。
|
||||
- `unknown_breakdown` 只按同主体有无历史、当前精确关联回执有无结构化来源或决定、当前档案缺不缺 `contract` 计数。冲突和未知总计在有小组被遮蔽时隐藏。零显示 `0` 和 `no`,1–4 显示 `<5` 和 `yes`。分组只输出固定词表。
|
||||
- 历史来源段独立于当前状态。对同一账号下的主体按历史收录长报告、主题报告、年运与完整合盘的现存行,分生成、完成、失败。合盘双方任一匹配即统计一次。可绑定的旧独立合盘单列,状态标示 `not_recorded`。统计报告存量,不能证明生成时的来源。
|
||||
- [旧产物与消费入口清单](../research/rect-p0-artifact-checklist-20261116.md) 记录当前输入、缓存键和已生成结果的读取边界。
|
||||
|
||||
## 验证
|
||||
|
||||
- `node node_modules/tsx/dist/cli.mjs --test tests/rectification-p0-aggregate-v2-20261116.test.ts` 两项通过。用仓内迁移在隔离 PostgreSQL 17 创建测试库。合成数据覆盖手选冲突、单独手选、未知分组、档案返回填报状态后仍可统计的报告、零和 1–4 区分、部分总计抑制和输出隐私。
|
||||
- 隔离测试首次运行时迁移子进程返回通用失败。最终测试直接调用同一仓内迁移函数,再走 PostgreSQL 客户端执行整份只读脚本。合成档案先写声明,再按实际数据库触发器边界写采用数据。
|
||||
- `npx --no-install eslint .` 为 0 错误,63 个既有警告。
|
||||
- `tsc --noEmit` 和 `npm run build` 通过。基线和候选首页都保持静态,39 个 JS/CSS 入口资产 gzip 各为 616 927 字节,变化 0%。
|
||||
- 生时纠正、长报告绑定、年运导出和合盘缓存的定向组合共 25 项通过。
|
||||
- 原生 Windows `npm test` 全量初跑,基线 3 903 项、70 项失败,候选 3 905 项、59 项失败,均无取消。按名字对照,候选出现 6 个基线未失败项,其中 5 个(含新增 PostgreSQL 用例)受共享的 Docker 测试端口耗尽影响,另一个是依赖调度时间的回答时钟断言。隔离库定向用例已通过。
|
||||
- Linux 快速门初跑有 2 项环境失败。修正容器中缺少 Node 和 `origin/staging` 未指向真实开工基线两个问题后,两份相关 Python 测试文件的 15 项定向复验通过。
|
||||
- 对照复跑用统一的 4 个前端测试并发,Docker 对这两轮全量不可用。基线 3 903 项(3 822 通过、37 跳过),候选 3 905 项(3 823 通过、38 跳过),相同 44 项失败,均无取消。按用例名逐项核对,原用例无缺失、新增失败为零。额外跳过的是另在隔离数据库通过的新增 PostgreSQL 用例。回答时钟断言在两端单跑都通过。
|
||||
- Linux Python 3.11.18、Node 22.23.2 上运行 `PATH=<venv>/bin:$PATH python scripts/run_quality_gate.py --profile quick --skip-frontend-runtime`,通过。
|
||||
- 同步 staging `a63d85f27` 后,仅合并 Bug 历史相邻新增段落。对合并后的工作树再次跑仓内迁移与 PostgreSQL 合成用例在内的组合验证,28 项通过,TypeScript 检查通过。
|
||||
- 原 SQL、冻结归档、应用运行时代码均无改动。既有测试断言未改动。
|
||||
|
||||
## 缺口
|
||||
|
||||
- 生产脚本由产品负责人按受控流程执行,实际统计值仍无。无主体关联的旧独立合盘、浏览器导出及本地下载无法按档案计数。
|
||||
- 审计分组可能发生组合披露,发布任何实际计数前仍需审核。旧快照重新核验、缓存失效和产品行为变更留在本单范围之外。
|
||||
@@ -1,72 +0,0 @@
|
||||
# 生时纠正:P0 收尾——聚合统计脚本修订与旧产物检查清单(2026-11-16,Claude)
|
||||
|
||||
Bug 编号:BUG-1931。
|
||||
|
||||
## 背景
|
||||
|
||||
占星师 11-16 审了 #294 交付的只读统计脚本 `docs/operations/rect-p0-aggregate-20261116.sql`,指出五处问题。脚本还没有在任何含真实用户资料的库上执行过。本单把这五处改掉,并补一份脚本覆盖不到的「旧产物与消费入口」检查清单。
|
||||
|
||||
## 不做的事
|
||||
|
||||
- 不连接、不查询任何含真实用户资料的数据库;不导出用户明细。脚本只写不跑,由产品负责人在受控环境执行。
|
||||
- 不改任何运行时行为:不改 `chart-choice` 的 API、页面、存储读写,不改报告、年运、聊天。
|
||||
- 不删除、不改写原始出生资料或历史记录的任何迁移。
|
||||
- 不改 `docs/operations/rect-p0-aggregate-20261116.sql` 原文件(它已随证据包 A 发出)。新脚本另起文件名。
|
||||
- 不碰 `references/real_case_calibration/` 下的归档。
|
||||
|
||||
## 一、新脚本 `docs/operations/rect-p0-aggregate-20261116-v2.sql`
|
||||
|
||||
保持:只读、repeatable read 事务、只输出固定词表和计数、不选出任何出生资料、标识、邮箱、正文。
|
||||
|
||||
要改的五处:
|
||||
|
||||
1. **来源冲突不再被首个匹配吞掉。** 现在的 `category` 是一条 `CASE`,先命中哪条算哪条。改为对每条档案分别算出各来源特征的布尔列(旧答题、旧事件采纳、segment-v1、明确手选、#229 分盘选边、填报默认),再输出:
|
||||
- 各特征单独的计数;
|
||||
- 同时命中两个及以上特征的计数,单列一类 `conflict`,并按「手选 + 旧来源」「其他组合」分开;
|
||||
- 都没命中的 `unknown`。
|
||||
「明确手选」如果同一条档案的记录链上还有旧答题、旧事件或选边的痕迹,归入 `conflict`,不算独立更正。
|
||||
2. **`unknown` 单独成表。** 另出一张表,只给 `unknown` 档案按「有无关联历史记录」「有无回执」「`contract` 是否缺失」分组的计数。脚本注释写明:unknown 不等于安全,也不等于应撤回。
|
||||
3. **补上已改状态档案上的旧产物。** 现在只看 `birth_time_status in ('accepted','confirmed')` 的档案及其 `ready` 报告。新增一段:历史记录表里出现过旧来源(旧答题、旧事件采纳、segment-v1、选边)的档案,不论当前状态,统计其名下各类型报告的数量(按报告类型、按报告状态分组)。表名、字段以仓内迁移为准;查不到对应字段就在注释里写明「无此字段」,不要猜。
|
||||
4. **零和「小于 5」分开。** 输出两列:`has_any`(`yes`/`no`)和 `count_display`(0 显示 `0`,1–4 显示 `<5`,其余显示数字)。注释写明:这是内部受权审计用的版本;外发前需再做组合披露审查,不能称为匿名保证。同时去掉可由总计减分组反推小组的输出:有分组被显示为 `<5` 时,该表不输出总计行。
|
||||
5. **说明统计的是什么。** 文件头注释写清:统计的是执行时刻的档案状态和现存报告,不是历史采用次数,也不能证明某份报告生成时用了已撤销的规则。
|
||||
|
||||
## 二、合成数据测试
|
||||
|
||||
新增 `frontend/tests/rectification-p0-aggregate-v2-20261116.test.ts`(沿用 #294 `rectification-p0-evidence-20261116.test.ts` 的做法;若那里是解析 SQL 文本的静态检查,就在此基础上增加可执行的检查):
|
||||
|
||||
- 仓内已有可起本地数据库的测试设施时(参考 `frontend/tests/database-chart-choice-*.test.ts`),用**合成档案**灌入并执行新脚本,断言:
|
||||
- 手选 + 旧答题痕迹的档案进 `conflict`,不进 `explicit_manual_choice`;
|
||||
- 只有手选、无旧痕迹的档案进 `explicit_manual_choice`;
|
||||
- 状态已改回的档案上的旧报告被第 3 点那段数到;
|
||||
- 计数为 0 时 `has_any = no`、`count_display = 0`;计数为 3 时 `has_any = yes`、`count_display = <5`;
|
||||
- 存在 `<5` 分组的表没有总计行;
|
||||
- 输出中不含任何合成档案的出生日期、时间、标识。
|
||||
- 本地起不了数据库就保留静态检查,并在 PROGRESS 里写明哪些断言没有执行过,不要写成已验证。
|
||||
- 合成数据不得使用任何真实出生资料。
|
||||
|
||||
## 三、旧产物与消费入口检查清单
|
||||
|
||||
新建 `docs/research/rect-p0-artifact-checklist-20261116.md`。只盘点现状,不改行为。逐行给出:入口或产物、读的是什么(字段、函数、文件位置)、是否会读到旧校时结果、现有保护(测试名)、没有保护的写「无」。
|
||||
|
||||
至少覆盖:
|
||||
|
||||
- 长报告、年运、合盘(含旧的独立合盘)、聊天取数卡、星盘面板、导出文件、首页;
|
||||
- 各自的缓存:缓存键是什么,键里有没有出生时间来源或范围的版本;旧缓存在来源被撤销后会不会继续被读;
|
||||
- 已生成并存库的报告快照:有没有「已校正」之类的状态字段;重开旧报告读的是快照还是当前档案;
|
||||
- 用户已下载到本地的文件:写明服务器无法回收;
|
||||
- 模型工具:聊天里的工具能不能读到或写回出生时间。
|
||||
|
||||
清单末尾列出「发现的缺口」,每条一句话,不给修复方案,不改代码。
|
||||
|
||||
## 四、文档
|
||||
|
||||
- `docs/BUG_HISTORY.md` 新增 BUG-1931(只在自己那一节内编辑;不写任何姓名、出生资料、邮箱、ID)。状态写 `resolved` 的前提是第二节的可执行断言真的跑过;否则写 `investigating` 并说明。
|
||||
- `CHANGELOG.md` 加一行。
|
||||
- `docs/tasks/PROGRESS-rect-p0-wrapup-20261116.md`:做了什么、跑了哪些命令和结果、没做到的。
|
||||
|
||||
## 验收
|
||||
|
||||
- `PATH=<venv>/bin:$PATH python scripts/run_quality_gate.py --profile quick --skip-frontend-runtime` 通过;
|
||||
- `cd frontend && npx eslint .` 0 错误;新测试通过,前端全量测试不新增失败;
|
||||
- 原脚本 `rect-p0-aggregate-20261116.sql` 与 `references/real_case_calibration/` 无改动;
|
||||
- 没有任何运行时代码改动(diff 只含 SQL、测试、文档)。
|
||||
@@ -0,0 +1,80 @@
|
||||
# 生时纠正页面:讲清哪些方面受影响,并让用户自己选线前线后(2026-11-16,Claude)
|
||||
|
||||
Bug 编号:BUG-1936。关联 BUG-1890(#279)、BUG-1896(#292)、BUG-1925(#294)。
|
||||
|
||||
## 背景
|
||||
|
||||
#292 停掉问答后,生时纠正页面只剩「显示时间、选范围、看六张盘、用这个时间」,用户进来没有任何结果。产品负责人 11-16 的决定:
|
||||
|
||||
1. 页面要直接讲清:哪些方面不受时间范围影响,哪些方面会因为差几分钟而不同,分别差在哪条线上、线前线后各是什么。
|
||||
2. **允许用户自己选线前还是线后。** 这是用户自己的选择(按自己的做事风格判断),不是系统验证出来的结果。选了,报告和聊天就按那一边写;不确定,受影响的方面两版都读。
|
||||
3. 系统不推荐任何一边,不打分,不问事件题。
|
||||
|
||||
这是对 #279/#292「停用选边」的**有意调整**,只恢复「用户自选」这一条路;问答、事件打分、答题得出的时间范围继续停用。
|
||||
|
||||
## 不做的事
|
||||
|
||||
- 不改 `RECT_QUESTIONNAIRE_ENABLED`,不恢复问答(`questionnaire`、`adaptive`、`chart_answers`、`resumeRecordId`)和事件证据输入。`useAnswerWindow` 继续被拒绝。
|
||||
- 不调用 `scripts/chart_choice/astrologer.py`、`adaptive.py`、`interview.py`、`chart_questions.py` 的任何打分或选题。
|
||||
- 不显示票数、推荐、把握、概率、「更可能」「系统判断」之类的任何措辞;不显示「已纠正」「已校正」「已确认」。
|
||||
- 不改报告、年运的渲染代码(`scripts/report_render/` 不动)。聊天侧只复用已有的「两版都读」(`frontend/src/lib/chart-choice-both-versions.ts`),不新写提示词。
|
||||
- 不删除、不改写历史记录;不改 `references/real_case_calibration/`。
|
||||
- 不新造按钮、卡片样式:沿用页面现有的 `Card`、`Primary`、范围按钮、六张盘条形图、`ChooseStep` 的选项样式。不加提示性的小字副标题。
|
||||
|
||||
## 一、结果页讲清结论
|
||||
|
||||
在现有「按你填的 HH:MM」这一步(`defaultOnly` 的 `FinalStep`)和「当前使用」首页,把「现有信息不足以确认更准确的出生时间。」这句换成由数据生成的结论,放在六张盘上方:
|
||||
|
||||
- 范围内没有任何盘换座:`这个时间范围内六张盘都不变,可以直接用。`(已有的 `certain` 步骤保持不变。)
|
||||
- 有换座:分两行。
|
||||
- `不受影响:主盘。`(列出范围内不换座的那些盘的名称,用页面已有的盘名:主盘、婚恋、事业、钱财、日常、突变。)
|
||||
- `差几分钟就不同:婚恋、事业、钱财、日常、突变。`(列出会换座的。)
|
||||
- 六张盘每行现有文案 `狮子上升,范围内会换座(04:59:43 换)` 改成把两边都写出来:`04:59:43 之前巨蟹上升,之后狮子上升`。一个盘在范围内换座多于一次时,只写离所填时间最近的那一次,后面加 `等 N 处`。星座名用现有的中文映射,时刻格式沿用现有的。
|
||||
- 所填时间离最近的线不到 2 分钟时,在结论下加一行:`你填的 05:00 离 04:59:43 这条线只有 17 秒。`(秒数、分钟数按实际计算;1 分钟以上写「X 分 Y 秒」。)
|
||||
|
||||
所有句子由后端 packet 里已有的线和分盘星座生成;packet 缺「线前星座」时在 `scripts/chart_choice/service.py` 的线视图里补上(`Line.flips` 已有前后星座)。不改任何计算。
|
||||
|
||||
## 二、用户自选
|
||||
|
||||
在结果页「用 05:00」按钮旁加一个次级按钮 `自己选线前线后`(范围内没有换座线时不显示)。
|
||||
|
||||
流程复用已有的逐条线选边步骤(`ChooseStep` / v1 的 `runDecision` + `overrideSide`,或 v2 的 `RoundStep`,以哪个更容易去掉打分为准,在 PROGRESS 写明选了哪个):
|
||||
|
||||
1. 从离所填时间最近的线开始,一次一条线。每条线列出在这条线上换座的方面,每个方面给线前、线后两段说明(用 `scripts/chart_choice/readings.py` 现有的文字,不新写)。
|
||||
2. 每条线一个三选一:`线前`、`线后`、`不确定`。整条线选一次,不是每个方面各选一次(同一条线上的各方面在同一时刻一起换,分开选会自相矛盾)。
|
||||
3. 选了线前或线后:范围收到那一侧,继续问这一侧里剩下的线(如果有),直到这一段里没有线或用户选了「不确定」或点了 `就到这里`。
|
||||
4. 选「不确定」:这条线不收范围,这条线上换座的方面记入「两版都读」(现有 `both_versions` 字段),流程结束。
|
||||
5. 结束后到确认页:写明最终用的时间、选过的每条线和选的哪一边,以及 `这是你自己选的,可以随时改。`。保存按钮文案 `用 HH:MM`。
|
||||
|
||||
保存规则:
|
||||
|
||||
- 采用时刻:选定的那一段里的代表时刻,沿用现有 `representative_minute` 规则;所填时间本来就在选定段内时保持所填时间不变。
|
||||
- 来源链写明是用户自选:`source = user_choice`、`rule = user_override`,并新增 `declared_by_user: true` 和 `basis: self_choice_20261116`,与旧问答、旧事件采纳区分开。不写 `votes`,不写任何打分回执。
|
||||
- **原始填写的时间和原范围必须原样保留**在记录里(现有的申报字段不动);首页「当前使用」显示采用时刻、选定的范围,以及一行 `按你自己的选择`。提供 `改回我填的时间`(复用现有的恢复默认 `restore_default`)。
|
||||
- 出生时间状态不得升级为「已确认」一类;沿用现有 `accepted`。
|
||||
- 服务器重新计算线和代表时刻,不信任客户端传来的时刻或范围。
|
||||
- 接口:在 `/api/chart-choice/adopt` 现有 schema 上加一个明确的入口字段(建议 `selfChoice: true` + 每条线的选择列表),只有带这个字段的请求才走自选;不带的旧载荷(`overrideSide`、非空 `resolved`、`answers`、`chart_answers`、`resumeRecordId`、`useAnswerWindow`)继续按 #279/#292/#294 的方式被拒绝或走默认。**不要靠放开旧字段来实现。**
|
||||
|
||||
## 三、下游
|
||||
|
||||
- 聊天:采用时刻变了,照常按采用时刻排盘;`both_versions` 非空时现有「两版都读」逻辑照常生效。确认 `chartChoiceBothVersionsFromProvenance` 认得本单写出的来源(它要求 `source === "user_choice"`、`chosen_side`、`other_saved_at`);「不确定」发生在第一条线、没有选定任何一侧时,`chosen_side` 怎么写、`other_saved_at` 取哪一侧,按现有字段约束给出一个能让两版都读生效的写法,并写测试。
|
||||
- 报告、年运:不改代码。它们读采用时刻,本单后自然按用户选的那边生成。旧报告不重算、不标记;这一点写进 PROGRESS 的「已知边界」。
|
||||
|
||||
## 四、测试
|
||||
|
||||
- `frontend/tests/chart-choice-self-choice-20261116.test.tsx`:结论两行的生成(全不变、部分换座、多次换座、离线不到 2 分钟);自选按钮只在有线时出现;三选一流程(线前→下一条线、线后、不确定结束、就到这里);确认页文案;页面任何位置不出现「推荐」「更可能」「把握」「已纠正」「已校正」「已确认」和票数。
|
||||
- 接口测试:带 `selfChoice` 的请求保存后读回,原始时间和原范围未变、来源字段齐全、无 `votes`;不带 `selfChoice` 的旧载荷行为与现在完全一致(#294 的 `rectification-p0-evidence-20261116.test.ts` 与 `chart-choice-pause-20261115.test.tsx` 不删断言、照旧通过;确需调整的断言逐条在 PROGRESS 说明原因);客户端伪造时刻被服务器重算覆盖;重复提交两次结果相同。
|
||||
- `改回我填的时间` 后读回等于原始申报。
|
||||
- 「两版都读」:不确定的线上换座的方面进入 `both_versions`,聊天侧读取函数返回非空。
|
||||
- Python:`service.py` 线视图补字段的测试;既有 `tests/` 里 chart_choice 相关测试照旧通过。
|
||||
|
||||
## 五、文档
|
||||
|
||||
- `docs/BUG_HISTORY.md` 新增 BUG-1936,关联 BUG-1890、BUG-1896、BUG-1925,写明这是产品负责人对「停用选边」的有意调整及其范围(只在自己那一节内编辑;不写姓名、出生资料、邮箱、ID)。
|
||||
- `CHANGELOG.md` 一行;`docs/tasks/PROGRESS-rect-self-choice-20261116.md`。
|
||||
- `docs/research/rect-p0-evidence-20261116.md` 末尾追加一段「11-16 之后的变更」,说明用户自选入口的恢复及其来源标记,不改原有内容。
|
||||
|
||||
## 验收
|
||||
|
||||
- Python quick gate 通过;`cd frontend && npx eslint .` 0 错误;`npx tsc --noEmit` 通过;前端全量测试不新增失败。
|
||||
- 验收时会用测试账号在 staging 之前的本地构建上走一遍:结论两行、自选三条路径、改回原时间。
|
||||
@@ -1,108 +1,155 @@
|
||||
"use client";
|
||||
|
||||
import { PlusOutlined } from "@ant-design/icons";
|
||||
import { useGetIdentity } from "@refinedev/core";
|
||||
import { useTable } from "@refinedev/antd";
|
||||
import { List } from "@refinedev/antd";
|
||||
import { Alert, App, Space, Switch, Table, Typography } from "antd";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { App, Button, Form, Input, InputNumber, Modal, Select, Space, Switch, Table, Typography, type TableColumnsType } from "antd";
|
||||
import { useState } from "react";
|
||||
|
||||
import { flagIsOn, KNOWN_FEATURE_FLAGS, publishedFlag, type FeatureFlagVersion } from "@/lib/admin/known-feature-flags";
|
||||
import { adminRequestJson, type AdminIdentity } from "@/lib/admin/providers";
|
||||
import { formatAdminDate } from "./resource-table";
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
type Row = (typeof KNOWN_FEATURE_FLAGS)[number];
|
||||
type FeatureFlag = {
|
||||
id: string;
|
||||
flagKey: string;
|
||||
version: number;
|
||||
enabled: boolean;
|
||||
rolloutPercentage: number;
|
||||
config: Record<string, unknown>;
|
||||
status: string;
|
||||
createdAt: string;
|
||||
publishedAt: string | null;
|
||||
};
|
||||
|
||||
type FlagFilters = { q?: string; status?: string };
|
||||
|
||||
type FlagForm = {
|
||||
flagKey: string;
|
||||
enabled: boolean;
|
||||
rolloutPercentage: number;
|
||||
configJson: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* BUG-1937: the page used to be a free-form editor (new key, rollout percent,
|
||||
* config JSON, draft then publish). Only four keys are read by the product, so
|
||||
* it now lists those four with one switch each; flipping it saves and publishes.
|
||||
*/
|
||||
export default function FeatureFlagsManagement() {
|
||||
const { message } = App.useApp();
|
||||
const { data: identity } = useGetIdentity<AdminIdentity>();
|
||||
const [rows, setRows] = useState<FeatureFlagVersion[]>([]);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [savingKey, setSavingKey] = useState<string | null>(null);
|
||||
const table = useTable<FeatureFlag, { message: string; statusCode: number }, FlagFilters>({
|
||||
resource: "feature-flags",
|
||||
syncWithLocation: true,
|
||||
pagination: { pageSize: 20 },
|
||||
onSearch: ({ q, status }) => [
|
||||
{ field: "q", operator: "contains", value: q },
|
||||
{ field: "status", operator: "eq", value: status },
|
||||
],
|
||||
});
|
||||
const [form] = Form.useForm<FlagForm>();
|
||||
const [editing, setEditing] = useState<FeatureFlag | null>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [publishingId, setPublishingId] = useState<string | null>(null);
|
||||
const canWrite = Boolean(identity?.permissions.includes("ops.flags.write"));
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const payload = await adminRequestJson<{ data: FeatureFlagVersion[] }>("/api/admin/feature-flags?pageSize=100");
|
||||
setRows(payload.data);
|
||||
setLoadError(null);
|
||||
return payload.data;
|
||||
} catch (error) {
|
||||
setLoadError(error instanceof Error ? error.message : "读取失败");
|
||||
return null;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
function edit(item?: FeatureFlag) {
|
||||
setEditing(item ?? null);
|
||||
form.setFieldsValue(item ? {
|
||||
flagKey: item.flagKey,
|
||||
enabled: item.enabled,
|
||||
rolloutPercentage: item.rolloutPercentage,
|
||||
configJson: JSON.stringify(item.config, null, 2),
|
||||
} : {
|
||||
flagKey: "",
|
||||
enabled: false,
|
||||
rolloutPercentage: 0,
|
||||
configJson: "{}",
|
||||
});
|
||||
setOpen(true);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => void load(), 0);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [load]);
|
||||
|
||||
async function toggle(row: Row, on: boolean) {
|
||||
setSavingKey(row.key);
|
||||
async function save(values: FlagForm) {
|
||||
setSaving(true);
|
||||
try {
|
||||
const saved = await adminRequestJson<{ data: { id: string } }>("/api/admin/feature-flags", {
|
||||
let config: unknown;
|
||||
try {
|
||||
config = JSON.parse(values.configJson);
|
||||
} catch {
|
||||
throw new Error("配置 JSON 格式不正确");
|
||||
}
|
||||
await adminRequestJson("/api/admin/feature-flags", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
action: "save",
|
||||
id: null,
|
||||
flagKey: row.key,
|
||||
enabled: on,
|
||||
rolloutPercentage: on ? 100 : 0,
|
||||
config: publishedFlag(rows, row.key)?.config ?? {},
|
||||
expectedVersion: null,
|
||||
id: editing?.id ?? null,
|
||||
flagKey: values.flagKey.trim(),
|
||||
enabled: values.enabled,
|
||||
rolloutPercentage: values.rolloutPercentage,
|
||||
config,
|
||||
expectedVersion: editing?.version ?? null,
|
||||
}),
|
||||
});
|
||||
const draft = (await load())?.find((item) => item.id === saved.data.id);
|
||||
if (!draft) throw new Error("已保存,但没有读到新版本,请刷新后再试");
|
||||
await adminRequestJson("/api/admin/feature-flags", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ action: "publish", id: draft.id, expectedVersion: draft.version }),
|
||||
});
|
||||
await load();
|
||||
message.success(`${row.label}已${on ? "打开" : "关闭"},大约 15 秒后对用户生效`);
|
||||
message.success("功能开关草稿已保存");
|
||||
setOpen(false);
|
||||
await table.tableQuery.refetch();
|
||||
} catch (error) {
|
||||
message.error(`${row.label}没有改成:${error instanceof Error ? error.message : "请求失败"}`);
|
||||
await load();
|
||||
message.error(error instanceof Error ? error.message : "保存失败");
|
||||
} finally {
|
||||
setSavingKey(null);
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return <List title="功能开关" headerButtons={null}>
|
||||
async function publish(item: FeatureFlag) {
|
||||
setPublishingId(item.id);
|
||||
try {
|
||||
await adminRequestJson("/api/admin/feature-flags", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ action: "publish", id: item.id, expectedVersion: item.version }),
|
||||
});
|
||||
message.success("功能开关已发布");
|
||||
await table.tableQuery.refetch();
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : "发布失败");
|
||||
} finally {
|
||||
setPublishingId(null);
|
||||
}
|
||||
}
|
||||
|
||||
const columns: TableColumnsType<FeatureFlag> = [
|
||||
{ title: "开关", render: (_, item) => <Space direction="vertical" size={0}><Text strong>{item.flagKey}</Text><Text type="secondary">v{item.version}</Text></Space> },
|
||||
{ title: "状态", render: (_, item) => <Text>{item.status === "published" ? "已发布" : item.status === "draft" ? "草稿" : item.status} · {item.enabled ? "已开启" : "已关闭"}</Text> },
|
||||
{ title: "灰度", dataIndex: "rolloutPercentage", render: (value) => `${value}%` },
|
||||
{ title: "配置", dataIndex: "config", render: (value) => <Text code>{JSON.stringify(value)}</Text> },
|
||||
{ title: "发布时间", dataIndex: "publishedAt", render: formatAdminDate },
|
||||
{
|
||||
title: "操作",
|
||||
fixed: "right",
|
||||
render: (_, item) => <Space>{canWrite && <Button type="link" onClick={() => edit(item)}>编辑草稿</Button>}{canWrite && item.status !== "published" && <Button type="link" loading={publishingId === item.id} onClick={() => void publish(item)}>发布</Button>}</Space>,
|
||||
},
|
||||
];
|
||||
|
||||
return <List title="功能开关" headerButtons={canWrite ? <Button type="primary" icon={<PlusOutlined />} onClick={() => edit()}>新增开关</Button> : null}>
|
||||
<Space direction="vertical" size="middle" style={{ width: "100%" }}>
|
||||
<Text type="secondary">这里列的是产品里真正会生效的全部开关。拨一下就直接生效,不需要另外发布。</Text>
|
||||
{loadError && <Alert type="error" showIcon message={`开关状态没有读出来:${loadError}`} />}
|
||||
<Table<Row>
|
||||
rowKey="key"
|
||||
loading={loading}
|
||||
pagination={false}
|
||||
dataSource={[...KNOWN_FEATURE_FLAGS]}
|
||||
columns={[
|
||||
{ title: "功能", render: (_, row) => <Text strong>{row.label}</Text> },
|
||||
{
|
||||
title: "现在",
|
||||
render: (_, row) => (
|
||||
<Switch
|
||||
checked={flagIsOn(rows, row.key)}
|
||||
checkedChildren="开"
|
||||
unCheckedChildren="关"
|
||||
disabled={!canWrite || loading || Boolean(loadError) || (savingKey !== null && savingKey !== row.key)}
|
||||
loading={savingKey === row.key}
|
||||
onChange={(on) => void toggle(row, on)}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{ title: "关掉会怎样", render: (_, row) => row.off.replace(/^关掉后:/, "") },
|
||||
]}
|
||||
/>
|
||||
<Form {...table.searchFormProps} layout="inline" style={{ rowGap: 8 }}>
|
||||
<Form.Item name="q" label="搜索"><Input.Search allowClear placeholder="开关键" /></Form.Item>
|
||||
<Form.Item name="status" label="状态">
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="全部状态"
|
||||
style={{ minWidth: 140 }}
|
||||
options={["draft", "published", "retired"].map((value) => ({ value, label: value }))}
|
||||
/>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
<Table {...table.tableProps} columns={columns} rowKey="id" scroll={{ x: "max-content" }} />
|
||||
</Space>
|
||||
<Modal title={editing ? `编辑 ${editing.flagKey}` : "新增功能开关"} open={open} okText="保存草稿" cancelText="取消" confirmLoading={saving} onOk={() => form.submit()} onCancel={() => setOpen(false)} destroyOnHidden>
|
||||
<Form<FlagForm> form={form} layout="vertical" onFinish={save}>
|
||||
<Form.Item name="flagKey" label="开关键" rules={[{ required: true }, { pattern: /^[a-z][a-z0-9._-]{1,99}$/ }]}><Input disabled={Boolean(editing)} /></Form.Item>
|
||||
<Form.Item name="rolloutPercentage" label="灰度百分比" rules={[{ required: true }]}><InputNumber min={0} max={100} precision={0} style={{ width: "100%" }} /></Form.Item>
|
||||
<Form.Item name="enabled" label="启用" valuePropName="checked"><Switch /></Form.Item>
|
||||
<Form.Item name="configJson" label="配置 JSON" rules={[{ required: true }]}><Input.TextArea rows={6} spellCheck={false} /></Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</List>;
|
||||
}
|
||||
|
||||
@@ -37,7 +37,6 @@ import {
|
||||
launchCnyPerCredit,
|
||||
launchDefaultModel,
|
||||
launchFeaturePrice,
|
||||
launchFeatureCost,
|
||||
launchMargin,
|
||||
microusdToCny,
|
||||
microusdToCnyPerMillion,
|
||||
@@ -282,10 +281,9 @@ export default function LaunchSetup() {
|
||||
const edited = priceEdits[feature.key];
|
||||
const credits = edited ?? current?.creditCost ?? null;
|
||||
const metrics = usageByFeature.get(feature.key)?.metrics.costMicrousd;
|
||||
const picked = launchFeatureCost({ runs: metrics?.runs ?? 0, p95Microusd: metrics?.p95 ?? null, model: launchDefaultModel(models), featureKey: feature.key });
|
||||
const cost = microusdToCny(picked?.microusd ?? null, usdToCny);
|
||||
const cost = microusdToCny(metrics?.p95 ?? null, usdToCny);
|
||||
const sale = credits !== null && cnyPerCredit ? credits * cnyPerCredit.low : null;
|
||||
return { ...feature, current, credits, runs: metrics?.runs ?? 0, cost, costSource: picked?.source ?? null, sale, margin: launchMargin(sale, cost) };
|
||||
return { ...feature, current, credits, runs: metrics?.runs ?? 0, cost, sale, margin: launchMargin(sale, cost) };
|
||||
});
|
||||
const changedPrices = featureRows.filter((row) => row.credits !== null && row.credits !== row.current?.creditCost);
|
||||
|
||||
@@ -507,18 +505,8 @@ export default function LaunchSetup() {
|
||||
},
|
||||
{ title: "现在生效的", render: (_, row) => (row.current ? `${row.current.creditCost} 积分` : <Tag color="warning">还没有价格</Tag>) },
|
||||
{ title: "折合售价", render: (_, row) => yuan(row.sale) },
|
||||
{
|
||||
title: "每次成本",
|
||||
render: (_, row) => (row.cost === null
|
||||
? "先填模型单价"
|
||||
: row.costSource === "measured" ? `${row.cost.toFixed(3)} 元(实测)` : `约 ${row.cost.toFixed(3)} 元(估算)`),
|
||||
},
|
||||
{
|
||||
title: "毛利",
|
||||
render: (_, row) => (row.margin === null
|
||||
? (row.sale === null ? "先上架积分包" : "先填模型单价")
|
||||
: `${row.costSource === "estimate" ? "约 " : ""}${(row.margin * 100).toFixed(0)}%`),
|
||||
},
|
||||
{ title: "实测成本(近 30 天,95% 的请求不超过)", render: (_, row) => (row.runs ? yuan(row.cost, 3) : "还没有数据") },
|
||||
{ title: "毛利", render: (_, row) => (row.margin === null ? "算不出" : `${(row.margin * 100).toFixed(0)}%`) },
|
||||
]}
|
||||
/>
|
||||
<Space style={{ marginTop: 16 }} wrap>
|
||||
@@ -529,7 +517,7 @@ export default function LaunchSetup() {
|
||||
{cnyPerCredit
|
||||
? `折合售价按最划算的积分包算(每积分 ${cnyPerCredit.low.toFixed(3)} 元)。`
|
||||
: "还没有在售的积分包,折合售价和毛利暂时算不出。"}
|
||||
实测:近 30 天里 95% 的请求不超过这个数,只算填好模型单价之后的请求。估算:还没有实测时,按模型单价乘以一次成功生成通常用掉的字数算,失败重试不算在内。
|
||||
模型单价填好之前产生的请求,成本记的是 0。
|
||||
</Text>
|
||||
</Space>
|
||||
</Card>
|
||||
|
||||
@@ -181,7 +181,6 @@ export function ReplyQualityResource() {
|
||||
return (
|
||||
<Space direction="vertical" size="middle" style={{ width: "100%" }}>
|
||||
<StatsPanel />
|
||||
<Alert type="info" showIcon message="用户给某条回答点了「踩」,这里才会多一条记录,里面有那一轮的问题、回答和模型当时读到的内容。没人点踩时,下面的列表是空的。" />
|
||||
<ResourceTable<Record_>
|
||||
resource="reply-quality"
|
||||
title="对话质量记录"
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
/**
|
||||
* The feature flags the product actually reads (BUG-1937). The admin page lists
|
||||
* exactly these: a flag with any other key is read by no code, so creating one
|
||||
* changed nothing. A flag counts as on only when its published version is
|
||||
* enabled at 100% (src/lib/feature-flags.ts).
|
||||
*/
|
||||
export const KNOWN_FEATURE_FLAGS = [
|
||||
{ key: "product.report_center", label: "报告", off: "关掉后:用户不能生成个人报告和年运报告,合盘报告也不能新建。已生成的报告不受影响。" },
|
||||
{ key: "product.compatibility", label: "婚恋合盘", off: "关掉后:合盘入口隐藏,不能新建合盘报告,也不能生成合盘英文版。" },
|
||||
{ key: "product.rectification", label: "生时纠正", off: "关掉后:生时纠正入口隐藏,聊天里也不再引导纠正出生时间。" },
|
||||
{ key: "billing.subscriptions", label: "订阅套餐", off: "关掉后:购买页不显示订阅套餐,也不能下订阅订单;积分包照常卖。" },
|
||||
] as const;
|
||||
|
||||
export type KnownFeatureFlagKey = (typeof KNOWN_FEATURE_FLAGS)[number]["key"];
|
||||
|
||||
export type FeatureFlagVersion = Readonly<{
|
||||
id: string;
|
||||
flagKey: string;
|
||||
version: number;
|
||||
enabled: boolean;
|
||||
rolloutPercentage: number;
|
||||
config: Record<string, unknown>;
|
||||
status: string;
|
||||
}>;
|
||||
|
||||
/** The published version of one flag, or null when it was never published (the product then treats it as off). */
|
||||
export function publishedFlag(rows: readonly FeatureFlagVersion[], key: string): FeatureFlagVersion | null {
|
||||
return rows.find((row) => row.flagKey === key && row.status === "published") ?? null;
|
||||
}
|
||||
|
||||
/** Whether the product sees this flag as on: published, enabled, and rolled out to everyone. */
|
||||
export function flagIsOn(rows: readonly FeatureFlagVersion[], key: string): boolean {
|
||||
const flag = publishedFlag(rows, key);
|
||||
return Boolean(flag && flag.enabled && flag.rolloutPercentage === 100);
|
||||
}
|
||||
@@ -194,41 +194,3 @@ export function launchMargin(saleCny: number | null, costCny: number | null): nu
|
||||
if (saleCny === null || costCny === null || saleCny <= 0) return null;
|
||||
return (saleCny - costCny) / saleCny;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tokens one successful run typically uses, measured locally on 2026-11-16
|
||||
* (one sample each, DeepSeek flash). Used only for the estimate the launch page
|
||||
* shows while a feature has no settled usage with a price yet (BUG-1937).
|
||||
*/
|
||||
export const LAUNCH_TYPICAL_TOKENS: Readonly<Record<LaunchFeatureKey, { input: number; output: number }>> = {
|
||||
"chat.standard": { input: 100_000, output: 13_000 },
|
||||
"report.full": { input: 126_000, output: 33_000 },
|
||||
"annual.full": { input: 108_000, output: 86_000 },
|
||||
"synastry.full": { input: 360_000, output: 102_000 },
|
||||
};
|
||||
|
||||
/** Estimated cost of one run from the default model's unit prices. Null until both prices are filled. */
|
||||
export function launchEstimatedCostMicrousd(
|
||||
model: Pick<LaunchModel, "inputCostMicrousdPerMillion" | "outputCostMicrousdPerMillion"> | null,
|
||||
featureKey: LaunchFeatureKey,
|
||||
): number | null {
|
||||
if (!model || !(model.inputCostMicrousdPerMillion > 0) || !(model.outputCostMicrousdPerMillion > 0)) return null;
|
||||
const tokens = LAUNCH_TYPICAL_TOKENS[featureKey];
|
||||
return (tokens.input * model.inputCostMicrousdPerMillion + tokens.output * model.outputCostMicrousdPerMillion) / 1_000_000;
|
||||
}
|
||||
|
||||
/**
|
||||
* The cost the launch page shows for one feature: the measured 95th percentile
|
||||
* when the ledger has priced runs, otherwise the estimate. A measured value of 0
|
||||
* means the runs settled before the unit prices were filled, so it is not used.
|
||||
*/
|
||||
export function launchFeatureCost(input: Readonly<{
|
||||
runs: number;
|
||||
p95Microusd: number | null;
|
||||
model: Pick<LaunchModel, "inputCostMicrousdPerMillion" | "outputCostMicrousdPerMillion"> | null;
|
||||
featureKey: LaunchFeatureKey;
|
||||
}>): { microusd: number; source: "measured" | "estimate" } | null {
|
||||
if (input.runs > 0 && input.p95Microusd !== null && input.p95Microusd > 0) return { microusd: input.p95Microusd, source: "measured" };
|
||||
const estimate = launchEstimatedCostMicrousd(input.model, input.featureKey);
|
||||
return estimate === null ? null : { microusd: estimate, source: "estimate" };
|
||||
}
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
-- BUG-1935: the admin role had SELECT grants on these tables but no row-level
|
||||
-- security policy, so every admin read returned zero rows without an error
|
||||
-- (用量和成本、上线配置里的实测成本、订阅列表都是空的). Same cause as BUG-147.
|
||||
begin;
|
||||
|
||||
do $$
|
||||
declare
|
||||
t text;
|
||||
begin
|
||||
if exists (select 1 from pg_roles where rolname = 'admin_runtime') then
|
||||
foreach t in array array[
|
||||
'usage_ledger', 'usage_reservations', 'usage_events',
|
||||
'user_subscriptions', 'user_product_redemptions',
|
||||
'notification_templates', 'pricing_experiment_events'
|
||||
] loop
|
||||
if to_regclass('public.' || t) is not null then
|
||||
execute format('grant select on table public.%I to admin_runtime', t);
|
||||
execute format('drop policy if exists %I on public.%I', t || '_admin_read', t);
|
||||
execute format('create policy %I on public.%I for select to admin_runtime using (true)', t || '_admin_read', t);
|
||||
end if;
|
||||
end loop;
|
||||
end if;
|
||||
end;
|
||||
$$;
|
||||
|
||||
commit;
|
||||
@@ -1,65 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import test from "node:test";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { flagIsOn, KNOWN_FEATURE_FLAGS, publishedFlag, type FeatureFlagVersion } from "../src/lib/admin/known-feature-flags.ts";
|
||||
import { LAUNCH_FEATURES, launchEstimatedCostMicrousd, launchFeatureCost } from "../src/lib/admin/launch-setup.ts";
|
||||
|
||||
const source = (path: string) => readFileSync(fileURLToPath(new URL(`../${path}`, import.meta.url)), "utf8");
|
||||
const model = { inputCostMicrousdPerMillion: 100_000, outputCostMicrousdPerMillion: 400_000 };
|
||||
|
||||
test("the launch page estimates a cost while a feature has no priced usage (BUG-1937)", () => {
|
||||
// chat: 100k in × $0.10/M + 13k out × $0.40/M = 10,000 + 5,200 microusd
|
||||
assert.equal(launchEstimatedCostMicrousd(model, "chat.standard"), 15_200);
|
||||
assert.equal(launchEstimatedCostMicrousd(null, "chat.standard"), null);
|
||||
assert.equal(launchEstimatedCostMicrousd({ inputCostMicrousdPerMillion: 0, outputCostMicrousdPerMillion: 400_000 }, "chat.standard"), null);
|
||||
for (const feature of LAUNCH_FEATURES) assert.ok((launchEstimatedCostMicrousd(model, feature.key) ?? 0) > 0, feature.key);
|
||||
|
||||
assert.deepEqual(launchFeatureCost({ runs: 0, p95Microusd: null, model, featureKey: "chat.standard" }), { microusd: 15_200, source: "estimate" });
|
||||
assert.deepEqual(launchFeatureCost({ runs: 12, p95Microusd: 9_000, model, featureKey: "chat.standard" }), { microusd: 9_000, source: "measured" });
|
||||
// Runs settled before the unit prices were filled carry cost 0: not a measurement.
|
||||
assert.deepEqual(launchFeatureCost({ runs: 12, p95Microusd: 0, model, featureKey: "chat.standard" }), { microusd: 15_200, source: "estimate" });
|
||||
assert.equal(launchFeatureCost({ runs: 0, p95Microusd: null, model: null, featureKey: "chat.standard" }), null);
|
||||
|
||||
const page = source("src/components/admin/launch-setup.tsx");
|
||||
// BUG-1937 follow-up: two decimals showed 0.008 and 0.015 both as 0.01; the estimate uses three, like the measured value.
|
||||
assert.ok(page.includes("`约 ${row.cost.toFixed(3)} 元(估算)`"));
|
||||
assert.match(page, /(实测)/);
|
||||
assert.doesNotMatch(page, /row\.runs \? yuan\(row\.cost, 3\) : "还没有数据"/);
|
||||
});
|
||||
|
||||
test("the flags page lists exactly the flags the product reads, one switch each (BUG-1937)", () => {
|
||||
const read = new Set<string>();
|
||||
for (const file of ["src/app/api/payment/packages/route.ts", "src/app/api/payment/epay/create/route.ts"]) {
|
||||
for (const match of source(file).matchAll(/loadRuntimeFeatureFlags\(\["([a-z._]+)"\]\)/g)) read.add(match[1]!);
|
||||
}
|
||||
const used = new Set<string>();
|
||||
for (const file of [
|
||||
"src/app/api/reports/route.ts", "src/app/api/account/route.ts", "src/app/api/synastry-reports/route.ts", "src/app/api/product-access/route.ts",
|
||||
"src/lib/annual-report-server.ts", "src/lib/synastry-full-create.ts", "src/lib/rectification-in-chat-server.ts", "src/lib/chart-choice/route-support.ts",
|
||||
]) {
|
||||
for (const match of source(file).matchAll(/isProductEnabled\("([a-z_]+)"\)/g)) used.add(`product.${match[1]}`);
|
||||
}
|
||||
assert.deepEqual([...KNOWN_FEATURE_FLAGS.map((flag) => flag.key)].sort(), [...read, ...used].sort());
|
||||
|
||||
const page = source("src/components/admin/feature-flags-management.tsx");
|
||||
assert.doesNotMatch(page, /新增开关|配置 JSON|灰度百分比|编辑草稿/);
|
||||
assert.match(page, /rolloutPercentage: on \? 100 : 0/);
|
||||
|
||||
const rows: FeatureFlagVersion[] = [
|
||||
{ id: "a", flagKey: "product.compatibility", version: 1, enabled: true, rolloutPercentage: 100, config: {}, status: "retired" },
|
||||
{ id: "b", flagKey: "product.compatibility", version: 2, enabled: true, rolloutPercentage: 50, config: { x: 1 }, status: "published" },
|
||||
{ id: "c", flagKey: "product.report_center", version: 1, enabled: true, rolloutPercentage: 100, config: {}, status: "published" },
|
||||
{ id: "d", flagKey: "billing.subscriptions", version: 1, enabled: true, rolloutPercentage: 100, config: {}, status: "draft" },
|
||||
];
|
||||
assert.equal(publishedFlag(rows, "product.compatibility")?.id, "b");
|
||||
assert.equal(flagIsOn(rows, "product.compatibility"), false);
|
||||
assert.equal(flagIsOn(rows, "product.report_center"), true);
|
||||
assert.equal(flagIsOn(rows, "billing.subscriptions"), false);
|
||||
assert.equal(flagIsOn(rows, "product.rectification"), false);
|
||||
});
|
||||
|
||||
test("the quality records page says when a record appears (BUG-1937)", () => {
|
||||
assert.match(source("src/components/admin/reply-quality-resource.tsx"), /点了「踩」,这里才会多一条记录/);
|
||||
});
|
||||
@@ -1,36 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import test from "node:test";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const MIGRATIONS = fileURLToPath(new URL("../supabase/migrations/", import.meta.url));
|
||||
const NEW_MIGRATION = "20261116040000_admin_runtime_usage_read_policies.sql";
|
||||
|
||||
// BUG-1935: a table with row-level security and a SELECT grant to admin_runtime
|
||||
// but no admin_runtime policy reads as empty, with no error. Every such table
|
||||
// must have a policy, either written out or listed in the BUG-1935 migration.
|
||||
test("every RLS table the admin role may read has an admin read policy (BUG-1935)", () => {
|
||||
const granted = new Set<string>();
|
||||
const withPolicy = new Set<string>();
|
||||
const rls = new Set<string>();
|
||||
for (const file of readdirSync(MIGRATIONS).filter((name) => name.endsWith(".sql")).sort()) {
|
||||
const sql = readFileSync(join(MIGRATIONS, file), "utf8");
|
||||
for (const match of sql.matchAll(/grant\s+([a-z, ]+?)\s+on\s+(?:table\s+)?([a-z_.,\s]+?)\s+to\s+([a-z_, ]+);/gi)) {
|
||||
if (!match[3]!.includes("admin_runtime") || !/select/i.test(match[1]!)) continue;
|
||||
for (const table of match[2]!.split(",").map((name) => name.trim())) if (table.startsWith("public.")) granted.add(table);
|
||||
}
|
||||
for (const match of sql.matchAll(/create policy\s+\S+\s+on\s+(public\.[a-z_]+)([\s\S]*?);/gi)) {
|
||||
if (match[2]!.includes("admin_runtime")) withPolicy.add(match[1]!);
|
||||
}
|
||||
for (const match of sql.matchAll(/alter table\s+(?:if exists\s+)?(public\.[a-z_]+)\s+enable row level security/gi)) rls.add(match[1]!);
|
||||
}
|
||||
const listed = readFileSync(join(MIGRATIONS, NEW_MIGRATION), "utf8");
|
||||
for (const match of listed.matchAll(/'([a-z_]+)'/g)) withPolicy.add(`public.${match[1]}`);
|
||||
assert.match(listed, /create policy %I on public\.%I for select to admin_runtime using \(true\)/);
|
||||
const missing = [...granted].filter((table) => rls.has(table) && !withPolicy.has(table)).sort();
|
||||
assert.deepEqual(missing, []);
|
||||
for (const table of ["usage_ledger", "usage_reservations", "usage_events", "user_subscriptions"]) {
|
||||
assert.ok(listed.includes(`'${table}'`), table);
|
||||
}
|
||||
});
|
||||
@@ -1,187 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { readFileSync } from "node:fs";
|
||||
import test from "node:test";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { Client, type QueryResult } from "pg";
|
||||
import { runMigrations } from "../scripts/db-migrate.mjs";
|
||||
import { startPostgresFixture } from "./helpers/postgres-fixture.ts";
|
||||
|
||||
const script = readFileSync(
|
||||
new URL("../../docs/operations/rect-p0-aggregate-20261116-v2.sql", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
const docker = spawnSync("docker", ["version"], { stdio: "ignore" }).status === 0;
|
||||
|
||||
test("BUG-1931 aggregate SQL is one read-only repeatable-read transaction", () => {
|
||||
const sql = script.replace(/^--.*$/gm, "").trim();
|
||||
assert.match(sql, /^begin transaction isolation level repeatable read read only;/i);
|
||||
assert.match(sql, /\bcommit;$/i);
|
||||
assert.doesNotMatch(sql, /\b(?:insert|update|delete|create|alter|truncate|copy)\b/i);
|
||||
});
|
||||
|
||||
type AggregateRow = {
|
||||
metric: string;
|
||||
category: string | null;
|
||||
contract: string | null;
|
||||
source: string | null;
|
||||
rule: string | null;
|
||||
report_type: string | null;
|
||||
report_status: string | null;
|
||||
has_history: string | null;
|
||||
has_receipt: string | null;
|
||||
missing_contract: string | null;
|
||||
has_any: string;
|
||||
count_display: string;
|
||||
};
|
||||
|
||||
test("BUG-1931 audits source conflicts, unknowns and old reports with synthetic PostgreSQL data", {
|
||||
skip: !docker && "docker unavailable",
|
||||
}, async () => {
|
||||
const fixture = startPostgresFixture();
|
||||
const url = fixture.connectionUrl("schema_owner", "schema-owner-test-password");
|
||||
const db = new Client({ connectionString: url });
|
||||
// All times, identifiers and report content below are fictional.
|
||||
const date = "2042-02-03";
|
||||
const time = "03:04:05";
|
||||
const ownerIds: string[] = [];
|
||||
const recordIds: string[] = [];
|
||||
const customSource = "synthetic-provenance-outside-allowlist";
|
||||
const privateText = "synthetic-report-body";
|
||||
const reportId = randomUUID();
|
||||
|
||||
async function addProfile(provenance: Record<string, unknown> | null, accepted = true) {
|
||||
const id = randomUUID();
|
||||
ownerIds.push(id);
|
||||
fixture.psqlAs("identity_runtime", "identity-runtime-test-password",
|
||||
"insert into identity.users(id,name,email,email_verified) values ('" + id
|
||||
+ "','Fictional Aggregate Fixture','" + id + "@example.invalid',true)");
|
||||
const declaration = await db.query(
|
||||
"update public.profiles set birth_date=$2, reported_birth_time=$3, birth_time_status='reported' where id=$1",
|
||||
[id, date, time],
|
||||
);
|
||||
assert.equal(declaration.rowCount, 1);
|
||||
if (accepted) {
|
||||
await db.query(
|
||||
"update public.profiles set birth_time_status='accepted', active_birth_date=$2, active_birth_time=$3, "
|
||||
+ "active_birth_provenance=$4 where id=$1",
|
||||
[id, date, time, provenance],
|
||||
);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
async function addReceipt(ownerId: string, rule: string, detail: Record<string, unknown>) {
|
||||
const id = randomUUID();
|
||||
recordIds.push(id);
|
||||
await db.query(
|
||||
"insert into public.chart_choice_records "
|
||||
+ "(id,user_id,saved_date,saved_time,timezone_offset,chosen_side,rule,declaration,detail) "
|
||||
+ "values ($1,$2,$3,$4,0,'none',$5,'{}',$6)",
|
||||
[id, ownerId, date, time, rule, detail],
|
||||
);
|
||||
return id;
|
||||
}
|
||||
|
||||
try {
|
||||
const migration = await runMigrations({
|
||||
connectionString: url,
|
||||
migrationsDirectory: undefined,
|
||||
migrationsDirectories: ["../db/migrations", "../supabase/migrations"].map(
|
||||
(directory) => fileURLToPath(new URL(directory, import.meta.url)),
|
||||
),
|
||||
});
|
||||
assert.equal(migration, 0);
|
||||
await db.connect();
|
||||
|
||||
const manual = { contract: "chart-choice-v2", source: "user_choice", rule: "user_override" };
|
||||
const questionnaire = {
|
||||
contract: "chart-choice-v2", source: "user_choice_from_answers", rule: "chart_answers",
|
||||
};
|
||||
for (let index = 0; index < 5; index += 1) await addProfile(manual);
|
||||
for (let index = 0; index < 3; index += 1) {
|
||||
const id = await addProfile(manual);
|
||||
const recordId = await addReceipt(id, "chart_answers", { provenance: questionnaire });
|
||||
await db.query("update public.profiles set active_birth_provenance=$2 where id=$1",
|
||||
[id, { ...manual, record_id: recordId }]);
|
||||
await addProfile({ source: customSource });
|
||||
}
|
||||
const manualWithHistory = await addProfile(manual);
|
||||
await addReceipt(manualWithHistory, "evidence", { decision: { rule: "evidence", decided_by: "event" } });
|
||||
const withHistory = await addProfile({ contract: "chart-choice-v1", source: customSource });
|
||||
const unknownReceipt = await addReceipt(withHistory, "majority", { decision: { rule: "majority" } });
|
||||
await db.query("update public.profiles set active_birth_provenance=$2 where id=$1",
|
||||
[withHistory, { contract: "chart-choice-v1", source: customSource, record_id: unknownReceipt }]);
|
||||
const event = { contract: "chart-choice-v1", rule: "evidence", decided_by: "event" };
|
||||
const changed = await addProfile(event);
|
||||
await addReceipt(changed, "evidence", { decision: { rule: "evidence", decided_by: "event" } });
|
||||
await db.query(
|
||||
"update public.profiles set birth_time_status='reported', active_birth_time=null where id=$1",
|
||||
[changed],
|
||||
);
|
||||
await db.query(
|
||||
"insert into public.personal_reports (id,user_id,request_id,request_fingerprint,report_type,status,"
|
||||
+ "schema_version,presentation_mode,skill_snapshot_sha256,failure_code) "
|
||||
+ "values ($1,$2,$3,repeat('a',64),'annual_full','failed','annual_report.v1','default',"
|
||||
+ "repeat('b',64),'report_guard_rejected')",
|
||||
[reportId, changed, randomUUID()],
|
||||
);
|
||||
const unrelated = await addProfile(null, false);
|
||||
await db.query(
|
||||
"insert into public.synastry_reports (user_id,report,subject_low,subject_high) "
|
||||
+ "values ($1,$3,'self',$4),($1,$3,null,null),($2,$3,'self',$4)",
|
||||
[changed, unrelated, { preview: privateText }, randomUUID()],
|
||||
);
|
||||
|
||||
const result = await db.query<AggregateRow>(script);
|
||||
const results: QueryResult<AggregateRow>[] = Array.isArray(result) ? result : [result];
|
||||
const [begin, aggregate, commit] = results;
|
||||
assert.equal(begin.command, "BEGIN");
|
||||
assert.equal(commit.command, "COMMIT");
|
||||
assert.deepEqual(aggregate.fields.map((field) => field.name), [
|
||||
"metric", "category", "contract", "source", "rule", "report_type", "report_status",
|
||||
"has_history", "has_receipt", "missing_contract", "has_any", "count_display",
|
||||
]);
|
||||
const rows = aggregate.rows;
|
||||
const count = (match: Partial<AggregateRow>) => rows
|
||||
.filter((row) => Object.entries(match).every(([key, value]) => row[key as keyof AggregateRow] === value))
|
||||
.map(({ has_any, count_display }) => [has_any, count_display]);
|
||||
assert.deepEqual(count({ metric: "feature", category: "explicit_manual_choice" }), [["yes", "5"]]);
|
||||
assert.deepEqual(count({ metric: "feature", category: "old_questionnaire" }), [["yes", "<5"]]);
|
||||
assert.deepEqual(count({ metric: "feature", category: "old_event" }), [["yes", "<5"]]);
|
||||
assert.deepEqual(count({ metric: "feature", category: "conflict_manual_and_old" }), [["yes", "<5"]]);
|
||||
assert.deepEqual(count({ metric: "feature", category: "conflict_other" }), [["no", "0"]]);
|
||||
assert.deepEqual(count({ metric: "feature", category: "conflict" }), []);
|
||||
assert.deepEqual(count({ metric: "feature", category: "unknown" }), []);
|
||||
assert.deepEqual(count({
|
||||
metric: "unknown_breakdown", has_history: "no", has_receipt: "no", missing_contract: "yes",
|
||||
}), [["yes", "<5"]]);
|
||||
assert.deepEqual(count({
|
||||
metric: "unknown_breakdown", has_history: "yes", has_receipt: "yes", missing_contract: "no",
|
||||
}), [["yes", "<5"]]);
|
||||
assert.deepEqual(count({
|
||||
metric: "unknown_breakdown", has_history: "yes", has_receipt: "no", missing_contract: "yes",
|
||||
}), [["no", "0"]]);
|
||||
assert.deepEqual(count({
|
||||
metric: "reports_on_historical_sources", report_type: "annual_full", report_status: "failed",
|
||||
}), [["yes", "<5"]]);
|
||||
assert.deepEqual(count({
|
||||
metric: "reports_on_historical_sources", report_type: "legacy_synastry", report_status: "not_recorded",
|
||||
}), [["yes", "<5"]]);
|
||||
assert.deepEqual(count({
|
||||
metric: "ready_reports_on_retired", report_type: "annual_full", report_status: "ready",
|
||||
}), [["no", "0"]]);
|
||||
assert.ok(!rows.some((row) => row.metric === "total" || row.category === "total"));
|
||||
const output = JSON.stringify(rows);
|
||||
for (const privateValue of [date, time, ...ownerIds, ...recordIds, reportId, customSource, privateText]) {
|
||||
assert.equal(output.includes(privateValue), false, "aggregate leaked a fixture value");
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
await db.end();
|
||||
} finally {
|
||||
fixture.stop();
|
||||
}
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user