Skip to content

Commit fc7534a

Browse files
fix(metadata-protocol): concurrent saves with no transaction never collide on the history event number (#38998)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBG4YD4RMAt72Ga5PdYYZDAQ)_ Fixes #38984 Claim for this branch: #38984 comment 7318812140 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:在托管环境(远程数据库)里,助手同时保存几份草稿时,每份都会成功并记进变更历史;不会再出现「报冲突说没写入、其实已经写入」的情况。本地文件数据库和内存数据库的行为不变。 - 为什么做:云端搭建体验的第二阶段(助手在托管环境里搭建应用)卡在这里:误报失败让助手反复重试,审阅卡漏列草稿。 - 出错会怎样:最坏情况是同时保存仍然撞号到上限,这时保存会被撤回并明确告诉助手「这次没有保存,请重新保存」;改动只在保存与删除的历史记录这一步,可以直接撤回本 PR。 - 要你做什么:无。 ## What changes `SysMetadataRepository.put` and `delete` write the parent `sys_metadata` row, then append a `sys_metadata_history` row numbered `MAX(event_seq) + 1`. On a connection that gives no transaction (remote Turso, `supports.transactionsUnsupported`, ADR-0119 D1), concurrent writers read the same MAX; the unique `(event_seq)` index refused every history row but one, and each refused save answered `409 DUPLICATE_RECORD` ("No record was written.") although its parent row had landed. The history append of both verbs now goes through one private method, `appendHistoryRow`: - **Inside a transaction** (the callback's context carries `transaction`: a driver that rolls back, or a joined outer unit) it makes one attempt and rethrows the refusal unchanged, as before, so the transaction rolls the parent write back. A retry there would be wrong: Postgres aborts the transaction on the refusal. - **With no transaction**, on the engine's `DUPLICATE_RECORD` envelope naming `object: 'sys_metadata_history'` and `field: 'event_seq'`, it waits a short random time (at most 250 ms per round), re-derives the seq and inserts again, up to 8 attempts. The item, the put/delete result, `seqCounter` and the `watch()` broadcast carry the seq actually stored. - A `DUPLICATE_RECORD` on the lineage key `(type, name, version)` (a concurrent write of the **same** item) is neither retried nor undone: numbering past it could leave the newest history version naming a different body than the live row, and undoing would erase the other write too. - When the cap is spent (or the seq cannot be re-read mid-race), the parent write is undone while the row still holds it: a fresh row is deleted, an updated row gets its prior column values back, a deleted row is inserted again. - Every race outcome that fails answers `409 CONCURRENT_UPDATE` (already registered for `@objectstack/metadata-protocol`) with a sentence that says what is stored: undone and nothing stored; already replaced by another writer and not stored; or the row written without its history row (lineage conflict, or a failed undo). None says "no record was written" of a row that was. - A history insert failure that is not this race (no `DUPLICATE_RECORD` on the history table) is rethrown unchanged with no undo, as before. Doc comments: `nextEventSeq` and the `event_seq` note in `sys-metadata-history.object.ts` no longer claim every producer runs inside a transaction. Design points from the dispatch: 1. **Route**: bounded retry with jitter, matched on the ADR-0112 envelope (`code === 'DUPLICATE_RECORD'`, `object === 'sys_metadata_history'`, `field === 'event_seq'`), never a dialect code. A derivation that cannot collide needs a sequence object or a serialising store (out of the fence); an in-process mutex would cover one server only. Lineage conflicts are not retried (see above). 2. **Exhaustion**: compensate (undo) and answer `409 CONCURRENT_UPDATE` saying nothing is stored; if the row was already replaced, say this write is not stored; if the undo fails, say the row was written without its history row. Pinned for fresh draft, updated draft, deleted active row, replaced row, failed undo. 3. **Transactional engines**: the retry and the undo run only where the callback's context has no `transaction`. `ObjectQL.transaction` passes the handle on its transactional and joined paths and none on its declared degrade. Pinned by the new suite's transactional case; existing pins: `sys-metadata-repository.history-counters.test.ts` (rollback on a failed counter read), `protocol.delete-rewrap-envelope.test.ts` (a non-race history failure keeps its 500). 4. **Counters**: `storedSeq` feeds the item, the result, `seqCounter` and the broadcast. Pinned (result seq, item seq, watched events). 5. **Delete**: the tombstone append takes the same path, with the removed row put back on exhaustion. Pinned. 6. **Docs**: both comments updated. ## Tests New file `packages/metadata-protocol/src/sys-metadata-repository-38984-event-seq-race.test.ts`: a stand-in engine with no rollback (`transaction` absent, and present calling back with no handle), enforcing both unique indexes with the engine's envelope. The global history reads are gated so every writer reads the same MAX before any insert: the race is run, not hoped for. Read at head `53dd1914da` (after merging `origin/main` 5704d13): <details><summary>Package suite and typecheck</summary> - `pnpm --filter @objectstack/metadata-protocol typecheck` and `pnpm --filter @objectstack/metadata-core typecheck`: exit 0 (the new test file is in the metadata-protocol program: `tsc --listFiles` counts it once). - `pnpm --filter @objectstack/metadata-protocol exec vitest run --maxWorkers=2`: Test Files 381 passed, 9 skipped (390); Tests 23933 passed, 45 skipped (23978). - New file alone: 19 passed (9 cases on each of the two no-transaction stand-ins, plus 1 transactional case). </details> <details><summary>Ablation (tested behaviour changed)</summary> - Mutation through `scripts/ablation-replace.mjs`: `const transactional = ...` replaced by `const transactional = true;` (anchor 1 to 0, blob c76a29e to 5b62d7c65e34). The new file: 18 failed, 1 passed (the transactional case, unchanged by design). First failure: `expected [ 'fulfilled', 'rejected', ...(4) ] to deeply equal [ 'fulfilled', 'fulfilled', ...(4) ]`. Restored: blob c76a29e equals HEAD, `git diff HEAD` empty. - The repository source at the base commit be2df75 run against the new file: 18 failed, 1 passed; the refusals read `Duplicate record refused on 'Metadata History' ...` where `CONCURRENT_UPDATE` is expected. Restored to HEAD blob, `git diff HEAD` empty. </details> ## Acceptance notes - Cloud's staging re-check of cloud#5324 belongs to the cloud pin round that carries this fix; this PR does not close it. - `scripts/engine-double-contract.pinned.json` gained the new test file's three pinned verbs (`check:engine-double-contract --write`, additive only): the gate's ledger for the authorised new test file, outside the listed file surface; named here. - `DatabaseLoader.createHistoryRecord` (`packages/metadata`) still says "The SysMetadataRepository path serializes this under engine.transaction()", which is not true on remote Turso. Stale prose outside this fence; the legacy loader tolerates the race by its own comment. - A history insert that fails for a reason other than this race, on a connection with no transaction, still leaves the parent row without a history row (unchanged behaviour, rethrown as before). - After merging `origin/main` (5704d13), `pnpm --filter @objectstack/spec check:generated` reads `declaration-map/api.json is stale`. This branch changes nothing under `packages/spec` (`git diff origin/main HEAD -- packages/spec` is empty), so that staleness is on `main`'s side; not regenerated here (outside this card's files). - `nextEventSeq`'s once-only error log on a failed re-read still says the enclosing transaction rolled back; on the no-transaction path the undo runs instead. ## Verification Read first: `appendHistoryRow` and `unrecordedHistoryRefusal` in `sys-metadata-repository.ts` (the transactional guard and the field match are the risk), then the undo closure in `put` (row-still-holds-this-write check). Two-minute check: `pnpm --filter @objectstack/metadata-protocol exec vitest run src/sys-metadata-repository-38984-event-seq-race.test.ts` shows 19 passed. <details><summary>Local gates (derived by dispatch-gates --commands at 53dd191)</summary> 77 derived: 74 run with exit 0 (among them `check:durability-log-level`, `check:engine-double-contract`, `check:objectql-double-limit`, `check:error-status-conformance`, `check:dispatcher-error-vocabulary`, `check:nul-bytes`, `check:type-check-debt`, `check:adr-0087-registration`, `check:empty-changeset`), 3 NOT MEASURED with exit 3 PREREQUISITE NOT MET: `check-plugin-teardown-shape --self-test` (shallow clone cannot reach its pinned fixture commit), `check:dual-build-cjs-loads` and `check:lean-entry-closure` (read built output of packages this worktree did not build). `dispatch-gates --ran`: 77 accounted, 0 unrun. CI runs the full farm. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WGufzeatqKfTRUzTJVa9jQ --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzeatqKfTRUzTJVa9jQ)_ <!-- signed: repo:objectstack@os-support-ai · os-support-ai · session_01WGufzeatqKfTRUzTJVa9jQ --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 38ab473 commit fc7534a

5 files changed

Lines changed: 635 additions & 17 deletions

File tree

‎.changeset/38984-event-seq-race.md‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
'@objectstack/metadata-core': patch
4+
---
5+
6+
fix(metadata-protocol): concurrent saves on a connection with no transaction no longer collide on the history event number
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
On a database connection that gives no transaction (remote Turso), several metadata saves made at once each read the same highest event number from `sys_metadata_history` and took the next one. The unique index on `event_seq` let one history row in and refused the others with `409 DUPLICATE_RECORD` ("No record was written."), while every one of those saves had already written its `sys_metadata` row. History lost the entries, and an agent retried saves that had landed.
12+
13+
Now, where the write runs with no transaction, the history append reads the event number again after a short random wait and inserts again, up to eight attempts. Each save that answers success has its row and its history row, and the number it answers, and broadcasts to `watch()` subscribers, is the one stored. The same holds for the tombstone of an active delete.
14+
15+
When concurrent writes still keep the history row out, the save answers `409 CONCURRENT_UPDATE` with a sentence that says what is stored:
16+
17+
- the write was undone (a new draft removed, an updated row put back, a deleted row restored), so nothing from it is stored; or
18+
- another writer had already replaced the row, so this write is not stored; or
19+
- the row was written without its history row: a concurrent save of the same item recorded the same version first (this case is not retried, because numbering past it could leave the newest history version naming a different body than the live row), or undoing the write failed.
20+
21+
None of these answers says "no record was written" about a row that was written. A history insert that fails for another reason (a dropped connection, say) is answered as before.
22+
23+
Connections that give a transaction (Postgres, MySQL, file SQLite, the in-memory driver) are unchanged: one attempt, and a refused history row rolls the whole save back.
24+
25+
In `@objectstack/metadata-core`, the `sys_metadata_history` object's docblock now says that `event_seq` is derived inside a transaction only where the connection gives one.

‎packages/metadata-core/src/objects/sys-metadata-history.object.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,12 @@ import { ObjectSchema, Field } from '@objectstack/spec/data';
2222
* go through `(type, name, version)` exclusively.
2323
*
2424
* • `event_seq` is the environment's monotonic event-log cursor.
25-
* Producers compute `MAX(event_seq) + 1` inside the same transaction as
26-
* the parent `sys_metadata` write.
25+
* Producers compute `MAX(event_seq) + 1` in the same unit of work as the
26+
* parent `sys_metadata` write, which is a transaction only where the
27+
* connection gives one: remote Turso gives none (ADR-0119 D1), so two
28+
* concurrent producers can derive the same number. The unique
29+
* `(event_seq)` index below refuses the second; `SysMetadataRepository`
30+
* then derives the number again, or undoes its parent write and says so.
2731
*
2832
* • `version` is the per-(type,name) lineage counter. Producers compute
2933
* `MAX(version) + 1 WHERE type = T AND name = N` so delete + recreate

0 commit comments

Comments
 (0)