Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
27dcbd889e |
@@ -1,9 +1,5 @@
|
||||
# 印度占星 Skill 更新日志
|
||||
|
||||
## 2026-11-16 · 生时纠正 P0 复核统计修订
|
||||
|
||||
- BUG-1931(#296):新增聚合 SQL v2,补齐来源冲突、未知来源分组和按历史来源统计现存报告。附旧产物与消费入口检查清单。Skill 版本不变。
|
||||
|
||||
## 2026-11-16 — 生时纠正复跑逐臂核对并补齐 P0 证据
|
||||
|
||||
- 新增完整四臂比较、历史范围读回回归与只读聚合统计。占星 Skill 版本不变(BUG-1925)。
|
||||
|
||||
@@ -26035,38 +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 万),不含失败重试,只作估算。后台页面本会话无登录权限,未在真实页面上操作过。
|
||||
- 关联记录: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,117 @@
|
||||
# 生时纠正:按用途判断时间范围够不够用——绑定与扫描(后端,2026-11-16,Claude)
|
||||
|
||||
Bug 编号:BUG-1932。
|
||||
|
||||
## 背景
|
||||
|
||||
产品负责人 11-16 确认了新方向:生时纠正不再帮用户「找出准确分钟」,而是判断「用户给的时间范围够不够回答他现在问的事」。够就直接用整个范围;不够就指出范围内哪里会变、影响哪条结论。占星师 11-16 的回信确认这部分可以先上线,并指明沿用她 11-09 的用途区间方案。
|
||||
|
||||
那份方案已经在仓内,**先完整读完再动手**:
|
||||
|
||||
- 规范:`docs/tasks/assets/purpose-gate-20261109/README.md`
|
||||
- 分步计划:`docs/tasks/assets/purpose-gate-20261109/PLAN.md`
|
||||
- 状态合同参考实现与示例:同目录 `reference_gate.py`、`examples.json`
|
||||
|
||||
其中 Task 1(用途决策合同)已由 #186 完成,在 `scripts/rectification_purpose_gate/__init__.py`,目前没有任何生产入口读它。**本单做 PLAN 的 Task 2 和 Task 3:从真实计算结果构造评估事实,并扫描范围内的敏感界限。只做后端,不接任何入口。** Task 4、5(接口、页面、模型、持久化)是后面的单子。
|
||||
|
||||
## 不做的事
|
||||
|
||||
- 不接任何生产入口:不改 `frontend/`,不改 `scripts/chart_choice/service.py` 的对外行为,不改报告、年运、聊天。新模块只被新测试调用。
|
||||
- 不改评分:不动 `scripts/chart_choice/astrologer.py` 的 `score_minute`、`scan`,不动 `active_rectification_events.py::adjudicate_candidate_rows` 的阈值和 `can_apply` 语义。不要把 `score_minute` 当稳定性检测器。
|
||||
- 不重写大运:周期顺序和日期一律调用现有引擎函数(`active_rectification_event_engine.py` 里的 `_vimshottari_timeline`、`_narayana_periods`、`_narayana_antardasha_table` 或它们的公开入口)。需要对外可调用的入口就加薄包装,不复制算法。
|
||||
- 不改 `references/real_case_calibration/` 下的归档与冻结复跑脚本;`tests/test_rectification_reseal_round7_bug1809.py` 必须照旧通过。
|
||||
- 不改 `scripts/rectification_purpose_gate/__init__.py` 里已有的状态枚举和 `assess_use` 行为;只允许新增。
|
||||
- 不产生任何「校时准确率」「已找到出生时间」之类的输出字段。
|
||||
- 不查询含真实用户资料的数据库;测试只用合成输入或 `references/real_case_calibration/` 里已公开的人物。
|
||||
|
||||
## 一、移植候选差异合同
|
||||
|
||||
把占星师仓的 `scripts/active_rectification_candidates.py`(`build_candidate_difference_contract`,输出 groups、discriminators、dimension_sensitivity)移植为 `scripts/active_rectification_candidates.py`,连同她的测试 `tests/test_active_rectification_candidates.py`。源文件由 Claude 随本单放在分支的 `docs/tasks/assets/purpose-scan-20261116/` 下,文件头写明来源提交。
|
||||
|
||||
移植时只允许这几处改动,并在 PROGRESS 逐条列出:
|
||||
|
||||
1. **参数必须显式传入。** 她的默认是 `ayanamsa=raman`、`node_mode=true`,本站是 `raman`/`mean`。去掉 `request.get(..., 默认值)`,缺 `ayanamsa` 或 `node_mode` 直接报错,不沿用任何一方的默认。
|
||||
2. `boundary_time` 改名或加注:它是「新一组的首个采样点」,不是求解出的精确边界。精确边界由第三节的边界提供器给。
|
||||
3. 240 分钟上限保留为这个模块自己的限制;全天未知的范围由第三节分段调用,不在这里放宽。
|
||||
|
||||
其余算法不改。她的测试原样通过。
|
||||
|
||||
## 二、用途绑定(PLAN Task 2)
|
||||
|
||||
新建 `scripts/rectification_purpose_gate/scope.py`:
|
||||
|
||||
```python
|
||||
def build_scope_request(question: dict, original_input: dict, remaining_ranges: list,
|
||||
profiles: dict, evaluated_at: str) -> dict: ...
|
||||
def collect_scope_outputs(scope_request: dict, native_results: list) -> dict: ...
|
||||
```
|
||||
|
||||
字段按规范第三节和第六节。要点:
|
||||
|
||||
- `build_scope_request` 规范化用途并算出七个绑定指纹(`BINDING_KEYS`,已在合同模块里)。同输入指纹相同;问题主题、预测窗、输入修订号、参数、引擎版本、精度政策、候选集合任一项变化,对应指纹必须变。
|
||||
- `remaining_ranges` 是一组范围,可以不连续,可以跨午夜。不填补中间空隙,不取外包络,不取中点。端点一律转成带时区的时刻;时区或地点有歧义时返回多个明确分支或报错,不在循环里猜。
|
||||
- `collect_scope_outputs` 只消费已经算好的原生结果,自己不算任何大运。每条记录保留候选时刻、分支、参数、方法、状态、原始结果引用和依赖。缺的层写 `blocked`,不补 0;不适用的层不进 `required_layers`。
|
||||
- **用途精度政策 `purpose_policy_v1`**:一张冻结的表,把(主题,时间粒度)映射到所需的层和判定条件。先查仓内现有的问题路由有没有机器可读的层清单,有就引用它;没有就按下表建,并在文件里写明「产品约定,待占星师审核」:
|
||||
|
||||
| 主题 | 所需层(最少) |
|
||||
|---|---|
|
||||
| 事业 | D1、D10、A10、Vimshottari、Narayana |
|
||||
| 财富 | D1、D2、D11、Vimshottari、Narayana |
|
||||
| 婚恋 | D1、D9、UL、A7、Vimshottari、Narayana |
|
||||
| 整体结构(只问性格、格局) | D1、D9、月亮星宿 |
|
||||
|
||||
时间粒度取 `structure`(不问时间)、`year`、`month`、`day`。粒度决定应期边界偏移到什么程度算实质变化(见第三节)。政策版本号进绑定指纹。表里没有的主题返回 `insufficient_evidence` 所需的事实(政策缺失),不要自造宽松规则。
|
||||
|
||||
测试 `tests/test_rectification_purpose_binding.py`:PLAN Task 2 列的各条(指纹变化、缺层保留 blocked、只扫了一部分范围时 `domain_complete=false`、没有事件也能评估用途稳定性且历史证据为 `not_evaluated`、不连续范围不被合并)。
|
||||
|
||||
## 三、敏感界限扫描(PLAN Task 3)
|
||||
|
||||
新建 `scripts/rectification_purpose_gate/scan.py`:
|
||||
|
||||
```python
|
||||
def scan_scope(scope_request: dict, compute_at, boundary_providers: dict) -> dict: ...
|
||||
```
|
||||
|
||||
输出 `scan_state`(`policy_covered` / `sampled_only` / `incomplete`)、`per_layer_scan_receipts`、`output_envelopes`、`material_differences`、`stable_claim_ids`、`conditional_claim_ids`,能直接组装成 `assess_use` 的输入。
|
||||
|
||||
边界提供器,本单要给出的真实实现:
|
||||
|
||||
1. **分盘上升换座**:复用 `scripts/chart_choice/boundaries.py::find_lines`(它已按度数求解精确时刻)。所需分盘不在 `TRACKED_DIVISIONS` 里的(如 D3、D7、D11),用同一求解方法扩展,可以给 `find_lines` 传 `divisions` 参数,不要改它的默认值。
|
||||
2. **D1 上升、上升星宿、月亮星座与星宿**:同样按度数求解,不靠分钟网格。
|
||||
3. **Arudha(A1、A7、A10、UL)**:没有解析边界,用分钟网格发现变化后在相邻两点间二分到秒级,回执里写明「网格发现 + 二分」,最大未检查间隔写实际值。
|
||||
4. **大运边界**:对用途的预测窗,取范围内各候选时刻下相关 Vimshottari(到政策要求的层级)和 Narayana 周期的起止日期,给出每条边界的最早、最晚、并集、交集。提醒:出生时间差 1 分钟,Vimshottari 边界约移动 3.8 天,范围越宽包络越宽,这是预期结果,不是错误。
|
||||
|
||||
判定规则:
|
||||
|
||||
- 首尾相同但中间变过(A→B→A)必须检出;只有首尾样本、没有边界依据时只能给 `sampled_only`。
|
||||
- 应期比较不只比主星名:同名周期,边界跨过用户问的日期、月末或年末(按粒度)就是实质变化。并集只能叫「各候选的可能范围」;交集为空不生成共同窗口。
|
||||
- 相同的分数、相同的空值、相同的 `blocked` 都不产生稳定事实。
|
||||
- 与本次用途无关的层发生变化(例如问事业时 D60 变了)只记录,不影响本次结论。
|
||||
- 区分原因:`birth_time_sensitive` / `method_unresolved` / `missing_input` / `calculation_failure` / `scan_incomplete`。
|
||||
- 计算预算:`scan_scope` 接受一个预算参数(候选计算次数上限)。用完返回 `incomplete` 并写明未覆盖的区段,不得因为超时或用完预算而判稳定。
|
||||
- 引擎只接受到秒时,不声称排除了秒内变化;回执写明分辨率。
|
||||
|
||||
测试 `tests/test_rectification_purpose_scan.py`:
|
||||
|
||||
- 用确定性假函数验证扫描器本身:A→B→A;无边界提供器只有首尾样本得 `sampled_only`;给出界限后得到三段。
|
||||
- 规范第八节的 U01、U02、U03、U05、U07、U08、U09、U11、U12、U16,各一条,场景名写进用例名。
|
||||
- 真实引擎三例(用 `references/real_case_calibration/` 里的公开人物或合成出生输入):一个范围较宽但对所选用途稳定的例子;一个范围内跨已知分盘边界的例子;一个应期日期敏感的例子。每例把原始结果存成夹具,PROGRESS 里用人话写清「为什么这例是稳定/不稳定」,供人工核对。
|
||||
- 扫描结果经 `assess_use` 得到的状态与预期一致:稳定例 `scope_ready`,跨界例 `needs_refinement` 或 `conditional`。
|
||||
|
||||
## 四、命令行入口(只供人工核对)
|
||||
|
||||
`python -m scripts.rectification_purpose_gate --input <json>`:读一份合成或公开人物的输入(出生日期、范围、地点、时区、岁差、交点模式、主题、粒度、预测窗),输出完整评估对象的 JSON。不接 API。README 写在 `docs/research/rect-purpose-scan-20261116.md`,附三例真实引擎的输出摘要。
|
||||
|
||||
## 五、文档
|
||||
|
||||
- `docs/BUG_HISTORY.md` 新增 BUG-1932(只在自己那一节内编辑;不写姓名、出生资料、邮箱、ID)。
|
||||
- `CHANGELOG.md` 加一行。
|
||||
- `docs/tasks/PROGRESS-rect-purpose-scan-20261116.md`:逐节写做了什么、命令和结果、与她原模块的差异清单、没做到的。有哪条 U 场景没能在真实引擎上验证,写「未验证」,不要写成通过。
|
||||
|
||||
## 验收
|
||||
|
||||
- `PATH=<venv>/bin:$PATH python scripts/run_quality_gate.py --profile quick --skip-frontend-runtime` 通过;
|
||||
- 新增三个测试文件全部通过;`tests/test_rectification_purpose_gate.py`、`test_rectification_comparability_bug1801.py`、`test_rectification_api_can_apply_guard_bug1802.py`、`test_active_rectification_api.py`、`test_rectification_reseal_round7_bug1809.py` 照旧通过,没有删改旧断言;
|
||||
- `cd frontend && npx eslint .` 0 错误(本单不应有前端改动);
|
||||
- diff 不含 `frontend/`、`scripts/report_render/`、`references/real_case_calibration/` 的改动;`scripts/chart_choice/` 只允许 `boundaries.py` 的新增参数,默认行为不变;
|
||||
- 没有任何生产入口导入新模块(验收时会 grep)。
|
||||
@@ -0,0 +1,8 @@
|
||||
# 来源
|
||||
|
||||
两份文件原样取自占星师资料仓 `ea2a9d657451cd04615a3a7108dc92666dc8340c`:
|
||||
|
||||
- `scripts/active_rectification_candidates.py`
|
||||
- `tests/test_active_rectification_candidates.py`
|
||||
|
||||
文件名加了 `.upstream` 后缀,避免被测试收集。移植要求见 `docs/tasks/TASK-rect-purpose-scan-20261116.md` 第一节。
|
||||
@@ -0,0 +1,322 @@
|
||||
# /// script
|
||||
# requires-python = ">=3.11"
|
||||
# dependencies = []
|
||||
# ///
|
||||
# ─── How to run ───
|
||||
# .venv/bin/python -m pytest -q tests/test_active_rectification_candidates.py
|
||||
"""Sample candidate birth times and group them by material chart differences.
|
||||
|
||||
This module implements the "Candidate Difference Contract" (candidate-driven
|
||||
rectification plan Task 2). It never approves a birth time. It answers one
|
||||
question only: inside the user's uncertain interval, which minutes are
|
||||
materially the same chart, where do the material boundaries fall, and which
|
||||
technique dimensions actually discriminate between adjacent candidate groups.
|
||||
|
||||
Design rules:
|
||||
- Every sampled candidate stays inside the user interval (reversed or
|
||||
out-of-bounds intervals are rejected).
|
||||
- Adjacent samples with an identical material signature merge into one group.
|
||||
- Group boundaries are reported as discriminators with from/to values, so a
|
||||
reader can say "08:03 and 08:12 differ because D9 ascendant moves X -> Y".
|
||||
- All results are plain JSON-compatible dictionaries; no prose conclusions.
|
||||
- The shared native calculation path is reused (same as the event engine):
|
||||
domain_calculation_service.compute_chart + varga.calc_all_vargas +
|
||||
jaimini.calc_arudha_padas + dasha_analyzer.lon_to_nakshatra.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from collections.abc import Sequence
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Final, TypedDict
|
||||
from uuid import NAMESPACE_URL, uuid5
|
||||
|
||||
SCRIPTS = Path(__file__).resolve().parent
|
||||
if str(SCRIPTS) not in sys.path:
|
||||
sys.path.insert(0, str(SCRIPTS))
|
||||
|
||||
import domain_calculation_service # noqa: E402
|
||||
import dasha_analyzer # noqa: E402
|
||||
import jaimini # noqa: E402
|
||||
import narayana_dasha # noqa: E402
|
||||
import varga # noqa: E402
|
||||
|
||||
SCHEMA_VERSION: Final = "jyotish.active_rectification_candidates.v1"
|
||||
# Divisions whose ascendant sign we fingerprint. Classical local path is the
|
||||
# same production line the event engine uses for its evidence rows.
|
||||
RELEVANT_DIVISIONS: Final[tuple[int, ...]] = (2, 3, 4, 7, 9, 10, 11, 12, 24, 30, 60)
|
||||
# Arudha padas tracked as derived points: A1 = arudha lagna (self), A7 = spouse,
|
||||
# A10 = career visibility, UL = upapada (marriage visibility).
|
||||
TRACKED_ARUDHAS: Final[tuple[str, ...]] = ("A1", "A7", "A10", "UL")
|
||||
MAX_WINDOW_MINUTES: Final = 240
|
||||
MAX_SAMPLE_STEP: Final = 15
|
||||
SIGNS: Final = narayana_dasha.SIGNS
|
||||
|
||||
FINGERPRINT_DIMENSION_ORDER: Final = (
|
||||
"lagna_sign",
|
||||
"lagna_nakshatra",
|
||||
"moon_sign",
|
||||
"moon_nakshatra",
|
||||
"vimshottari_md_lord",
|
||||
*(f"varga_asc.D{division}" for division in RELEVANT_DIVISIONS),
|
||||
"arudha.A1",
|
||||
"arudha.A7",
|
||||
"arudha.A10",
|
||||
"arudha.UL",
|
||||
)
|
||||
|
||||
|
||||
def _sign_name(sign_index: int) -> str:
|
||||
return str(SIGNS[sign_index % 12])
|
||||
|
||||
|
||||
class CandidateDifferenceRequest(TypedDict):
|
||||
birth_date: str
|
||||
start_time: str
|
||||
end_time: str
|
||||
lat: float
|
||||
lon: float
|
||||
tz: float
|
||||
ayanamsa: str
|
||||
node_mode: str
|
||||
sample_step_minutes: int
|
||||
|
||||
|
||||
def _candidate_times(request: CandidateDifferenceRequest) -> list[datetime]:
|
||||
"""Return sampled candidate datetimes strictly inside the user interval."""
|
||||
birth_date = date.fromisoformat(request["birth_date"])
|
||||
try:
|
||||
start_time = time.fromisoformat(request["start_time"])
|
||||
end_time = time.fromisoformat(request["end_time"])
|
||||
except ValueError as exc:
|
||||
raise ValueError("candidate_times_invalid_format") from exc
|
||||
step = int(request.get("sample_step_minutes", 1))
|
||||
if step < 1 or step > MAX_SAMPLE_STEP:
|
||||
raise ValueError("candidate_sample_step_out_of_bounds")
|
||||
start = datetime.combine(birth_date, start_time)
|
||||
end = datetime.combine(birth_date, end_time)
|
||||
if end < start:
|
||||
raise ValueError("candidate_interval_reversed")
|
||||
total_minutes = int((end - start).total_seconds() // 60) + 1
|
||||
if total_minutes < 2:
|
||||
raise ValueError("candidate_interval_too_short")
|
||||
if total_minutes > MAX_WINDOW_MINUTES:
|
||||
raise ValueError("candidate_interval_out_of_bounds")
|
||||
sampled = [start + timedelta(minutes=offset) for offset in range(0, total_minutes, step)]
|
||||
if len(sampled) < 2:
|
||||
raise ValueError("candidate_sample_step_too_coarse")
|
||||
if sampled[-1] != end and (end - sampled[-1]).total_seconds() // 60 >= 1:
|
||||
# Keep the user-visible end minute as the final sample so the reported
|
||||
# contract always covers the declared interval edge.
|
||||
sampled.append(end)
|
||||
return sampled
|
||||
|
||||
|
||||
def _varga_chart(varga_results: dict, division: int) -> dict | None:
|
||||
return next(
|
||||
(chart for name, chart in varga_results.items() if name.startswith(f"D{division}_")),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def _material_signature(chart: dict, planet_longitudes: dict[str, float]) -> dict[str, str]:
|
||||
"""Compute the material chart fingerprint for one sampled candidate."""
|
||||
ascendant_longitude = float(chart["ascendant"]["lon"])
|
||||
ascendant_index = int(ascendant_longitude // 30)
|
||||
moon_longitude = float(planet_longitudes["Moon"])
|
||||
asc_nak = dasha_analyzer.lon_to_nakshatra(ascendant_longitude)
|
||||
moon_nak = dasha_analyzer.lon_to_nakshatra(moon_longitude)
|
||||
signature: dict[str, str] = {
|
||||
"lagna_sign": _sign_name(ascendant_index),
|
||||
"lagna_nakshatra": f"{asc_nak[0][0]} p{asc_nak[2]}",
|
||||
"moon_sign": _sign_name(int(moon_longitude // 30)),
|
||||
"moon_nakshatra": f"{moon_nak[0][0]} p{moon_nak[2]}",
|
||||
# Vimshottari Mahadasha lord is the Moon nakshatra lord.
|
||||
"vimshottari_md_lord": str(moon_nak[0][1]),
|
||||
}
|
||||
|
||||
varga_results = varga.calc_all_vargas(
|
||||
planet_longitudes,
|
||||
ascendant_longitude,
|
||||
divisions=list(RELEVANT_DIVISIONS),
|
||||
)
|
||||
for division in RELEVANT_DIVISIONS:
|
||||
dimension = f"varga_asc.D{division}"
|
||||
varga_chart = _varga_chart(varga_results, division)
|
||||
ascendant = varga_chart.get("Ascendant") if isinstance(varga_chart, dict) else None
|
||||
sign_index = ascendant.get("sign_idx") if isinstance(ascendant, dict) else None
|
||||
signature[dimension] = _sign_name(sign_index) if isinstance(sign_index, int) else "blocked"
|
||||
|
||||
arudha_result = jaimini.calc_arudha_padas(ascendant_index, planet_longitudes)
|
||||
padas = arudha_result.get("padas") if isinstance(arudha_result, dict) else None
|
||||
for key in TRACKED_ARUDHAS:
|
||||
pada = (padas or {}).get(key) if isinstance(padas, dict) else None
|
||||
sign_index = pada.get("sign_idx") if isinstance(pada, dict) else None
|
||||
signature[f"arudha.{key}"] = _sign_name(sign_index) if isinstance(sign_index, int) else "unavailable"
|
||||
|
||||
return signature
|
||||
|
||||
|
||||
def _compute_chart_for_candidate(request: CandidateDifferenceRequest, candidate_at: datetime) -> tuple[dict, dict[str, float]]:
|
||||
chart = domain_calculation_service.compute_chart({
|
||||
"year": candidate_at.year,
|
||||
"month": candidate_at.month,
|
||||
"day": candidate_at.day,
|
||||
"hour": candidate_at.hour,
|
||||
"minute": candidate_at.minute,
|
||||
"lat": request["lat"],
|
||||
"lon": request["lon"],
|
||||
"tz": request["tz"],
|
||||
"ayanamsa": request.get("ayanamsa", "raman"),
|
||||
"node_mode": request.get("node_mode", "true"),
|
||||
})
|
||||
planet_longitudes = {
|
||||
name: float(data["lon"])
|
||||
for name, data in chart.get("planets", {}).items()
|
||||
if isinstance(data, dict) and isinstance(data.get("lon"), int | float)
|
||||
}
|
||||
if "Moon" not in planet_longitudes:
|
||||
raise ValueError("candidate_chart_missing_moon")
|
||||
return chart, planet_longitudes
|
||||
|
||||
|
||||
def _merge_signature_groups(rows: Sequence[tuple[datetime, dict[str, str]]]) -> list[dict]:
|
||||
groups: list[dict] = []
|
||||
for candidate_at, signature in rows:
|
||||
if groups and groups[-1]["signature"] == signature:
|
||||
group = groups[-1]
|
||||
group["end_time"] = candidate_at.strftime("%H:%M")
|
||||
group["width_minutes"] = _width_minutes(group["start_time"], group["end_time"])
|
||||
group["sample_count"] += 1
|
||||
continue
|
||||
groups.append({
|
||||
"group_id": f"g{len(groups) + 1}",
|
||||
"start_time": candidate_at.strftime("%H:%M"),
|
||||
"end_time": candidate_at.strftime("%H:%M"),
|
||||
"representative_time": candidate_at.strftime("%H:%M"),
|
||||
"width_minutes": 1,
|
||||
"sample_count": 1,
|
||||
"signature": dict(signature),
|
||||
})
|
||||
for group in groups:
|
||||
group["signature"] = {key: group["signature"][key] for key in FINGERPRINT_DIMENSION_ORDER if key in group["signature"]}
|
||||
return groups
|
||||
|
||||
|
||||
def _width_minutes(start_time: str, end_time: str) -> int:
|
||||
start = datetime.strptime(start_time, "%H:%M")
|
||||
end = datetime.strptime(end_time, "%H:%M")
|
||||
return int((end - start).total_seconds() // 60) + 1
|
||||
|
||||
|
||||
def _build_discriminators(groups: Sequence[dict]) -> list[dict]:
|
||||
discriminators: list[dict] = []
|
||||
for previous, current in zip(groups, groups[1:]):
|
||||
changed: list[dict[str, str]] = []
|
||||
stable_dimensions: list[str] = []
|
||||
for dimension, current_value in current["signature"].items():
|
||||
previous_value = previous["signature"].get(dimension)
|
||||
if previous_value == current_value:
|
||||
stable_dimensions.append(dimension)
|
||||
else:
|
||||
changed.append({
|
||||
"dimension": dimension,
|
||||
"from": previous_value,
|
||||
"to": current_value,
|
||||
})
|
||||
discriminators.append({
|
||||
"boundary_time": current["start_time"],
|
||||
"from_group": previous["group_id"],
|
||||
"to_group": current["group_id"],
|
||||
"changed_dimensions": changed,
|
||||
"stable_dimensions": sorted(stable_dimensions),
|
||||
})
|
||||
return discriminators
|
||||
|
||||
|
||||
def _build_dimension_sensitivity(groups: Sequence[dict]) -> dict:
|
||||
dimensions = FINGERPRINT_DIMENSION_ORDER if groups else ()
|
||||
rows: dict[str, dict] = {}
|
||||
for dimension in dimensions:
|
||||
values: list[str] = []
|
||||
for group in groups:
|
||||
value = group["signature"].get(dimension)
|
||||
if value is not None and value not in values:
|
||||
values.append(value)
|
||||
changed = len(values) > 1
|
||||
rows[dimension] = {
|
||||
"values": values,
|
||||
"distinct_value_count": len(values),
|
||||
"group_count": len(groups),
|
||||
"kind": "sensitive" if changed else "stable",
|
||||
"usable_discriminator": changed,
|
||||
}
|
||||
ranking = sorted(
|
||||
(dimension for dimension in dimensions if rows[dimension]["usable_discriminator"]),
|
||||
key=lambda dimension: (-rows[dimension]["distinct_value_count"], dimension),
|
||||
)
|
||||
return {"dimensions": rows, "ranking": ranking}
|
||||
|
||||
|
||||
def _adapter_status(groups: Sequence[dict]) -> dict:
|
||||
blocked_layers: list[str] = []
|
||||
for group in groups:
|
||||
for dimension, value in group["signature"].items():
|
||||
if value in {"blocked", "unavailable"} and dimension not in blocked_layers:
|
||||
blocked_layers.append(dimension)
|
||||
return {
|
||||
"native_calculation": "available",
|
||||
"blocked_layers": sorted(blocked_layers),
|
||||
"note": "Layers listed in blocked_layers could not be computed and never count as evidence.",
|
||||
}
|
||||
|
||||
|
||||
def build_candidate_difference_contract(request: CandidateDifferenceRequest) -> dict:
|
||||
"""Sample candidate times and return groups plus discriminators (no approval)."""
|
||||
sampled = _candidate_times(request)
|
||||
rows: list[tuple[datetime, dict[str, str]]] = []
|
||||
for candidate_at in sampled:
|
||||
chart, planet_longitudes = _compute_chart_for_candidate(request, candidate_at)
|
||||
rows.append((candidate_at, _material_signature(chart, planet_longitudes)))
|
||||
|
||||
groups = _merge_signature_groups(rows)
|
||||
discriminators = _build_discriminators(groups)
|
||||
sensitivity = _build_dimension_sensitivity(groups)
|
||||
fingerprint = (
|
||||
f"{request['birth_date']}|{request['start_time']}|{request['end_time']}|"
|
||||
f"{request['lat']}|{request['lon']}|{request['tz']}|"
|
||||
f"{request.get('ayanamsa', 'raman')}|{request.get('node_mode', 'true')}|"
|
||||
f"{request.get('sample_step_minutes', 1)}"
|
||||
)
|
||||
return {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"contract_id": str(uuid5(NAMESPACE_URL, f"{SCHEMA_VERSION}:{fingerprint}")),
|
||||
"request_profile": {
|
||||
"birth_date": request["birth_date"],
|
||||
"start_time": request["start_time"],
|
||||
"end_time": request["end_time"],
|
||||
"lat": request["lat"],
|
||||
"lon": request["lon"],
|
||||
"tz": request["tz"],
|
||||
"ayanamsa": request.get("ayanamsa", "raman"),
|
||||
"node_mode": request.get("node_mode", "true"),
|
||||
"sample_step_minutes": int(request.get("sample_step_minutes", 1)),
|
||||
},
|
||||
"sample": {
|
||||
"candidate_count": len(sampled),
|
||||
"first_candidate_time": sampled[0].strftime("%H:%M"),
|
||||
"last_candidate_time": sampled[-1].strftime("%H:%M"),
|
||||
"all_candidates_within_interval": True,
|
||||
},
|
||||
"groups": groups,
|
||||
"discriminators": discriminators,
|
||||
"dimension_sensitivity": sensitivity,
|
||||
"adapter_status": _adapter_status(groups),
|
||||
"status": "candidate_groups_only",
|
||||
"claim_boundary": (
|
||||
"Candidate difference contract only; it shows where material chart "
|
||||
"changes fall inside the uncertain interval and cannot approve a birth time."
|
||||
),
|
||||
}
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
SCRIPTS = Path(__file__).resolve().parents[1] / "scripts"
|
||||
if str(SCRIPTS) not in sys.path:
|
||||
sys.path.insert(0, str(SCRIPTS))
|
||||
|
||||
import active_rectification_candidates as candidates # noqa: E402
|
||||
from jyotish_api_server import BadRequest, JyotishAPIHandler # noqa: E402
|
||||
|
||||
|
||||
def _handler() -> JyotishAPIHandler:
|
||||
return JyotishAPIHandler.__new__(JyotishAPIHandler)
|
||||
|
||||
|
||||
def _base_request(**overrides) -> dict:
|
||||
request = {
|
||||
"birth_date": "2000-01-01",
|
||||
"start_time": "08:00",
|
||||
"end_time": "08:03",
|
||||
"lat": 31.2304,
|
||||
"lon": 121.4737,
|
||||
"tz": 8,
|
||||
"ayanamsa": "raman",
|
||||
"node_mode": "true",
|
||||
"sample_step_minutes": 1,
|
||||
}
|
||||
request.update(overrides)
|
||||
return request
|
||||
|
||||
|
||||
def test_rejects_reversed_interval() -> None:
|
||||
with pytest.raises(ValueError, match="candidate_interval_reversed"):
|
||||
candidates.build_candidate_difference_contract(
|
||||
_base_request(start_time="08:05", end_time="08:00")
|
||||
)
|
||||
|
||||
|
||||
def test_rejects_out_of_bounds_interval() -> None:
|
||||
with pytest.raises(ValueError, match="candidate_interval_out_of_bounds"):
|
||||
candidates.build_candidate_difference_contract(
|
||||
_base_request(start_time="08:00", end_time="12:00")
|
||||
)
|
||||
|
||||
|
||||
def test_rejects_single_minute_window() -> None:
|
||||
with pytest.raises(ValueError, match="candidate_interval_too_short"):
|
||||
candidates.build_candidate_difference_contract(
|
||||
_base_request(start_time="08:00", end_time="08:00")
|
||||
)
|
||||
|
||||
|
||||
def test_rejects_out_of_bounds_sample_step() -> None:
|
||||
with pytest.raises(ValueError, match="candidate_sample_step_out_of_bounds"):
|
||||
candidates.build_candidate_difference_contract(
|
||||
_base_request(sample_step_minutes=16)
|
||||
)
|
||||
|
||||
|
||||
def test_rejects_step_coarser_than_interval() -> None:
|
||||
with pytest.raises(ValueError, match="candidate_sample_step_too_coarse"):
|
||||
candidates.build_candidate_difference_contract(
|
||||
_base_request(start_time="08:00", end_time="08:02", sample_step_minutes=5)
|
||||
)
|
||||
|
||||
|
||||
def test_groups_are_contiguous_and_every_candidate_stays_inside_interval() -> None:
|
||||
result = candidates.build_candidate_difference_contract(
|
||||
_base_request(start_time="08:00", end_time="08:04")
|
||||
)
|
||||
groups = result["groups"]
|
||||
assert len(groups) >= 1
|
||||
assert result["sample"]["first_candidate_time"] == "08:00"
|
||||
assert result["sample"]["last_candidate_time"] == "08:04"
|
||||
assert result["sample"]["all_candidates_within_interval"] is True
|
||||
assert result["sample"]["candidate_count"] == 5
|
||||
# Groups must tile the sampled range without gaps or overlaps.
|
||||
total_samples = sum(int(group["sample_count"]) for group in groups)
|
||||
assert total_samples == result["sample"]["candidate_count"]
|
||||
for index, group in enumerate(groups):
|
||||
if index == 0:
|
||||
continue
|
||||
previous = groups[index - 1]
|
||||
assert group["start_time"] > previous["end_time"]
|
||||
assert group["group_id"].startswith("g")
|
||||
assert group["representative_time"]
|
||||
assert group["width_minutes"] >= 1
|
||||
assert int(group["sample_count"]) >= 1
|
||||
assert group["status"] if False else True
|
||||
|
||||
|
||||
def test_members_of_one_group_share_an_identical_material_signature() -> None:
|
||||
result = candidates.build_candidate_difference_contract(
|
||||
_base_request(start_time="08:00", end_time="08:04")
|
||||
)
|
||||
for group in result["groups"]:
|
||||
signature = group["signature"]
|
||||
for dimension in (
|
||||
"lagna_sign",
|
||||
"moon_nakshatra",
|
||||
"vimshottari_md_lord",
|
||||
"varga_asc.D9",
|
||||
"varga_asc.D60",
|
||||
"arudha.A1",
|
||||
"arudha.A10",
|
||||
"arudha.UL",
|
||||
):
|
||||
assert dimension in signature
|
||||
assert signature["varga_asc.D9"] not in {"blocked", "unavailable"}
|
||||
assert signature["vimshottari_md_lord"]
|
||||
|
||||
|
||||
def test_discriminators_report_material_boundaries_with_from_to_values() -> None:
|
||||
result = candidates.build_candidate_difference_contract(
|
||||
_base_request(start_time="08:00", end_time="08:04")
|
||||
)
|
||||
groups = result["groups"]
|
||||
discriminators = result["discriminators"]
|
||||
assert len(discriminators) == len(groups) - 1
|
||||
for discriminator in discriminators:
|
||||
to_group = next(group for group in groups if group["group_id"] == discriminator["to_group"])
|
||||
from_group = next(group for group in groups if group["group_id"] == discriminator["from_group"])
|
||||
assert discriminator["boundary_time"] == to_group["start_time"]
|
||||
assert from_group["end_time"] < to_group["start_time"]
|
||||
assert discriminator["changed_dimensions"], "adjacent groups must differ somewhere"
|
||||
for change in discriminator["changed_dimensions"]:
|
||||
assert change["from"] != change["to"]
|
||||
assert change["dimension"] in candidates.FINGERPRINT_DIMENSION_ORDER
|
||||
for dimension in discriminator["stable_dimensions"]:
|
||||
assert from_group["signature"][dimension] == to_group["signature"][dimension]
|
||||
|
||||
|
||||
def test_dimension_sensitivity_marks_usable_discriminators() -> None:
|
||||
result = candidates.build_candidate_difference_contract(
|
||||
_base_request(start_time="08:00", end_time="08:04")
|
||||
)
|
||||
sensitivity = result["dimension_sensitivity"]
|
||||
assert "dimensions" in sensitivity and "ranking" in sensitivity
|
||||
rows = sensitivity["dimensions"]
|
||||
for dimension, row in rows.items():
|
||||
assert row["kind"] in {"stable", "sensitive"}
|
||||
assert row["usable_discriminator"] == (row["distinct_value_count"] > 1)
|
||||
for dimension in sensitivity["ranking"]:
|
||||
assert rows[dimension]["usable_discriminator"] is True
|
||||
for dimension in candidates.FINGERPRINT_DIMENSION_ORDER:
|
||||
assert dimension in rows
|
||||
|
||||
|
||||
def test_contract_is_deterministic_for_identical_input() -> None:
|
||||
first = candidates.build_candidate_difference_contract(
|
||||
_base_request(start_time="08:00", end_time="08:01")
|
||||
)
|
||||
second = candidates.build_candidate_difference_contract(
|
||||
_base_request(start_time="08:00", end_time="08:01")
|
||||
)
|
||||
assert first["contract_id"] == second["contract_id"]
|
||||
assert first["groups"] == second["groups"]
|
||||
assert first["discriminators"] == second["discriminators"]
|
||||
|
||||
|
||||
def test_wide_window_finds_material_changes_and_keeps_boundary() -> None:
|
||||
result = candidates.build_candidate_difference_contract(
|
||||
_base_request(start_time="04:00", end_time="06:00", sample_step_minutes=10)
|
||||
)
|
||||
assert result["sample"]["candidate_count"] == 13
|
||||
assert len(result["groups"]) >= 2, "rising vargas must produce a boundary in two hours"
|
||||
assert result["dimension_sensitivity"]["ranking"], "at least one dimension must discriminate"
|
||||
assert result["adapter_status"]["native_calculation"] == "available"
|
||||
assert result["status"] == "candidate_groups_only"
|
||||
assert "cannot approve a birth time" in result["claim_boundary"]
|
||||
|
||||
|
||||
def test_api_handler_exposes_candidate_contract() -> None:
|
||||
result = _handler()._compute_active_rectification_candidates(
|
||||
{
|
||||
"birth_date": "2000-01-01",
|
||||
"start_time": "08:00",
|
||||
"end_time": "08:04",
|
||||
"lat": 31.2304,
|
||||
"lon": 121.4737,
|
||||
"tz": 8,
|
||||
"ayanamsa": "raman",
|
||||
}
|
||||
)
|
||||
assert result["success"] is True
|
||||
assert result["endpoint"] == "active_rectification_candidates"
|
||||
assert result["schema_version"] == candidates.SCHEMA_VERSION
|
||||
assert result["request_profile"]["ayanamsa"] == "raman"
|
||||
assert result["groups"]
|
||||
assert result["claim_boundary"]
|
||||
|
||||
|
||||
def test_api_handler_rejects_reversed_interval() -> None:
|
||||
with pytest.raises(BadRequest):
|
||||
_handler()._compute_active_rectification_candidates(
|
||||
{
|
||||
"birth_date": "2000-01-01",
|
||||
"start_time": "08:05",
|
||||
"end_time": "08:00",
|
||||
"lat": 31.2304,
|
||||
"lon": 121.4737,
|
||||
"tz": 8,
|
||||
"ayanamsa": "raman",
|
||||
}
|
||||
)
|
||||
@@ -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(2)} 元(估算)`),
|
||||
},
|
||||
{
|
||||
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,64 +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");
|
||||
assert.match(page, /(估算)/);
|
||||
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