diff --git a/.changeset/32504-in-memory-rollback-docblocks.md b/.changeset/32504-in-memory-rollback-docblocks.md new file mode 100644 index 00000000000..396c0287f8b --- /dev/null +++ b/.changeset/32504-in-memory-rollback-docblocks.md @@ -0,0 +1,16 @@ +--- +'@objectstack/spec': patch +'@objectstack/objectql': patch +'@objectstack/metadata-protocol': patch +--- + +docs(spec, objectql, metadata-protocol): the transaction docblocks no longer say the in-memory driver cannot roll back + +Clause-②: no +Metadata-protocol: none + +TSDoc only; no behaviour, type or export changes. The edited docblocks land in the shipped `dist/*.d.ts` (and `@objectstack/spec` ships `src/**/*.zod.ts` itself), so they publish: + +- `driverSupportsTransactions` (`@objectstack/spec`): the in-memory driver is no longer listed among drivers with no `beginTransaction`; it implements `beginTransaction` / `rollback` by snapshotting its whole store. +- `EngineTransactionOptions.require` (`@objectstack/spec`): the callers the no-transaction degrade suits are test doubles; the in-memory driver is no longer named among them, since it implements `beginTransaction`. +- `ObjectQL.transaction` (`@objectstack/objectql`) and `SysMetadataEngine.transaction` (`@objectstack/metadata-protocol`): the drivers that cannot roll back are a test double with no `beginTransaction` and those declaring `supports.transactionsUnsupported` (remote Turso, OData). The in-memory driver does roll back, restoring the whole store to its state at begin: no isolation, and a rollback also discards what other callers wrote since that begin, so do not rely on it with concurrent writers. diff --git a/docs/adr/0067-commit-history-and-rollback-for-ai-authoring.md b/docs/adr/0067-commit-history-and-rollback-for-ai-authoring.md index 12f68c208b6..a970018c7bc 100644 --- a/docs/adr/0067-commit-history-and-rollback-for-ai-authoring.md +++ b/docs/adr/0067-commit-history-and-rollback-for-ai-authoring.md @@ -1,6 +1,6 @@ # ADR-0067: Commit history and rollback for AI authoring — turns become atomic, revertible commits -**Status**: Accepted (2026-06-24; completed 2026-07-16) · **Amended** (2026-08-06, #5351/#5696 — the D2 join is now distinguishable (`owned`), and Decision-2's atomicity is enforced as a ONE-datasource promise, with audit rows carved out and possibly orphaned; see the Amendment at the end) — fully implemented: commit grouping (`sys_metadata_commit`), `revertCommit`/`rollbackToPackageCommit`/`listCommits`, REST routes; **Decision-2 landed via #3066**: `publishPackageDrafts` runs every promotion + the commit record inside ONE `engine.transaction()` (two-phase — side effects post-commit), so a commit cannot half-land; `engine.transaction()` joins ambient transactions to make nested repository writes participate. Locked by `protocol-publish-package-drafts.test.ts` (all-or-nothing + rollback tracking) and `engine-ambient-transaction.test.ts`. **Letter index** (2026-08-29, #12786): the Decision headings are relabeled `1.`–`6.` → `D1`–`D6` so `Dk` citations verify — recognition of the record's own numbering (this status line and the Amendment already say "D2"); no decision is renumbered, reordered, or rewritten. · **Amended** (2026-11-12, #32396/#32480 — Decision-2's atomicity holds where the engine can roll back (`engineCanRollBack`), which is not the same line as "a SQL driver"; elsewhere a package publish is judged first and undone by compensation, best effort; see the 2026-11-12 Amendment at the end). +**Status**: Accepted (2026-06-24; completed 2026-07-16) · **Amended** (2026-08-06, #5351/#5696 — the D2 join is now distinguishable (`owned`), and Decision-2's atomicity is enforced as a ONE-datasource promise, with audit rows carved out and possibly orphaned; see the Amendment at the end) — fully implemented: commit grouping (`sys_metadata_commit`), `revertCommit`/`rollbackToPackageCommit`/`listCommits`, REST routes; **Decision-2 landed via #3066**: `publishPackageDrafts` runs every promotion + the commit record inside ONE `engine.transaction()` (two-phase — side effects post-commit), so a commit cannot half-land; `engine.transaction()` joins ambient transactions to make nested repository writes participate. Locked by `protocol-publish-package-drafts.test.ts` (all-or-nothing + rollback tracking) and `engine-ambient-transaction.test.ts`. **Letter index** (2026-08-29, #12786): the Decision headings are relabeled `1.`–`6.` → `D1`–`D6` so `Dk` citations verify — recognition of the record's own numbering (this status line and the Amendment already say "D2"); no decision is renumbered, reordered, or rewritten. · **Amended** (2026-11-12, #32396/#32480 — Decision-2's atomicity holds where the engine can roll back (`engineCanRollBack`), which is not the same line as "a SQL driver"; elsewhere a package publish is judged first and undone by compensation, best effort; see the 2026-11-12 Amendment at the end). · **Amended** (2026-11-14, #32504 — Decision-3's revert doors are not atomic across items: `revertCommit` reverts item by item and reports `reverted[]` and `failed[]`, and `rollbackToPackageCommit` runs one `revertCommit` per commit; neither opens a transaction around the whole; see the 2026-11-14 Amendment at the end). **Deciders**: ObjectStack Protocol Architects **Builds on / amends**: [ADR-0045](./0045-additive-materialization-and-visibility-gate.md) (**amended**: ADR-0045 keeps a *draft + human-confirm* gate on mutations as the safety mechanism; this ADR replaces *confirm-before* with *revert-after* for everything except irreversible data loss, and unifies the two authoring regimes under one primitive — the commit), [ADR-0027](./0027-metadata-authoring-lifecycle.md) (draft workspace — retained as a *review affordance*, demoted from *safety mechanism*), [ADR-0033](./0033-ai-assisted-metadata-authoring.md) ("AI never publishes — it drafts" → **AI commits; commits are revertible**), [ADR-0034](./0034-transactional-writes-and-ambient-transaction.md) (per-write transaction — **extended to span a whole turn**), [ADR-0038](./0038-build-verification-loop.md) (machine gate — runs per commit, before it lands) **Consumers**: `@objectstack/objectql` (commit grouping, atomic turn-apply, `revertCommit`, history query — built on the existing `sys_metadata_history` + `restoreVersion`), `@objectstack/runtime` + `@objectstack/rest` (commit/revert routes), `../cloud/service-ai-studio` (turn = commit; auto-commit policy; data-loss confirmation), `../objectui` (commit timeline + "revert to here") @@ -15,7 +15,7 @@ 1. **A turn is a commit.** Every AI apply (and Studio batch) records its metadata changes as one **commit** — a named group over the existing `sys_metadata_history` event log, tagged with a `commit_id`, actor, message (the user's prompt), and the AI model. The per-item history and full-body snapshots that back rollback already exist; this ADR adds the *grouping* and the *package-scoped HEAD*. 2. **Commits are atomic.** All metadata writes in a turn land in **one transaction** or none do. This closes ADR-0045's residual seam — `publishPackageDrafts` is per-item best-effort today, so a mid-batch failure leaves a half-live app ("claimed 120 rows, opens empty"). A commit cannot half-land. -3. **Rollback is first-class.** `revertCommit(id)` / `rollbackToPackageCommit(id)` restores every item in the target commit atomically, reusing the single-item `restoreVersion` primitive. A revert is a **new forward commit** (git-revert, not reset): history is append-only and never loses the record. +3. **Rollback is first-class.** `revertCommit(id)` / `rollbackToPackageCommit(id)` restores every item in the target commit atomically, reusing the single-item `restoreVersion` primitive. A revert is a **new forward commit** (git-revert, not reset): history is append-only and never loses the record. *(Amended 2026-11-14: neither door is atomic across items — see the Amendment of that date at the end.)* 4. **The confirm gate narrows from "before publish" to "before irreversible data loss."** With atomic + revertible commits, additive *and* mutation turns auto-commit with no per-change confirmation. The only confirmation that remains is destroying **real user data** (§Decision-5). Governed orgs keep their ADR-0045/0027 approval gate by policy — unchanged. 5. **Metadata reverts cleanly; data is made reversible by discipline.** Destructive operations (drop field/object) go **soft by default** — data retained, column/table hidden, recoverable in the ADR-0045 trash window — so their revert restores data losslessly. Hard teardown happens only on explicit discard/GC. This is what makes "revert-after" actually safe. 6. **Substrate: the framework history log is the commit log; package snapshots are named restore points.** `sys_metadata_history` (per-event, lightweight, already carries actor/diff/`operation_type`) is the commit substrate. `sys_package_version` (full-bundle, heavy) is reserved for **named restore points** — the escape hatch cut before a risky revert, and marketplace release — *not* a per-turn snapshot. @@ -80,8 +80,8 @@ All metadata writes in a turn execute inside **one `engine.transaction()`**; any ### D3 — Rollback is first-class and append-only -- `revertCommit(commitId)` — restore every item the commit touched to its **pre-commit** body, atomically (reuse `restoreVersion` per item inside one transaction). Recorded as a **new forward commit** (`operation_type='revert'`), so history is never rewritten and a revert is itself revertible. -- `rollbackToPackageCommit(commitId)` — revert the package's HEAD back through every commit after the target, as one transaction. This is the "一层一层回退" the founder described — **commit-granular, not per-artifact** (§Resolved-1). +- `revertCommit(commitId)` — restore every item the commit touched to its **pre-commit** body, atomically (reuse `restoreVersion` per item inside one transaction). Recorded as a **new forward commit** (`operation_type='revert'`), so history is never rewritten and a revert is itself revertible. *(Amended 2026-11-14: no transaction spans the items; the revert runs per item and reports `reverted[]` and `failed[]`; and reverting a revert commit restores nothing today — see the Amendment of that date at the end.)* +- `rollbackToPackageCommit(commitId)` — revert the package's HEAD back through every commit after the target, as one transaction. This is the "一层一层回退" the founder described — **commit-granular, not per-artifact** (§Resolved-1). *(Amended 2026-11-14: not one transaction; one `revertCommit` per commit, each step's failures collected — see the Amendment of that date at the end.)* - Revert restores **metadata** deterministically. Its effect on **data** is governed by §5. ### D4 — The confirm gate, relocated @@ -349,3 +349,95 @@ declared no-rollback degrade, and its D1-R4. **Implemented in** the gate is `engineCanRollBack` in `packages/core/src/utils/migration-journal.ts`. Pinned by `protocol-publish-drafts-all-or-nothing.test.ts`. + +--- + +## Amendment (2026-11-14, #32504) — Decision-3's revert doors are not atomic across items; a revert runs per item and reports per item + +Decision-3's design — a revert restores every item the commit touched to its +pre-commit body, reusing `restoreVersion`, and is recorded as a **new forward +commit** — is **unchanged**. What is amended is the atomicity TL;DR 3 and D3's +first two bullets attach to it: "atomically", "inside one transaction", "as one +transaction". The code on `main` never opened that transaction. This record now +says what the two doors do instead; it records the code and does not decide +whether a revert should stay this way (below). + +### What the doors do + +Read from the code on `main` at `ba35dfd7` — a reading of that date, not part +of the decision: + +- **`revertCommit`** walks the commit's items in reverse apply order. An item + the commit created is soft-removed; an item it modified is restored to its + `prevVersion` through `restoreVersion`, as D3 says. Each item's own write — + the row and its history event — runs in the repository's per-item `withTxn`, + so it rolls back as one where the engine can roll back (the gate of the + 2026-11-12 Amendment). **No transaction spans the items**: the function + opens none. An item that is refused, or whose removal or restore throws, + goes into `failed[]` with its client-facing error (and its code, where it + has one), and the walk goes on to the next item. What follows an item's row + write does not reach `failed[]`: the registry write-through (or, on the + soft-remove limb, the registry heal) and the projector catch their own + faults and log them, and their results are not read; storage sync reports on + `advisories`. Such an item is still reported in `reverted[]`, and `success` + does not see the fault. (One exception, on the soft-remove limb: for an + `object_extension` item, a store fault while the heal re-reads the stored + extensions is rethrown, so that item lands in `failed[]` with its row + already removed.) +- **An item can also be skipped.** An item recorded as existing before the + commit but with no `prevVersion` takes neither limb: it appears in neither + `reverted[]` nor `failed[]`. Every revert commit writes its own plan that + way (`existedBefore` true for an item it restored, `prevVersion: null`), and + a revert commit can be reverted, so reverting a revert commit restores none + of the items it restored (and sends the items it removed down the + soft-remove limb again, recreating nothing). +- **The revert commit.** When the walk ends, it is written from `reverted[]` — + what was reverted, not what the commit named — and the answer's `success` is + true only when `failed[]` is empty and at least one item was reverted. +- **The revert commit itself is best effort.** `recordPackageCommit` catches + every error: where `sys_metadata_commit` is unprovisioned it logs once at + `info`, and where the write fails it logs at `error`, and either way it + returns no record. `revertCommit` then answers without `revertCommitId` and + returns normally. Such a revert is on no package-commit timeline (each + item's `sys_metadata_history` event is still written), so there is no + commit to revert. Where the record lands, reverting it still restores + nothing, as the skipped outcome above says. +- **`rollbackToPackageCommit`** runs one `revertCommit` per `apply` commit + newer than the target, newest first. A step that throws, and every item a + step reports in its own `failed[]`, goes into the rollback's `failed[]`; + neither stops the rollback, and every step that returns has attempted its + own revert commit, best effort as above. + +So a revert in which one item fails leaves the package **partly reverted**: +the item's neighbours are reverted (and recorded, where the record write +lands), the failed item is named in the response, and `success` is false. A +fault after an item's row write is not named there, and a skipped item is +not named at all. +That is the half-land shape D2 exists to prevent on publish, here on the +revert side — reported, not prevented. + +### What this amendment does not decide + +- **Whether a revert should be atomic.** Running `revertCommit` (or a whole + rollback) inside one `engine.transaction()` would change what a caller sees — + a revert with one refused item would then revert nothing — and would hold + only where the engine can roll back. That is a maintainer decision, not made + here. +- **Whether a revert commit should carry the versions it restored**, so that + D3's "a revert is itself revertible" holds, and **whether a fault after an + item's row write should reach `failed[]`**. Both are code questions; this + record states what the code does today. +- It changes nothing in Decision-2, the package-publish door, or the + 2026-08-06 carve-out (audit rows written during rolled-back work still + remain). + +**Recorded by**: the triage of #32504 ("stale text only"), dispatched as a text +correction: this record follows the code; no historical text is rewritten. +**Implemented in** `packages/metadata-protocol/src/protocol-package-commits.ts` +(`revertCommit`, `rollbackToPackageCommit`). Where the doors' docblocks on +`ObjectStackProtocolImplementation` in `protocol.ts` say more than the code +(a revert answering `success: true` is one the process has acted on; a revert +is itself revertible; each rollback step records its revert commit), this +record states the code. Pinned by +`protocol.revert-stored-type-canonical.test.ts` ("reverts the neighbours of a +refused item and reports the mix honestly"). diff --git a/packages/metadata-protocol/src/sys-metadata-repository.ts b/packages/metadata-protocol/src/sys-metadata-repository.ts index 74759d91d7d..e76b3df80e2 100644 --- a/packages/metadata-protocol/src/sys-metadata-repository.ts +++ b/packages/metadata-protocol/src/sys-metadata-repository.ts @@ -392,9 +392,15 @@ export interface SysMetadataEngine { ): Promise<{ deleted: number }>; /** * Optional. Falls through to direct callback invocation if the - * underlying driver lacks ACID support (matches the real + * underlying driver cannot open a transaction (matches the real * `ObjectQL.transaction` semantics). Repository code must not rely on - * rollback for correctness against in-memory drivers. + * rollback for correctness where the engine cannot roll back + * (`engineCanRollBack` answers no: a default driver with no + * `beginTransaction`, or one declaring `supports.transactionsUnsupported` + * as remote Turso does). The in-memory driver rolls back, by restoring a + * snapshot of its whole store to its state at begin: no isolation, and a + * rollback also discards what other callers wrote since that begin, so it + * is not safe with concurrent writers. * * Typed off the `objectql` slot contract (ADR-0119 D1) rather than restated * by hand, so this stub surface cannot drift from `ObjectQL.transaction`. @@ -758,9 +764,14 @@ export class SysMetadataRepository implements MetadataRepository { /** * Run `cb` inside `engine.transaction(...)` if the engine supports it, * otherwise fall through to a direct call. Matches the real - * `ObjectQL.transaction` semantics — in-memory drivers (and our test - * fakes) get no rollback, which is acceptable because production - * always runs on a SQL driver with real ACID. + * `ObjectQL.transaction` semantics — a test fake with no `transaction`, + * and an engine whose driver cannot roll back (no `beginTransaction`, or + * `supports.transactionsUnsupported` as remote Turso declares), get no + * rollback: the degrade ADR-0119 D1 declares. A SQL driver is not by + * itself a guarantee of rollback (ADR-0067, 2026-11-12 amendment); the + * in-memory driver does roll back, by restoring a snapshot of its whole + * store to its state at begin: no isolation, and a rollback also discards + * what other callers wrote since that begin. */ private async withTxn(cb: (ctx: any) => Promise): Promise { if (typeof this.engine.transaction === 'function') { diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 7b5c668829a..ef8ec189d03 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -5304,8 +5304,14 @@ export class ObjectQL implements IObjectQLEngine { * from a transport that inherited one it cannot honour (#18063) — the * callback * runs directly with the supplied base context (no rollback). This keeps - * the API safe to call on drivers without ACID support (e.g. the - * in-memory driver in tests). It is DECLARED behaviour (ADR-0119 D1), not + * the API safe to call on drivers that cannot roll back (a test double + * with no `beginTransaction`, remote Turso, OData). The in-memory driver + * is not one: it implements `beginTransaction` / `rollback` over a + * snapshot of its whole store, so the callback runs inside a + * transaction there, with no isolation: its rollback restores the whole + * store to its state at begin, discarding what other callers wrote since + * then too (unsafe with concurrent writers). The + * degrade is DECLARED behaviour (ADR-0119 D1), not * a bug to be discovered — but since v17 it is no longer *silent*: the * degrade warns once per driver (#4619, {@link warnTransactionUnsupported}), * and a caller who cannot live with it says so with `opts.require: true`, diff --git a/packages/spec/src/contracts/objectql-engine.ts b/packages/spec/src/contracts/objectql-engine.ts index bc93b121ee4..173657384bc 100644 --- a/packages/spec/src/contracts/objectql-engine.ts +++ b/packages/spec/src/contracts/objectql-engine.ts @@ -148,7 +148,8 @@ export interface EngineTransactionOptions { * Default (`undefined` / `false`) keeps ADR-0119 D1's declared degrade: a * driver without `beginTransaction` runs the callback with no transaction * and no rollback, warning once. That degrade is right for callers who can - * live without atomicity (test doubles, in-memory drivers) and wrong for + * live without atomicity (test doubles; the in-memory driver is not one of + * these drivers: it implements `beginTransaction`) and wrong for * callers whose whole reason to open a transaction is the rollback. * * With `require: true` the engine THROWS instead of degrading, before the diff --git a/packages/spec/src/data/driver.zod.ts b/packages/spec/src/data/driver.zod.ts index 9dc43a28384..75d8a27236e 100644 --- a/packages/spec/src/data/driver.zod.ts +++ b/packages/spec/src/data/driver.zod.ts @@ -839,10 +839,12 @@ export type PoolConfigParsed = z.infer; * * Two clauses, and they answer different questions: * - * 1. **The method is there.** A driver with no `beginTransaction` (the - * in-memory driver, a test double, a foreign engine) has nothing to open. - * This clause is unchanged from the pre-`transactionsUnsupported` gate and - * is why the bit's absence keeps every existing driver exactly as it was. + * 1. **The method is there.** A driver with no `beginTransaction` (a test + * double, a foreign engine) has nothing to open. The in-memory driver is + * not one: it implements `beginTransaction` / `rollback` by snapshotting + * its whole store and restoring the snapshot. This clause is unchanged + * from the pre-`transactionsUnsupported` gate and is why the bit's + * absence keeps every existing driver exactly as it was. * 2. **The transport did not deny it.** `supports.transactionsUnsupported` * is how a subclass that INHERITED the method says its own transport * cannot honour it. Without this clause a class cannot opt out of a door