Skip to content

Commit 976770c

Browse files
fix(metadata-protocol): a refused package publish leaves nothing live on a runtime that cannot roll back (#32454)
Fixes #32396 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:软件包「全部发布」(`publishPackageDrafts`) 在不能回滚事务的运行时(例如远程 Turso)上,也做到「要么全部生效,要么都不生效」。 - 为什么改:云端实测:11 个草稿中第 9 个被拒后,前 8 个已经上线,提示却说「没有内容生效」。原因是发布门只看引擎有没有 `transaction` 方法,没看驱动能不能真正回滚。 - 风险与回滚:只改变不能回滚的运行时:先把整包逐项校验一遍再写(这类运行时上校验开销翻倍);写入中途失败时,把已上线的项逐项撤销、草稿放回。能回滚的 SQL 运行时行为不变。回滚即 revert 本 PR。 - 先看:`protocol-history-and-publish.ts` 中 Phase 0 循环与 `catch` 里调用 `undoLandedPromotions` 的一段(风险最高);同文件顶部 `undoLandedPromotions` 本体;新测试 `protocol-publish-drafts-all-or-nothing.test.ts`。 - 两分钟验证:`pnpm --filter @objectstack/metadata-protocol exec vitest run src/protocol-publish-drafts-all-or-nothing.test.ts`,预期 9 passed。 - 需要你做的:无,席位落地。 ## What changes ADR-0067 D2, verbatim: "All metadata writes in a turn execute inside **one `engine.transaction()`**; any failure rolls the whole commit back — no half-built app, no orphan rows, no partial visibility flip." The publish dialog promises the same: 「发布将一次性发布此包全部 11 个待发布草稿:要么全部生效,要么都不生效」, and the refusal toast says 「没有内容生效:软件包作为一个整体发布,其余草稿会等待这项修复。」 This PR makes the door keep that promise. It does not soften the words. **The cause, from the code, reproduced in-repo.** `publishPackageDrafts` promoted the drafts one by one and relied on `engine.transaction()` to undo the earlier promotions when a later one was refused. It chose that path with `typeof engine.transaction === 'function'`, which is true on every real engine. But `ObjectQL.transaction()` runs the callback with **no transaction and no rollback** when the default driver declares none (the ADR-0119 D1 degrade). The remote Turso transport declares exactly that (`supports.transactionsUnsupported`). On such a runtime every promotion before the refused draft was already durable, and the refusal path still reported "nothing landed". The card's other hypothesis, writes not joining the ambient transaction, does not produce this prefix shape in-repo: a cross-datasource business write inside the transaction is refused at the first item. **The fix (only where `engineCanRollBack(engine)` answers no).** That is the predicate `batchData`'s atomic gate and `/discovery`'s `transactionalBatch` already share, and it reads the driver's declaration as well as the engine method. 1. **Phase 0, judge before writing.** Every draft goes through `promoteDraftForPublish` with a new `judgeOnly` flag. Every refusal fires exactly as before, and the method returns just before `repo.promoteDraft`, so a refused draft refuses the batch with nothing written. This is the class the card hit. Phase 1 still judges each draft again as it promotes it, so nothing it refused before is now let through. Phase 0 can only refuse what Phase 1 would also refuse: the gates read the registry (untouched until Phase 2), the batch closure, or conflicts with already-live store rows. 2. **Undo for what Phase 0 cannot see.** That covers a refusal only an earlier promotion provokes, a draft saved under the publish, or a store fault. The `catch` undoes every promotion already made, newest first, through `undoLandedPromotions`, before anything reports the refusal. A row the publish created is removed. A row it edited is restored to its prior version, read from the existing ADR-0067 pre-publish capture. The consumed draft is put back unchanged (same hash, same version token). Each undo write takes the registry heal (`restoreArtifactRegistryView`), as the stored-row census requires. Phase 2 never ran, so there is no event, materialization or `allowed` audit row to undo. 3. **Honest text when the undo itself fails.** That item's `failed[]` entry carries no `BATCH_ABORTED` (that code means "not published") and says it is live. One `console.error` names the live items, the consequence and the fix. The `batch_aborted` audit note stops saying "nothing landed". On the other paths the non-causal sentence now says how nothing landed: the transaction rolled back, the promotions were put back, or nothing was promoted. Runtimes whose engine can roll back take exactly the old path: no judging pass and no undo. The rolling-back pins below hold that. The method's contract docblock in `protocol.ts` said "Per-item failures are collected and do NOT abort the rest", which was stale since ADR-0067 D2. It now states all-or-nothing. The return type is unchanged, so the `#9406` conformance-suite obligation is not triggered. Ruling markers in the touched files that bind this edit, all kept: - ruling 6624345766: the facet stays a stateless host facet; the new helpers are module functions taking the host. - The maintainer's ruling that advisories ride each `published[]` element, with no parallel top-level map: untouched. - The pre-publish capture still discriminates its read failure by error type (the maintainer's ruling for that family): untouched. ## Tests New suite `packages/metadata-protocol/src/protocol-publish-drafts-all-or-nothing.test.ts`. It stages the card's eleven drafts in the card's order through the real `saveMetaItem`, publishes them through the real `publishPackageDrafts`, and stubs nothing on the gate or promotion path. Item 9 is refused by the real publish-time `lint-autonumber-formats` rule (`QJ{YYYYMM}-{0000}` on `leave_no`). The stub engine has two modes. `degrading` is modelled on `ObjectQL.transaction()` over a driver that declares no transactions. `rollingBack` snapshots and restores. Nine pins: - Refusal at item 9 of 11 (`degrading`): `outcome: 'refused'`, `publishedCount: 0`, causal `code: 'INVALID_METADATA'` with exactly one error finding (on `leave_no`), the other ten `BATCH_ABORTED`. **Nothing active, all eleven drafts pending with their pre-publish hashes.** - The same refusal serves nothing as published: no app on `getMetaItems({ type: 'app', packageId })` (the read the REST door's visibility flip uses); `runPublishSideEffects`, `applyRegistryWriteThrough` and `emitMetadataMutation` never called; no `publish`/`allowed` audit row; exactly one `batch_aborted` row, on the causal object; no commit row; **zero history events**. - Phase 0 judged the first nine drafts with `judgeOnly` and made no write call. - A clean batch (`degrading`) publishes all eleven: 11 `allowed` publish audit rows and 1 commit. - A write-time failure at item 9 (`METADATA_CONFLICT` 409, after Phase 0 judged everything clean) undoes items 1–8. The app, live at v1 before the batch, is restored to v1. The created rows are removed. All drafts are back with their hashes. - An undo that fails (the dataset's removal throws) is reported: that `failed[]` entry has no `code`, the dataset is still active, one `console.error` names it, and the audit note does not say "nothing landed". - `rollingBack`: the refusal is undone by the transaction with no `judgeOnly` call, and a clean batch publishes all eleven. The refusal pins assert `code` plus `outcome`. This door answers a refused batch on HTTP 200 by its declared contract (`PublishPackageDraftsResponseSchema`), and `failed[]` elements carry no per-item status. Also changed: - `packages/objectql/src/protocol-publish-package-drafts.test.ts`: its double has no `transaction()`, so it now counts the three judging calls and the three writes apart, instead of six undifferentiated calls. - `protocol.view-expansion-reconcile-call-sites.test.ts` records the undo's three stored-row writes and their heal route. - `scripts/engine-double-contract.pinned.json` learns the new suite's three pinned seams (written by the gate's `--write`). <details><summary>Reproduction before the fix (cd9f896, the suite's store pin, degrading runtime)</summary> ``` AssertionError: a refused batch promoted drafts before the refused item — the half-landing the card measured: expected [ 'app/leave_management', …(7) ] to deeply equal [] + "app/leave_management", + "dashboard/leave_stats", + "dataset/nyd2_leave_request_ds", + "view/nyd2_leave_request.leave_calendar", + "view/nyd2_leave_request.leave_ledger", + "view/nyd2_leave_request.leave_month_ledger", + "view/nyd2_leave_request.leave_pending", + "view/nyd2_leave_request.leave_status_board", Tests 1 failed | 1 passed (2) ``` The response in the same run already said `outcome: 'refused'`, `publishedCount: 0`. </details> <details><summary>Ablation (mutation committed first; restore proven)</summary> `node scripts/ablation-replace.mjs` on `protocol-history-and-publish.ts`, anchor `const canRollBack = engineCanRollBack(this.engine);` replaced by the pre-fix probe `const canRollBack = typeof this.engine?.transaction === 'function';`. Anchor x1→x0, blob `92a0e25b57a3`→`9d513072b99e`. The suite imports `./protocol.js` from `src/`, so no build sits between mutation and run. ``` × a refusal at item 9 of 11 leaves every draft pending, byte for byte, and nothing active × …and serves nothing as published: no app on the read the visibility flip uses, no registry write-through, no event, no allowed audit row, no commit × judges the whole batch before promoting any of it, and promotes nothing once a draft is refused × a failure the judging pass cannot see undoes every promotion already made: created rows removed, an edited row restored, drafts put back × an undo that fails is reported, never hidden: the live item is not marked BATCH_ABORTED, and the error log names it Tests 5 failed | 4 passed (9) ok restored: blob == HEAD (92a0e25) and `git diff HEAD` is empty ``` The four that stay green are the staging check, the two clean batches and the rolling-back refusal, which is the expected direction. The ablation ran at `ed1ed884a2`. The two later commits change only the undo's registry route; the census and pin runs at the final head are listed below. </details> ## Acceptance notes - **ADR-0067 D2's driver caveat.** It reads "atomicity is a SQL-driver guarantee. Production is SQL; document the gap, don't paper over it." The remote Turso transport is a production transport with no transactions, so that premise no longer holds. This PR keeps D2 at the door without the driver, by judging first and undoing where it cannot roll back. Whether the ADR's caveat line is amended is a Tier H edit and the maintainer's to decide. Carrier: maintainer. - **The REST door's ADR-0045 visibility flip** (`packages/runtime/src/domains/packages.ts`, `POST /packages/:id/publish-drafts`) runs after `publishPackageDrafts` whatever its `outcome`. On a refused publish it would still set `_unpublished: false` on any app already ACTIVE for the package, which is a partial visibility flip ADR-0067 D2 rules out. In the card's case this PR leaves no app active, and the pin shows the flip's read returns nothing. An app that was already active-but-unpublished before a refused publish is not covered. Read from the code, not measured through the door. Carrier: seat. - **Residual limits of the undo,** on a runtime that cannot roll back: - A causal promotion that the store itself half-wrote (active row stored, history append then failed) is not in the landed list and is not undone. That is the store's own non-atomicity. - The put-back draft keeps its body and hash but not its per-key provenance (`draft_changes`). - The history log keeps the publish events beside their undo events, append-only as a D3 revert is. - The judging pass doubles gate work on those runtimes only. - **Out of scope:** the card's "Secondary" (`verify_build` and the `create_metadata` result not surfacing the autonumber refusal before publish) is not addressed here. Carrier: seat. - **Beyond the claimed file surface:** the objectql orchestration test above, and `scripts/engine-double-contract.pinned.json`, which the gate requires for a new suite. Neither `packages/metadata` nor `packages/spec` is touched. ## Verification All readings are at head `4831a9b995` unless stated otherwise. <details><summary>Affected-package tests and typecheck</summary> - `pnpm --filter @objectstack/metadata-protocol typecheck`: exit 0 (on the final content). - `@objectstack/metadata-protocol` build: exit 0. Then the 61 `metadata-protocol` test files that name `publishPackageDrafts`/`promoteDraftForPublish` or carry publish, draft, batch, commit or revert in their name: `Test Files 61 passed (61)`, `Tests 1542 passed (1542)`. This includes the two stored-row and write-through censuses. - The 11 `@objectstack/objectql` files that test this door, read through the rebuilt `dist/`: `Test Files 11 passed (11)`, `Tests 169 passed (169)`. - Narrowed, and declared: the rest of the `metadata-protocol` suite, and the `runtime` suites that mock this door, are left to CI's Test Core. These runs went unlocked because the shared verify lock was held by a sibling's run for more than 30 minutes. </details> <details><summary>Gate families (dispatch-gates --commands, 80 derived)</summary> Derived at `4831a9b995` (6 paths): 80 commands. `dispatch-gates --ran`: "80 derived famil(ies) accounted for". Each exit code was captured before any pipe. - **73 source-reading families: exit 0** at `4831a9b995`. Every derived command except the seven below, among them `check:durability-log-level`, `check:startup-registry-verdict`, `check:where-matcher`, `check:objectql-double-limit`, `check:engine-double-contract`, `check:error-code-casing`, `check:doc-authoring`, `check:issue-citations`, `check:facade-delegation-only` and `check:cross-package-test-inputs`. - **`check:dts-closure`, `check:sourcemap-no-sources-content`, `check:published-files`: exit 0** at `4831a9b995`, after the build. - **`check:type-check-debt`, `check:type-check-coverage`: exit 0** at `ec95718334`. The later commits change only the undo's registry route and two test files, and the package typechecks clean at the final content. - **`check:dual-build-cjs-loads`, `check:lean-entry-closure`: NOT MEASURED** locally (exit 3, `PREREQUISITE NOT MET`: they load every package's built output). CI runs them. - Red at the first run and fixed on this branch: `check:engine-double-contract` (the ledger learned the new suite's seams), `check:error-code-casing` (two D6b `adr0112-ok` markers on the persisted audit code), `check:objectql-double-limit` (the `find` double applies `limit`), `check:where-matcher` (the where double refuses combinators it does not implement). - Changed-file eslint (`eslint --no-inline-config` on the touched sources): exit 0, no findings. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01J8VVAnTcb4cZVkPdhkPicW)_ --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 9dbcc1f commit 976770c

7 files changed

Lines changed: 907 additions & 93 deletions
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
---
4+
5+
fix(metadata-protocol): a refused package publish leaves nothing live on a runtime that cannot roll back
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A package publish (`publishPackageDrafts`, behind `POST /packages/:id/publish-drafts` and Studio's publish-all) is all-or-nothing (ADR-0067 D2), and relied on `engine.transaction()` to undo the drafts it had promoted before a refused one. On a runtime whose default driver declares no transactions, such as the remote Turso transport, the engine runs that callback with no rollback. A draft refused at item 9 of 11 therefore left items 1–8 live while the response said nothing had taken effect.
11+
12+
Where the runtime cannot roll back (the `engineCanRollBack` check that `/discovery`'s `transactionalBatch` already answers), the publish now judges every draft before it promotes any, so a refusal leaves every draft pending and nothing served. A failure that only the writes themselves can meet, such as a draft saved under the publish or a store fault, undoes every promotion already made before the refusal is reported: rows the publish created are removed, rows it edited go back to their prior version, and each consumed draft is put back unchanged. Each undo step leaves its own history event. An undo that itself fails is named in `failed[]`, without `BATCH_ABORTED`, and in an error log, instead of being reported as "nothing landed". Runtimes with a real transaction behave exactly as before.

‎packages/metadata-protocol/src/protocol-history-and-publish.ts‎

Lines changed: 337 additions & 88 deletions
Large diffs are not rendered by default.

‎packages/metadata-protocol/src/protocol-publish-drafts-all-or-nothing.test.ts‎

Lines changed: 517 additions & 0 deletions
Large diffs are not rendered by default.

‎packages/metadata-protocol/src/protocol.ts‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9673,6 +9673,8 @@ export class ObjectStackProtocolImplementation implements
96739673
member?: string;
96749674
/** The registry question this promotion asks (`registry-question.ts`). */
96759675
registryQuestion: RegistryQuestion;
9676+
/** [#32396] Judge every refusal, write nothing: the answer then carries no `result`. */
9677+
judgeOnly?: boolean;
96769678
}): Promise<{
96779679
singularType: string;
96789680
/**
@@ -9687,7 +9689,10 @@ export class ObjectStackProtocolImplementation implements
96879689
* discipline — per the maintainer's ruling, no parallel top-level map.
96889690
*/
96899691
advisories: RuntimeAuthoringIssue[];
9690-
result: { version: string; seq: number; item: MetadataItem; packageId: string | null };
9692+
/** What the promotion wrote. Absent exactly when `judgeOnly` was stated. */
9693+
result?: { version: string; seq: number; item: MetadataItem; packageId: string | null };
9694+
/** [#32396] The draft row the promotion consumed. Absent when nothing was written. */
9695+
promotedDraft?: { body: unknown; hash: string };
96919696
}> {
96929697
// [#29985 codemod] The body moved to `protocol-history-and-publish.ts`; it reaches this class through `protocol-host.ts`.
96939698
return ProtocolHistoryAndPublishFacet.promoteDraftForPublish(protocolHost(this), request);
@@ -9957,8 +9962,13 @@ export class ObjectStackProtocolImplementation implements
99579962
* per-item {@link publishMetaItem} primitive (which runs the overridable /
99589963
* lock guards and refreshes the runtime registry), so this needs NO
99599964
* `metadata` service (unlike `MetadataService.publishPackage`, which reads
9960-
* the in-memory registry and 503s when that service is absent). Per-item
9961-
* failures are collected and do NOT abort the rest.
9965+
* the in-memory registry and 503s when that service is absent).
9966+
*
9967+
* All-or-nothing (ADR-0067 D2): a refusal of any draft refuses the whole
9968+
* batch, and nothing it promoted stays live. [#32396] That holds on a
9969+
* runtime that cannot roll a transaction back too — there the whole batch
9970+
* is judged before any draft is promoted, and a failure only the writes
9971+
* meet undoes the promotions already made — see the body's Phase 0.
99629972
*
99639973
* [#9406] The wire face of this return is DECLARED:
99649974
* `PublishPackageDraftsResponseSchema` in `@objectstack/spec/api` (the

‎packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,11 @@ const WRITES: ReadonlyArray<{ readonly member: string; readonly verb: string; re
167167
{ member: 'reassignOrphanedMetadata', verb: 'this.engine.update(\'sys_metadata\'', route: { sameMember: 'applyRegistryWriteThrough' } },
168168
// [#30000] `os migrate packageless-overlays --apply`: the unbound row, once its pair's row reads back.
169169
{ member: 'migratePackagelessOverlays', verb: 'repo.delete(', route: { sameMember: 'restoreArtifactRegistryView' } },
170+
// [#32396] A refused package publish on a runtime that cannot roll back undoes its promotions: the
171+
// edited row restored, the created row removed, the draft put back, each healed from what the store serves.
172+
{ member: 'undoLandedPromotions', verb: 'repo.restoreVersion(', route: { sameMember: 'restoreArtifactRegistryView' } },
173+
{ member: 'undoLandedPromotions', verb: 'repo.delete(', route: { sameMember: 'restoreArtifactRegistryView' } },
174+
{ member: 'undoLandedPromotions', verb: 'repo.put(', route: { sameMember: 'restoreArtifactRegistryView' } },
170175
];
171176

172177
/** The verb as `WRITES` spells it: no whitespace after its open paren, [#29985] the class as `this`. */

‎packages/objectql/src/protocol-publish-package-drafts.test.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -161,8 +161,14 @@ describe('protocol.publishPackageDrafts (ADR-0033 / ADR-0067 D2)', () => {
161161
{ type: 'object', name: 'student', state: 'active', package_id: 'app.edu' },
162162
{ type: 'view', name: 'course_list', state: 'active', package_id: 'app.edu' },
163163
]);
164-
expect(promote).toHaveBeenCalledTimes(3);
165-
expect((promote.mock.calls[0][0] as any)).toMatchObject({ type: 'object', name: 'course' });
164+
// [#32396] This double has no `transaction()` — a runtime that cannot roll
165+
// back — so the batch is judged whole (`judgeOnly`, nothing written) before
166+
// any draft is promoted, then each draft is promoted once, in order.
167+
const judged = promote.mock.calls.filter(([req]) => (req as any).judgeOnly === true);
168+
const written = promote.mock.calls.filter(([req]) => (req as any).judgeOnly !== true);
169+
expect(judged.map(([req]) => (req as any).name)).toEqual(['course', 'student', 'course_list']);
170+
expect(written).toHaveLength(3);
171+
expect((written[0][0] as any)).toMatchObject({ type: 'object', name: 'course' });
166172
// Side effects ran once per promoted item, AFTER promotion, in order.
167173
//
168174
// [#8820] Was `requestType`, the UNFOLDED spelling Phase 2 also used to

‎scripts/engine-double-contract.pinned.json‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,21 @@
296296
"verb": "update",
297297
"pinned": 1
298298
},
299+
{
300+
"file": "packages/metadata-protocol/src/protocol-publish-drafts-all-or-nothing.test.ts",
301+
"verb": "delete",
302+
"pinned": 1
303+
},
304+
{
305+
"file": "packages/metadata-protocol/src/protocol-publish-drafts-all-or-nothing.test.ts",
306+
"verb": "findOne",
307+
"pinned": 1
308+
},
309+
{
310+
"file": "packages/metadata-protocol/src/protocol-publish-drafts-all-or-nothing.test.ts",
311+
"verb": "update",
312+
"pinned": 1
313+
},
299314
{
300315
"file": "packages/metadata-protocol/src/protocol-publish-drafts-closure.test.ts",
301316
"verb": "delete",

0 commit comments

Comments
 (0)