Skip to content
MSO CloudDocumentation

ADR 0060 — Self-learning seams: labels, reward, served champion, lineage, eval gate

On this page
  • Status: Accepted (2026-11-07, operator). Per-seam build status sits in each seam.
  • Date: 2026-11-07
  • Owners: Platform / decision-intelligence (packages/metrics, packages/actions, packages/platform-contract); S5 lands through the AI work packages (packages/ai).
  • Related: ADR 0004 (off-take loop), ADR 0009 (causal service, deferred by this ADR, not superseded), ADR 0010 (RLS roles, outbox), ADR 0025 (PCNQ), ADR 0026 (metric layer), ADR 0027 (declared conversion), ADR 0053 (loop console), ADR 0057 (alert workflows); §60, §64, §65, §66, §82, §117, §171.
  • Evidence: every path:line below was read at commit eb676254 on 2026-11-07.

Context#

The loop records decisions: append-only decision_episodes with selection propensity and receipt hash (packages/schema/src/tables/mso-episodes.ts:169, :266, :293; trigger packages/schema/sql/append-only-guards.sql:78), replay as a verify:rls leg (packages/metrics/src/decision-replay.ts:295, package.json:58), OPE that refuses below ESS 30 (packages/metrics/src/ope.ts:72, :232), owner-only promote and rollback (apps/web/src/server/routers/offtake.ts:2112, :2149). Evidence levels L3–L5 are beta and their missing pieces are listed in docs/status.md:138-146. It does not learn from outcomes yet:

# Gap Evidence
G1 The lever posterior is fit on correlation, not reward. fitPolicyModels reads offtake_models.per_lever; outcomes enter only as a count that shrinks variance, and the count includes unconfirmed outcomes although outcome_confirmed is the only event learning may read. Rewards are already written. packages/metrics/src/policy-loop.ts:159, :182, :203-210, :302-313; mso-episodes.ts:79-80; reward writes packages/metrics/src/offtake-loop.ts:1744, :3193, :4669
G2 The champion config is not served. The scan ranks with defaults; only the evaluation path passes a config. offtake-loop.ts:906-912 vs :5332-5337; packages/metrics/src/playbook-stats-rank.ts:411-417
G3 The 10 % holdout is a payload literal. MSO approve inserts approved commands directly; arms are assigned only inside proposeAction; observed_lift_bp has one writer, the sample generator. apps/web/src/server/routers/offtake.ts:1005, :1017; packages/actions/src/index.ts:290-291, :359-369; scripts/generate-sample-data.ts:1145
G4 Few human labels. alert_events.acknowledged_at has two writers, neither a person acting on the alert; brief bullets and chat answers carry no reaction. packages/schema/src/tables/actions.ts:109-110; apps/web/src/server/routers/offtake.ts:829; scripts/data-maintenance/retire-platform-rules-from-org-alerts.ts:52; packages/schema/src/tables/briefings.ts:19-45; packages/schema/src/tables/chat.ts:86-110
G5 Feedback weight reaches one path. weights is optional; only the dataset collector reads it; the catalog-domain collector has no production caller and passes none; workflow rows are excluded from signal_stats (ADR 0057 D5). packages/metrics/src/dataset-signal-collect.ts:458; packages/metrics/src/signal-binding.ts:346, :400; apps/web/src/server/signals/domain-signal-collector.ts:38, :53; packages/metrics/src/signal-stats.ts:61-72
G6 Agent eval is not in a gate; prompts carry no version. package.json:54 (absent from .github/workflows/*, .husky/*); packages/schema/src/tables/ai-prompt-templates.ts:40-62; packages/schema/src/tables/ai.ts:51-80
G7 Event contracts carry no shared id or schema version; lineage stops at bronze. packages/eventbus/src/bus.ts:86-95; packages/platform-contract/src/webhooks.ts:14-18; apps/web/src/app/api/ingest/webhook/[connectorType]/[connectorId]/route.ts:19-37; packages/schema/src/tables/data-lake.ts:46-47; packages/schema/src/tables/orders.ts:23; packages/schema/src/tables/agg.ts:76; docs/architecture/decision-engine.md:72-73
G8 AOV has two formulas. apps/web/src/server/routers/reports.ts:807 vs :1020; fallback offtake-loop.ts:3540
G9 The playbook runner proposes as org_admin, so its steps approve themselves. packages/actions/src/index.ts:675, :305-310, :373
G10 Chat has no token cap: the budget map covers two purposes. packages/ai/src/server.ts:200-201, :228-231, :269
G11 No consent mechanism for cross-org learning. category_benchmarks has no reader or writer; the industry prior is a constant. packages/schema/src/tables/decision.ts:33; packages/schema/src/runtime-acl.ts:53; policy-loop.ts:92

The signals work packages in flight own alert state and feedback UI: WP-SIG3 adds incident status, resolve and auto-resolve on alert_events (migration 0249), WP-SIG5 the ack, resolve, snooze and dismiss actions on the bell, brief and alert list, WP-SIG2 owns dataset-signal-collect.ts. S1 consumes their transitions as labels and does not redefine them.

Practice this ADR measures against (sources as cited in the 2026-11-07 architecture review, not re-fetched here):

Source Practice Seam
Google, Rules of ML Ship a heuristic, log serving-time features, join outcomes to them S2
Google Cloud, MLOps levels 0–2 Level 1: validated pipeline with training triggers; target level 1 only S2, S5
Microsoft, MLOps maturity model Registry with versioned lineage of what was served S3, S5
Netflix, Decision making at Netflix Assignment and estimand stored before the readout S2
DoorDash, Dash-AB Analysis as a service; guardrail metrics per test S2 (guardrails later)
Uber, Michelangelo One feature definition shared by training and serving S3, G8
Anthropic, Building effective agents Workflows before agents; autonomy only with evals S5
OpenAI, A practical guide to building agents Layered guardrails, eval-driven iteration S5
Shopify Engineering (Sidekick) Merchant-grounded answers judged by user feedback S1

Decision#

Five seams, each one module or one additive migration plus one guard in an existing gate. No new service, queue, table or framework.

S1 — Labels at the owning layer (G4, G5)

  • Alerts: a label is a WP-SIG3 transition (acked, resolved manual or auto, dismissed). No alert columns here.
  • Brief: no column on briefings; a brief is one reader's rendering. A bullet's reaction writes the row it came from: the four §117 feedback columns on signal_events, or the WP-SIG3 transition on alert_events.
  • Chat: chat_messages gains rating (up | down, NULL), rating_reason, rated_at, rated_by; set on role = 'assistant' rows by the conversation's own user through orgProcedure.
  • Episode link: a label on a row linked to a decision (packages/metrics/src/episode-signal-link.ts) appends a decision_episodes row with a new event kind feedback. EPISODE_EVENT_KINDS is a varchar union (mso-episodes.ts:64-99), so no migration; reducePlaybookStats (packages/metrics/src/decision-episodes.ts:1126) must ignore it.
  • One weight reader: weights becomes required on the collector input (signal-binding.ts:346), so no caller can rank unweighted. The rule stays demote-only (§117 amendment C4).
  • Verification: type test (omitting weights fails typecheck); router test (rating refused for another user's message and another org); reducePlaybookStats test (a feedback row changes no stat); append-only-ledger.ts and verify:rls green.
  • Consequences: one migration (chat_messages); labels become rows the reward join and prompt eval can read.
  • Rejected: rating on chat_tool_calls (a person judges the answer, and that table has no is_sample, packages/schema/src/tables/chat-tool-calls.ts:30-52); a briefings column (two labels for one event).
  • Isolation: chat_messages (rls-policies.sql:343), signal_events (:400, worker-only insert, §117), alert_events (:129), decision_episodes (:390); a rating is writable only by the message's own user.
  • Status (2026-11-07): chat rating built. Migration 0254_chat_message_rating.sql (columns, CHECKs, partial index, frozen-column guard in sql/append-only-guards.sql); chat.rateMessage (apps/web/src/server/routers/chat.ts, rate-limited, audit chat.message.rate); thumbs on /chat and the dashboard assistant tab; reader listChatAnswerLabels (packages/metrics/src/chat-answer-labels.ts) on a worker column grant that excludes parts. Not built yet: the feedback episode kind, required weights, and the deck assistant's thumbs.

S2 — Reward reaches the learner; the holdout is real (G1, G3)

  • MSO approve keeps its own insert (its payload is not an ActionProposalSchema payload, packages/actions/src/index.ts:139-158) and calls the exported assignExperimentArm (:738-741) with holdoutBp: 1000, the 10 % now written as a literal. It writes the experiment_assignments row in the same transaction; a control-arm command lands as holdout, never approved. Nothing starts executing that does not today; §64 gates stay in front.
  • Reward join in offtake-loop.ts, the sole persister (§60b): at window close it writes observed_lift_bp from the org's declared conversion through resolveConversionActualScoped (offtake-loop.ts:4489).
  • fitPolicyModels fits each lever posterior on lift in bp from owner-confirmed outcomes (confirmed_at set): incremental_value × 10000 / (measured_value − incremental_value), the quantity observed_lift_bp stores. A correlation is not a lift, so offtake_models.per_lever stops being an input: the cold-start prior becomes 0 bp with COLD_START_VAR_BP2 (packages/metrics/src/policy.ts:47), and a new policy_models.method value marks lift-fit rows so a reader never mixes the two. Below 8 confirmed outcomes, the floor ranking already uses (playbook-stats-rank.ts:96), the brand keeps the prior.
  • Selection stays deterministic: S2 gives a control arm, not randomized choice among playbooks.
  • Verification: verify:data assertion (observed lift reproduces from orders over the window for sample orgs, anchored to the §55 oracle); unit test (an unconfirmed outcome moves no posterior); offtake-single-source.py.
  • Consequences: no migration; observed_lift_bp gets a production writer besides scripts/generate-sample-data.ts:1145; 10 % of approved MSO commands are withheld as control.
  • Rejected: routing MSO approve through proposeAction (payload schema mismatch, and a new approved row there auto-executes, packages/actions/src/index.ts:373); keeping the correlation as the lift prior (different quantity).
  • Isolation: experiment_assignments (rls-policies.sql:147), decision_outcomes (:383), policy_models (:421); the fit reads one org (policy-loop.ts:178-186).
  • Status (2026-11-07): built, no migration (0252 unused). The arm unit is the decision: sha256("mso_decision:<org>:<decision>") into assignExperimentArm with MSO_DECISION_HOLDOUT_BP (1000, row mso-decision-holdout in docs/architecture/reference/limits-and-budgets.md), so a cancel and re-approve keeps its arm; one experiment_assignments row per command (subject_type = 'mso_decision', subject_key = decision id) in the claim transaction, a control arm inserts every command as holdout, and a decision with no command records no arm. assignExperimentArm now buckets on 8 hex digits: 4 digits put 10.7 % in a 10 % arm. The baseline is the same conversion over the equal-length window before execution, read by resolveConversionActualScoped; the lift is pre/post per decision, written on both arms, and not yet control-adjusted. A control-arm decision was never run: its outcome is written with verdict abstain (no calibration bucket, no measured episode, so playbook_stats, the OPE log and the confirm-due ping never see it) and confirmOutcome refuses it. The decision board tells the owner: the approve response's arm raises a notice not to run the decision by hand, and a control decision keeps one status line on its card and detail, read from its newest experiment_assignments row inside offtake.decisions (now narrowed by the caller's brand grant, §198); a control decision gets no lesson to approve. The fit reads observed_lift_bp of treatment-arm, non-sample rows whose outcome is confirmed (policy_models.method = 'lift_normal'; recommendPolicy and the champion/challenger card read only those rows); decision_outcomes.incremental_value stays NULL on real rows, so no surface number changes. yng_worker gains UPDATE on experiment_assignments(observed_lift_bp, measured_at) only. Verification: verify:data #61 (fixture org: lifts equal the literals its orders imply, both arms; the control outcome abstains with no episode; the posterior folds the 8 confirmed treatment rewards and leaves out the unconfirmed one and the control) and #20 (every lift-fit row reproduces from an independent join); unit tests in policy-loop.test.ts, policy.test.ts, offtake-approve-ordering.test.ts, run-playbook-role.test.ts. Follow-up: recommendPolicy serves only a lever with confirmed positive lift (n_obs at the floor, mean > 0 bp) and abstains as cold_start ("chưa đủ bằng chứng") otherwise, and a guardrail veto falls back only to such a lever that clears the floor itself; approveLesson refuses a control decision in its UPDATE as confirmOutcome does; markExecuted on a proposed decision assigns the arm and writes the commands through the helpers approve uses, in its claim transaction. Not done: decision_episodes.source_watermark (S4) has no writer here.

S3 — Serving reads the champion; the runner uses the caller's role (G2, G9)

  • The scan (offtake-loop.ts:906) passes the champion policy_versions.config, read once per org per scan with the query at :5164-5179. No champion means TIER2_DEFAULTS, today's behaviour.
  • The episode pins the served policy_versions id and version in its receipt, which receipt_hash already covers (mso-episodes.ts:290-293); replay ranks with that config. logging_policy_version (:275) keeps its meaning, the rule-DSL version (packages/metrics/src/decision-episodes.ts:647).
  • runPlaybook (packages/actions/src/index.ts:659) takes the actor's role from its caller instead of the literal at :675. A system trigger (apps/worker/src/trigger-dispatcher.ts:142) proposes as viewer, so every step waits for a person.
  • Verification: unit test (a promoted challenger with a different prior changes the served order); scripts/audit/decision-replay.ts replays with the pinned version; test (a system-triggered step is pending_approval); decision-mutation-rbac.py.
  • Consequences: no migration; a promotion now changes what tenants see, so promote stays owner-only and audit-logged (§64); alert-triggered playbook steps stop approving themselves.
  • Rejected: a second logging_policy_version meaning (one column, two versions); keeping org_admin for system triggers (no person approved).
  • Isolation: policy_versions (rls-policies.sql:425), read per org and brand (offtake-loop.ts:5164-5179).

S4 — One event envelope; lineage to gold (G7)

  • One Zod EventEnvelopeSchema in packages/platform-contract: {id, type, org_id, brand_id?, occurred_at, source_system, source_ref, schema_version, data}. The eventbus envelope gains id and schema_version; webhook ingest parses with it while the raw body still lands verbatim in raw_events (§44).
  • Additive migration: nullable raw_event_id, source_batch_id on orders and the sync-written silver tables; source_watermark jsonb on agg_* and on decision_episodes (set at insert). NULL means "before lineage"; no backfill. Indexes only when a reader exists.
  • Verification: new audit event-envelope-single-schema.py in audit:all (no envelope type outside platform-contract); scripts/audit/decision-replay.ts compares the watermark when present; verify:rls and drizzle-journal-monotonic.py.
  • Consequences: one migration; replay can say whether today's warehouse matches the inputs a decision saw (docs/status.md:146); producers of the three contracts change once.
  • Rejected: a streaming platform or OpenTelemetry for lineage (columns answer the question; no consumer needs more); backfilling lineage for old rows (unrecoverable for rows ingested before it).
  • Isolation: no learned state. orders (rls-policies.sql:305) and agg_org_day (:329) are already org-scoped; the envelope carries org_id, and a mismatch with the authenticated connector's org is refused.
  • Status (2026-11-07): schema half built. eventEnvelopeSchema in packages/platform-contract/src/event-envelope.ts (contract 0.3.0), used by the webhook ingest route (the envelope org_id is the authenticated connector's org) and the eventbus publisher (id, schema_version). Migration 0253 adds raw_event_id/source_batch_id on orders and inventory_snapshots; the polling sync, Bronze replay and webhook writers set them, uploads clear them. creators is left out: it is a merged identity, not one Bronze record. source_watermark is on agg_* and decision_episodes with no writer yet; the materialization refresh and the episode persister (offtake-loop.ts, owned by S2/S3) add it, and decision-replay.ts compares it once it is written. Guard: event-envelope-single-schema.py (§205) in audit:all. Reference: event contracts.

S5 — Eval and prompt versions in the gate; a chat cap (G6, G10)

  • ai_prompt_templates gains version and body_hash; ai_usage_log gains prompt_hash, prompt_version. WP-AI1's columns merged as migration 0248 (6d39fc09).
  • organizations gains a nullable chat token budget (NULL = unlimited, today's behaviour) and one row in PURPOSE_BUDGET_COLUMN (packages/ai/src/server.ts:228-231); the chat route asks aiBudgetRemaining before streaming. No default cap: the operator sets it.
  • CI job in .github/workflows/ci.yml: eval:agent --dry-run --baseline=<committed file> (scripted, no provider); --live runs nightly and gates nothing.
  • Verification: the baseline diff fails CI on a regression; limits-registry.py row for the cap; ai-resolver-single-source.py.
  • Consequences: one migration (ai_prompt_templates, ai_usage_log, organizations); a prompt or model change that regresses a graded case fails CI; chat spend can be capped per org per month.
  • Rejected: --live eval as a merge gate (provider cost and nondeterminism per push); a default chat cap (no source for the number).
  • Status (2026-11-07, accepted by the operator): CI half merged (9fc00c06). Schema half is migration 0255: ai_prompt_templates.version (N+1 per body change, computed in the router's one UPDATE) and body_hash; ai_usage_log.prompt_hash/prompt_version, written by /api/chat as the hash of its system prompt rendered at a fixed clock (version NULL: chat reads no template row); organizations.chat_ai_budget_tokens, refused before streaming with chat_budget_exhausted (429, Retry-After to the next ICT month), set in the Admin CP org drawer, row ai-chat-budget in docs/architecture/reference/limits-and-budgets.md. Other purposes record NULL until their call sites separate instructions from data; chat_deck stays uncapped.
  • Isolation: ai_prompt_templates (rls-policies.sql:80) and ai_usage_log (:78) are org-scoped. organizations is outside RLS by design (:664-665; inventory scripts/audit/rls-policy-inventory.ts:55); the budget column is written only where the two existing budget columns are (apps/web/src/server/routers/admin.ts:861) and read for the caller's own org.

Tenant isolation of learned state

No seam adds a table. Every learned-state and label table is in the attested org RLS arrays (packages/schema/sql/rls-policies.sql:548-590): ai_usage_log:78, ai_prompt_templates:80, alert_events:129, experiment_assignments:147, chat_messages:343, decision_outcomes:383, decision_episodes:390, playbook_stats:391, signal_stats:406, policy_models:421, policy_versions:425. S4 lineage columns land on org-scoped fact tables; the S5 budget column lands on organizations, the one table outside RLS (S5 above). Learned state is fit per org (policy-loop.ts:178-186) and pooled across brands inside one org only (:197); brand-carrying rows keep brand_id (§82). No code reads another org's outcomes. Cross-org learning (pooled priors, category_benchmarks) stays closed until a separate ADR defines consent: per-org opt-in, recorded and revocable, aggregated above a minimum org count.

Rollout order

Step Seam Waits for Rollback
1 S3 nothing revert; without a promotion the served order is unchanged
2 S2 S3 (a promoted policy must be the one served) revert; assignments already written stay as history
3 S4 nothing; any time revert code; nullable columns stay
4 S1 WP-SIG1, SIG3, SIG5 merged revert; rating columns stay NULL
5 S5 AI work packages (packages/ai/**, chat route) drop the CI job; NULL budget = unlimited

Rejected alternatives#

  • A feature-store product: no second consumer; the catalog, Cube and dataset DSL already define features. G8 is a catalog fix (packages/metrics/src/types.ts:185 has no formula field), not a new store.
  • Cross-org priors now: no consent mechanism (G11).
  • Production bandit now: needs S2 rewards for at least 2 months and an OPE ESS of 30 (ope.ts:72) before randomized selection.
  • The causal service now (ADR 0009): apps/ml/yng_ml/main.py is a 68-line stub; deferred until S2 yields a control arm. 0009 stays Proposed.
  • A new alert incident table: the operator chose columns on alert_events (WP-SIG3).
  • Seam-level alternatives are listed under each seam.

Consequences#

  • Three additive, idempotent migrations: S1 (chat_messages), S4 (lineage), S5 (prompt version, usage, org budget). Numbers are allocated at build time; 0249 and 0250 belong to the signals work.
  • One shared Zod schema, one CI job, one new audit, one verify:data assertion, one type-level guard.
  • Unchanged: a person approves every action (§64), and S3 removes the one path where a step approved itself; no machine write-back (packages/connectors/tiktok-shop/src/index.ts:972-984 returns manual_follow_up); the weight rule only demotes.
  • L3 can move on control-arm evidence (S2) and L5 on the watermark (S4); docs/status.md rows change only with that evidence.
  • Not addressed: G8 beyond S2 using the one conversion resolver; replay of signal_events inputs.