Skip to content

fix(metadata-protocol): a seed key reference empty on the first load holds one row across loads - #34854

Merged
objectstack-fleet[bot] merged 6 commits into
mainfrom
claude/issue-34800-seed-composite-deferred-key
Nov 17, 2026
Merged

objectstack-fleet[bot] merged 6 commits into
mainfrom
claude/issue-34800-seed-composite-deferred-key

Conversation

@objectstack-fleet

Copy link
Copy Markdown
Contributor

Requested by Yibo Wang · project thread
Fixes #34800

Clause-②: no
Metadata-protocol: none

repo:objectstack#3 · os-support-ai · session_01WGufzgNCAXyGfBQFZBwixH

维护者速读

  • 改了什么:种子数据集的复合 externalId 里含一个首次加载时只能留空的引用(如尚未注册的人员)时,这行以「按作者写下的键派生的 id」落库;之后每次加载按这个 id 找回同一行,引用一旦可解析就补写到这一行上。
  • 为什么改:之前每次启动/每次组织重放都再插一行(实测 1 → 2 → 3;人员在两次启动之间注册则 1 → 2 → 2,旧行永远留空)。seed: an unkeyed (insert/replace) inline seed is inserted again on every un-walled start, so the first row's person references stay NULL and the dataset duplicates #34613 退役 insert/replace 后,默认模式 + 复合键正是推荐写法。
  • 风险与回滚:只影响「键里有引用、且该引用在插入时被延后」的行;引用首次即可解析的复合键、纯字段复合键照旧(引擎生成 id)。已经产生重复行的安装不会自动清理,下次加载最多再落一行,之后稳定。回滚 = revert 本 PR。
  • 先看:packages/metadata-protocol/src/seed-loader.ts 里 rowLandedWithEmptyKeyReference(按 id 认领的守卫条件)、派生 id 赋值块与 ignore 模式的 pass-2 补写块;seedDeferredKeyRowId。
  • 两分钟验证:pnpm --filter @objectstack/metadata-protocol exec vitest run --maxWorkers=2 src/seed-loader-deferred-key-reference.test.ts,预期 9 个用例全绿(三次加载始终 1 行、人员出现后引用补到首行、两条仅引用不同的记录保持 2 行、客户手建的空引用行不被占用)。
  • 需要你做的:无,席位落地。

What changes

packages/metadata-protocol/src/seed-loader.ts:

  • A row that lands while a reference in its key is deferred (pass 1 could not resolve it, so the column is left out of the insert) now lands with an id derived from the key as authored: seedDeferredKeyRowId(object, row organization, authoredKey), where authoredKey is seedLandedKey over the record before its references resolve — the person's natural key, never the id it resolves to. Only for upsert / ignore, only when the record names no id of its own, and never an id a row of this organization or another record of the load already holds.
  • When a record's natural key finds no row, rowLandedWithEmptyKeyReference looks the row up by that id (or by the record's own id), from the same pre-load read, now also indexed by id (loadExistingRecords' optional byId). It takes the row only when its other key columns equal the record's and each reference column it holds is empty or the very value the record resolved, and only for one record of the load. An exact natural-key match always wins. The write decision, the create-only check, seed files and the seed loader: a declared seed row a person deleted comes back under a new id at the next seed replay — record landed keys per organization and skip the ones now absent #31021 withdrawal question all read the found row through one view (existingRowsFor).
  • Once the reference resolves it lands on the row first landed: upsert updates the row as it does any matched row; ignore writes nothing over a row it found, so the one column is back-filled by pass 2 (the held person reference path writes the same way onto the row the seed landed on).

Route (the claim's): the replay finds the row as first landed. Why an id and not the #31021 ledger: the ledger stores keys, never which row a key landed on, so it can say "this key landed here" but cannot find the row; and it exists only where a composition registers sys_seed_landed_key and the load has an organization. The id is carried by the row itself, so both paths are covered by one mechanism, and a row a person created (random id) can never be taken. Authoring-time refusal of such a key was not taken (it narrows the accept set; the claim excludes it).

Tests

  • New packages/metadata-protocol/src/seed-loader-deferred-key-reference.test.ts (9 cases, a fresh loader per load as a restart does): ignore and upsert × {person never appears: 3 loads → 1 row; person appears between loads: 1 row, reference on the row first landed}; the landed-key record kept (landedKeys: 'honour'): 1 row, skipped not withdrawn; two records differing only in the reference stay two rows, each filled with its own person; a customer row with the reference empty is never taken. CONTROLs: a composite key whose reference resolves on the first load, and a composite key over plain fields, match as before with engine-minted ids.
  • New packages/runtime/src/seed-deferred-key-reference-real-driver.integration.test.ts (2 cases): real SeedLoaderService + real ObjectQL + real SqlDriver on one better-sqlite3 file, three boots (new engine/driver/loader each): per-organization replay with the landed-key record, person never appears → [1, 1, 1]; no landed-key record, upsert, person appears before boot 2 → [1, 1, 1] and the reference lands.
  • scripts/engine-double-contract.pinned.json: the three pinned doubles of the new test file, written by node scripts/check-engine-double-contract.mjs --write as the gate prescribes (add-only, "0 lost").

Acceptance notes

  • Already-duplicated installs keep their copies (the old rows carry engine-minted ids, which are indistinguishable from a customer's row); the next load lands at most one more row, which every later load finds. Stated in the changeset.
  • SeedDatasetFiles.open still receives the natural-key map only; a row found by id is passed to prepareRow through existingRowsFor, which is the call that reads it.
  • A row that landed by its derived id and was filled later, whose person is then removed: the record defers again and still finds the row by id. NOT covered, unchanged from main: a row that landed with its reference resolved (engine-minted id) whose person is later removed keys empty on the next load, and a new row lands.
  • The held person reference path (resolveHeldPersonReferences) is not edited: the deferral's internal id is the found row's id, so a held reference is written onto that row.

Verification

Measured on origin/main c513d62 before code, with the same harness as the runtime test (scratch file, deleted): every composition duplicated.

Reproduction on main (three boots over one sqlite file)
MEASURE mode=default ledger=true  sole=false signUpAfter=null rows=1 -> 2 -> 3
MEASURE mode=default ledger=true  sole=true  signUpAfter=null rows=1 -> 2 -> 3
MEASURE mode=default ledger=true  sole=false signUpAfter=1    rows=1 -> 2 -> 2
MEASURE mode=default ledger=false sole=false signUpAfter=null rows=1 -> 2 -> 3
MEASURE mode=default ledger=false sole=false signUpAfter=1    rows=1 -> 2 -> 2
MEASURE mode=upsert  ledger=true  sole=false signUpAfter=null rows=1 -> 2 -> 3
MEASURE mode=upsert  ledger=false sole=false signUpAfter=1    rows=1 -> 2 -> 2
(the 1 -> 2 -> 2 rows: the second copy carried the person, the first stayed NULL)

Same harness on this branch: every line rows=1 -> 1 -> 1, reference filled where the person signed up.

Ablation (unit file; it imports ./seed-loader.js from src, so no dist leg)

Fix committed first; mutation via scripts/ablation-replace.mjs, restore by git checkout HEAD --, proven by blob == HEAD and git diff HEAD empty.

  1. Find-by-id removed (const row = existingRowsById.get(rowId); → const row = undefined as any;, blob 195e71f0 → 50685164): 7 failed / 2 passed — every duplicate and fill case red; the two CONTROLs green.
  2. Guard replaced by the naive fallback (take any stored row whose reference column is empty): 1 failed / 8 passed — the customer-row case red, as it must be. A first attempt at this mutation reassigned a const and threw TypeError in every case; that run was discarded as a non-mutation and redone.
Local readings at head 58dc0df (CI runs the full farm)
  • pnpm --filter @objectstack/metadata-protocol typecheck + full vitest run (after merging origin/main dfbc316 and rebuilding the closure): VERDICT command-exit 0 · Test Files 349 passed / 9 skipped (358) · Tests 23100 passed / 45 skipped.
  • pnpm --filter @objectstack/runtime typecheck (tsc + check:test-typecheck OK) and the new runtime file: Test Files 1 passed · Tests 2 passed.
  • Derived gate families (dispatch-gates.mjs --commands, 75 for this diff): --ran verdict "75 derived famil(ies) accounted for — 73 run, 2 NOT-MEASURED". NOT MEASURED: check:dual-build-cjs-loads (PREREQUISITE NOT MET: reads every package's dist; only the touched closures are built here) and check-plugin-teardown-shape.mjs --self-test (shallow clone cannot reach its pinned fixture commit; checker-health only). check:engine-double-contract was red until the ledger rows above, exit 0 after.
  • overlap-check.mjs: VERDICT clean — merges cleanly with origin/main and with fix(spec,metadata-protocol)!: retire the seed modes insert and replace, which inserted every record again on each replay #34791 (shares seed-loader.ts) and feat(i18n): a dependent package's fieldPatches text is translated from that package's own translations #34784 (shares the ledger).
  • Package test:repo projects and the rest of the farm: declared to CI.

Generated by Claude Code

🤖 Generated with Claude Code

https://claude.ai/code/session_01WGufzgNCAXyGfBQFZBwixH

@github-actions

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

3 anchor(s) derived from 1 changed package(s); no hand-written page names any of them, so this run has nothing to list — not a clean bill of health. This check sees only pages that NAME a derived anchor: one that documents this change in prose, or enumerates it in an authoring dialect, names none and stays invisible to it on every run.

What this run could not see
  • the SDK route bridge reached 65 of 247 client-bound route-ledger rows — the other 182 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 182: 0 are remediable by widening that discovery convention (an in-repo file declares the path; the convention did not scan it); 59 are structural — on a ledger where NOT ONE row is declared in-repo, so no discovery change reaches them at any price; 123 are undecided (no in-repo declaration, on a ledger that has other in-repo registrars — absence and an unreadable spelling are not distinguishable here). The rows themselves: node scripts/docs-audit/affected-docs.mjs --bridge-coverage
  • a page that states a rule by its inputs shares no identifier with the emitter that implements the rule, so an emitter-only diff cannot list it — not on this run and not on any run. Measured on fix(driver-sql): emit varchar(maxLength) for a text field a declared index keys on #11430: content/docs/protocol/objectql/types.mdx documents the text-family column mapping by the ObjectQL type names it maps FROM (text / textarea / html) while the diff changed createColumn; it went unlisted, and it was the page that diff falsified, in four places. No shared token exists to detect this on, so a rule your change carries has to be re-read by hand in the pages that restate it.
  • a key NAME is not a key, so the hand re-read the line above prescribes can land on the wrong schema. The same spelling is authorable on one governed type and a [REMOVED] tombstone on another for each of active, aria, joins, objects, template, tools and version (censused on [finding] tools is a key on BOTH AgentSchema (tombstoned, dead) and SkillSchema (live, cloud-attested), so a name-based search attributes skill examples to the agent key — it produced a false stop-the-line alarm on PR #19059 #19093 over the liveness ledger's governed types, top-level keys); nothing in a search result distinguishes the two, so a grep hit on a LIVE example reads as evidence about the DEAD key. Measured on fix(spec): the agent.tools liveness row says dead — it claimed live on a key the schema tombstoned #19059: content/docs/ai/agents.mdx was reported as contradicting the agent.tools tombstone over its tools: example at :161, which is inside the defineSkill({ block opened at :155 — the page was already correct. Settle ownership by PARSING the value against both schemas, never by the name: that literal PASSES SkillSchema, and as an AgentSchema it FAILS at tools with the tombstone prescription. ⛔ These names are not the whole class — a key retired through a .strict() guidance map leaves no tombstone in the walked shape and none of them here (tool.category, live as AIToolDefinition.category).

Coarse fallback — 10 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): node scripts/docs-audit/affected-docs.mjs --json 7752cac7b002c6beb7b32dcc4ad2db450884151a → packageMentionDocs.

Which tree this was computed on

This run read content/docs from aa4e5f5eb3bec86e950121078c090eda0c04eb35 — the merge of head 58dc0dfd82d3ad31538410285214129b6aaef9c0 into base 7752cac7b002c6beb7b32dcc4ad2db450884151a, which is what actions/checkout gives a pull_request run. Not the PR head.

A worktree cut from an older main holds a different content/docs, so re-deriving there can legitimately return a different list — that is a different tree, not a wrong row. To answer on the same tree:

# while this PR is open — GitHub drops the merge commit once it closes
git fetch origin aa4e5f5eb3bec86e950121078c090eda0c04eb35 && git checkout aa4e5f5eb3bec86e950121078c090eda0c04eb35
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 7752cac7b002c6beb7b32dcc4ad2db450884151a 58dc0dfd82d3ad31538410285214129b6aaef9c0 && git checkout -B drift-repro 7752cac7b002c6beb7b32dcc4ad2db450884151a && git merge --no-ff 58dc0dfd82d3ad31538410285214129b6aaef9c0

node scripts/docs-audit/affected-docs.mjs --json 7752cac7b002c6beb7b32dcc4ad2db450884151a

⚠️ That checkout carried uncommitted changes, so the commit above does not fully identify what was read.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#3 · os-support-ai · session_01WGufzgQsdnyS4QdR8stjDa

L1 review (L1-d) · 2026-11-17T14:25Z

L1: ACCEPT
Head-sha: 58dc0dfd82d3ad31538410285214129b6aaef9c0

Read at that head: the file list (5 paths), the full diff, the PR body, card #34800 with triage 6946065909, claim 6947910076 (its Route line), surface amendment 6950188764, os-dev report 6950154378, and the 53 check-runs.

Checklist

  • Shape: draft, base main, Fixes #34800. The card asks the claiming seat to choose the seam, and the claim's Route ("the replay finds the row as first landed", on both the ledger and no-ledger paths, and the fallback must not capture a different row) is delivered whole. A closing keyword is right. No other open card sits beside a keyword: fix(spec,metadata-protocol)!: retire the seed modes insert and replace, which inserted every record again on each replay #34791 and feat(i18n): a dependent package's fieldPatches text is translated from that package's own translations #34784 appear only in the overlap reading.
  • Scope vs claim: seed-loader.ts, the new card-named loader test, the root changeset, the runtime real-boot test (allowed by the claim, named in the amendment) and scripts/engine-double-contract.pinned.json (15 add-only lines written by the gate's own --write, named in the amendment). No unrelated file, and no existing test is edited.
  • Changeset: @objectstack/metadata-protocol is published and is the only package whose src/** ships a change. @objectstack/runtime gains only a test file. Sentences checked against the diff:
    • "lands with an id derived from the key as the author wrote it … in its object and organization" is seedDeferredKeyRowId(objectName, rowOrganization, authoredKey). authoredKey is seedLandedKey read before resolution, and the organization column is already stamped (:2129) before either the id or the lookup is computed.
    • "takes it only when its other key columns still match and its reference column is empty or already holds the resolved value" is the keyFields loop in rowLandedWithEmptyKeyReference.
    • "two records whose keys differ only in that reference stay two rows" holds because each authored key derives its own id. Test "two records …" pins it.
    • "by the update under mode: 'upsert', and under the default mode: 'ignore' by the pass-2 back-fill of that one column" is the landedKeyRow block. ignore is the default per seed.zod.ts:28.
    • "Keys that resolve on the first load, and keys over plain fields, match exactly as before, with engine-minted ids" is pinned by the two CONTROLs (/^gen-/).
    • The legacy-duplicates sentence matches the body's acceptance note.
      All true.
  • Docs and spec text: seed.zod.ts externalId says composite reference keys "match by their RESOLVED ids, so a composite of foreign keys dedupes correctly across restarts", and content/docs/data-modeling/seed-data.mdx §Composite externalId says the same. Both were false for this case on main and are true after this PR. Nothing is made false.
  • Clause-② / Metadata-protocol: no / none, the same in the claim, the body and the changeset. loadExistingRecords gains a private optional parameter. No export, schema or accept set changes, so no contract face and no L2.
  • Governed: check-governed-merges.mjs --pr 34854 gives 0 of 5 paths and 580 lines, so not Tier H.
  • Tests and evidence:
    • Reproduction on main: seven compositions, 1→2→3, or 1→2→2 when the person appears later.
    • Same harness on this branch: 1→1→1 throughout.
    • Ablation 1 (find-by-id removed): 7 red, with only the CONTROLs green.
    • Ablation 2 (naive empty-column fallback): exactly the customer-row case red. This is the "must not capture a different row" check the claim asked for.
    • The real-driver file runs a fresh engine, driver and loader per boot over one sqlite file, so a seed_<32 hex> id is proven to land through SqlDriver.
  • CI at this head: Lint & Repo Gates, TypeScript Type Check, Test Core (all 10 shards), Build Core, Dogfood Regression Gate, Live E2E UI, Check Changeset and the Governed Surface Queue Guard all success. The UI lanes are skipped by path filter. Nothing red or pending.

Must-fix

None.

Should-fix

None.

Notes

Landing: not governed, all checks green. Area o3-G lands it. A later push owes a delta read.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#3 · os-support-ai · session_01WGufzgNCAXyGfBQFZBwixH

Landing · 2026-11-17T14:26Z

Probe Reading
L1 ACCEPT 6950853690 (L1-d) at 58dc0dfd82d3ad31538410285214129b6aaef9c0, no must-fix, no should-fix; notes only (N1 theoretical lookup timing, not owed; N2 no forced order with #34791; N3 findings filed as #34856/#34857)
Governed check-governed-merges.mjs --pr 34854: NOT governed, 0 of 5 paths, 580 lines ≤ 3000; no contract face, no L2 owed
CI at head all check suites completed, none failed (L1-d read 53 check-runs, Test Core 10/10)
K behind main 12 first-parent commits since merge-base 0ad377c1 (< 15); no file of this PR changed on main since; no os-regen path in the diff

Ready + auto-merge into the queue. Area o3-G (repo:objectstack#3) watches it to MERGED and closes out #34800.

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review November 17, 2026 14:27
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Nov 17, 2026
Merged via the queue into main with commit 842b468 Nov 17, 2026
54 checks passed
@objectstack-fleet
objectstack-fleet Bot deleted the claude/issue-34800-seed-composite-deferred-key branch November 17, 2026 15:01
os-support-ai pushed a commit that referenced this pull request Nov 17, 2026
…ed keys

Seat S2: since #34854 a composite-key row whose reference the first load
leaves empty is found again by its authored key and filled later, so the
advice to key only on fields every load can fill is false. Dropped from the
migration entry replacement and SEED_MODE_RETIRED_FIX; seed-data.mdx step 2
now says what the loader does. N12: the changeset states the rule count
70 to 69. Text only.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGufzfr1xZSFZzCR8HnqXX
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation size/l tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

seed: a composite externalId that includes a reference only fillable after the first load never matches on later loads, so each load inserts another row

2 participants