Repository navigation
Commit fc7534a
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
- packages
- metadata-core/src/objects
- metadata-protocol/src
- scripts
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
22 | 22 | | |
23 | 23 | | |
24 | 24 | | |
25 | | - | |
26 | | - | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
27 | 31 | | |
28 | 32 | | |
29 | 33 | | |
| |||
0 commit comments