Skip to content

Commit 70f454a

Browse files
fix(metadata): two Studio Saves over one published item are no longer last-writer-wins (#36720)
<!-- claude-projects-attribution: {"github_login":"os-alice"} --> _Requested by **Alice** · [project thread](https://claude.ai/code/project/chan_01NoziMoftaSPmzgKNjJGePH?thread=cmsg_01NoziMoftaSPmzgKNjJGePHJDtYrcfiNfCiqhM4g8dFWZ)_ Fixes #36601 Clause-②: yes (widening) — two new optional members join what the API accepts and answers: `PublishMetaItemRequestSchema.parentVersion` (the `If-Match` / `If-None-Match: *` pin on `POST /meta/:type/:name/publish`) and `GetMetaItemLayeredResponseSchema.overlayVersion` (served on `GET /meta/:type/:name/layers`); nothing is removed or narrowed, and a publish that names no version behaves as before Metadata-protocol: added Skills-docs: none — the two members are REST wire members (a publish precondition and a layered-read answer member) that Studio sends and reads; no metadata author writes them and no published skill teaches the publish route's headers ## 维护者速读 - 在 Studio 对象页,两位管理员同时改同一个已发布对象时,后保存的人不再悄悄覆盖先保存的人,而是看到“你打开之后这里已被修改”,可选重新加载、确认覆盖或继续编辑。 - 属于元数据并发保护:草稿已有版本锁,这次补上“直接发布”这一步,替同时编辑的管理员解决改动丢失。 - 出错的话,最坏是保存时多弹一次冲突对话框或保存被拒;不带版本的旧客户端行为不变,撤回本次合并即可恢复原状。 - 要你做的事:无。 ## What changes **Server (`@objectstack/spec`, `metadata-protocol`, `rest`, `runtime`)** - `GET /meta/:type/:name/layers` answers `overlayVersion`: the keyed version token of the stored active row at the read's address (`?package=`). It is the same token the plain uncached read serves as `version` and a publish receipt serves as `version`; `null` when no active row is stored there. Opt-in on the protocol (`withVersion`), turned on by the REST route and the runtime meta domain, so in-process layered readers pay no extra read. - `POST /meta/:type/:name/publish` takes that token as `If-Match`, or `If-None-Match: *` for "no active row here". The headers are parsed by the save door's own parser (`metaSaveRequestOptions`), so the two doors refuse the same malformed preconditions with `400 VALIDATION_ERROR`. - A stale pin is refused `409 METADATA_CONFLICT` with `currentVersion`, through the existing `metadataConflictRefusal`. Nothing is promoted and the draft stays pending. - The pin is checked by the store's put lock on the promoting write (`promoteDraft`'s new `expectedActiveHash` becomes the put's `parentVersion`), not by an earlier separate read. The token is converted with the existing `storedParentForToken`. - A publish with neither header is unpinned, exactly as before. **Studio (`@object-ui/data-objectstack`, `app-shell`, `i18n`)** - `MetadataClient.publish` takes `ifMatch` / `ifNoneMatch` and sends them as headers. - `DraftVersionGuard` holds a second pin per item, for the published row: `recordPublished` (from the load's `/layers` read, via `publishedPinOf`) and `publish` (sends the pin, then holds the receipt's version so one editor's Saves chain). - On a conflict, the guard asks through the same dialog as a stale draft, with `layer: 'published'` wording ("This changed since you opened it"): - **Reload** takes back the draft the Save wrote, then re-reads the live object. - **Overwrite**, after a confirmation, re-publishes pinned to the refusal's `currentVersion`. A publish landing in between is asked about again. - **Keep editing** publishes nothing, takes back the saved draft, and leaves the edits on the page with the draft conflict's own "Not saved" line. - `publishSavedItem` takes the guard's publish as an optional `pinned` argument. Overloads keep the unpinned callers' outcome type unchanged. - Studio's object page (`StudioDesignSurface` data pillar) is wired: its load records the published pin and its Save publishes through it. - New studio locale keys (en, zh): `engine.draftConflict.publishedTitle`, `publishedDescription`, `publishedOverwriteTitle`, `publishedOverwriteDescription`. **Not in this PR.** The object extension, hooks, pair-actions and flow editors still publish unpinned, so their behaviour is unchanged. Each needs its own load to read `/layers`. This is reported to the seat as follow-up. ## Tests - `packages/rest/src/meta-item-publish-version-pin.test.ts` (new, real stack: better-sqlite3, cache off). Cases: - the unpinned control (last writer wins, as before) - two pinned Saves: the second gets `409`, `currentVersion` equals A's receipt and the next `/layers` token, B's draft stays pending, and an overwrite pinned to `currentVersion` is accepted - the token agrees across `/layers`, the plain read and the publish receipt - a draft-only item serves `null`, its first `If-None-Match: *` publish succeeds and a second is refused - a guessed raw token gets `409` - two malformed header pairs get `400` - `DraftConflictDialog.test.tsx`, new describe for the published pin: - `publishedPinOf` - pin then receipt chaining - reload order (publish, then discard, then reload, with pins cleared) - overwrite and keep-editing (the kept-editing error is told apart) - a `null` pin, and unpinned - `StudioDesignSurface.draftVersionConflict-11773.test.tsx`, new describe "two Saves over one published object are not last-writer-wins": - keep editing - reload - overwrite - one editor's pins chain - a server without `overlayVersion` gets an unpinned publish - Ablation: with the Save's publish unpinned again, 4 of the 5 race cases fail. The control stays green, as it should. ## Acceptance notes - Ruling ①: the publish answer already served `version` (the active token). The new piece is the read Studio loads from, so `/layers` now answers `overlayVersion`, the same token. - Ruling ②: the refusal is the typed `409 METADATA_CONFLICT` with `currentVersion`, the draft door's own. Studio shows the draft conflict's reload-or-overwrite dialog, worded for a live change. - Ruling ③: no header means unpinned. The control test pins today's behaviour. - Seat ruling on #36511 (no client-only re-read before save): the check is server-side, inside the promoting write's lock. - Read first, by risk: - `packages/metadata-protocol/src/protocol-history-and-publish.ts`: the token-to-hash conversion and the first-write pin passed to `metadataConflictRefusal`. - `ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.tsx`: `DraftVersionGuard.publish`, especially the reload ordering. - `ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx`: `publishSavedItem`'s `pinned` branch. - Two-minute check: `pnpm --filter @objectstack/rest exec vitest run src/meta-item-publish-version-pin.test.ts` should report 7 passed. ## Verification Head `263b1dc5`, base `3cf6a44b`; merges cleanly onto current `origin/main` (`overlap-check`: VERDICT clean). - Premise on main `3cf6a44b`: the unpinned control showed B's publish replacing A's, the publish ignored `If-Match`, and `/layers` served no version. - Server suites: `@objectstack/metadata-protocol` 23352 passed / 45 skipped; `@objectstack/rest` 8794 passed / 351 skipped, with 1 failure: an existing assertion on the layered route's options, updated for `withVersion` and re-run green (13 passed in that file); `@objectstack/runtime` 11845 passed / 25 skipped. - New and neighbouring server files: `meta-item-publish-version-pin`, `meta-item-layered-route`, `meta-item-version-token-occ`: 35 passed. - UI: `DraftConflictDialog.test.tsx` + `StudioDesignSurface.draftVersionConflict-11773.test.tsx` 41 passed; the 36511 save suites plus `data-objectstack` and `i18n`: 237 files, 3413 passed; `ui/scripts`: 5127 passed. - Type checks: `spec`, `metadata-protocol`, `rest`, `runtime`, `app-shell` (both tsconfigs), `data-objectstack`, `i18n`: clean. - Generated: `check:generated --fix` regenerated `content/docs/references/api/protocol.mdx` (committed). - Derived gate families (`dispatch-gates --ran`): 126 derived, 125 run with exit 0, 1 NOT-MEASURED: `check-plugin-teardown-shape --self-test` exit 3, its positive control is pinned to a commit this shallow clone cannot reach. Declared to CI. `check:dual-build-cjs-loads` needs a whole-repo `pnpm build` and is likewise declared to CI. - Two gates went red on this branch and are fixed in it: `check:facade-delegation-only` (the protocol facade was 10 lines over its ceiling; its layered-read answer type now reuses the facet's declared type, and the file is 30 lines shorter than base) and `check:test-source-alias` (the edited layered-route test pays the engine load at collection). 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_011y7As7qXR2zTnbLDZgn218 <!-- signed: repo:objectstack#7 · os-alice · session_011y7As7qXR2zTnbLDZgn218 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 81eae2b commit 70f454a

21 files changed

Lines changed: 993 additions & 76 deletions
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@objectstack/metadata-protocol': patch
4+
'@objectstack/rest': patch
5+
'@objectstack/runtime': patch
6+
'@object-ui/data-objectstack': patch
7+
'@object-ui/app-shell': patch
8+
'@object-ui/i18n': patch
9+
---
10+
11+
fix(metadata): two Studio Saves over one published item are no longer last-writer-wins
12+
13+
Clause-②: yes (widening) — two new optional members join what the API accepts and answers: `PublishMetaItemRequestSchema.parentVersion` (the `If-Match` / `If-None-Match: *` pin on `POST /meta/:type/:name/publish`) and `GetMetaItemLayeredResponseSchema.overlayVersion` (served on `GET /meta/:type/:name/layers`); nothing is removed or narrowed, and a publish that names no version behaves as before
14+
Metadata-protocol: added
15+
16+
A Studio Save writes the item's draft and then publishes that one item, so it leaves no draft behind. Two admins who opened the same object with no pending draft both asserted "no draft" on their draft save, and the later Save published over the earlier one without a word: the published layer served no version a Save could pin.
17+
18+
- `GET /meta/:type/:name/layers` now answers `overlayVersion`: the version token of the stored active row at the read's address (`?package=`), the same keyed token the plain uncached read serves as `version` and a publish receipt serves as `version`; `null` when no active row is stored there.
19+
- `POST /meta/:type/:name/publish` takes that token as `If-Match` (or `If-None-Match: *`, "no active row here"). A token that is not the current active row's is refused `409 METADATA_CONFLICT` with the current token as `currentVersion`, and nothing is promoted: the draft stays pending. The headers are read as the save door reads them, so `If-Match` beside `If-None-Match`, or an `If-None-Match` other than `*`, is refused `400 VALIDATION_ERROR`. A publish with neither header is unpinned, as before. The pin is checked by the store's own lock on the promoting write, not by a separate earlier read.
20+
- `MetadataClient.publish` (`@object-ui/data-objectstack`) takes `ifMatch` / `ifNoneMatch`, sent as those headers.
21+
- Studio's object page pins its Save's publish to the published row it was loaded at. When another editor published since, the Save shows the reload-or-overwrite dialog the draft conflict shows, worded for a live change: reload takes back the draft the Save wrote and re-reads the live object, overwrite (after a confirmation) publishes over the version the refusal names, and keep editing leaves the edits on the page, unsaved. New locale keys in the studio catalogue (en, zh): `engine.draftConflict.publishedTitle`, `engine.draftConflict.publishedDescription`, `engine.draftConflict.publishedOverwriteTitle`, `engine.draftConflict.publishedOverwriteDescription`.
22+
23+
The two members enter the authorable-surface ratchet (`api/GetMetaItemLayeredResponse:overlayVersion`, `api/PublishMetaItemRequest:parentVersion`), so `@objectstack/spec` takes `minor`; the other packages stay `patch`.
24+
25+
Nothing to migrate: a client that sends no version is unaffected.

‎content/docs/references/api/protocol.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1521,6 +1521,7 @@ This schema accepts one of the following structures:
15211521
| **name** | `string` | ✅ | Item name |
15221522
| **code** | `any` | ✅ | LAYER 1 — the packaged artifact baseline exactly as shipped, before any tenant customization. `null` when no artifact ships this item (it exists only as an overlay). |
15231523
| **overlay** | `any` | ✅ | LAYER 2 — the stored customization row ALONE, not merged with `code`. `null` when the environment has not customized the item. |
1524+
| **overlayVersion** | `string \| null` | optional | ADR-0008 version token of the stored ACTIVE row at this read's address (`?package=`, and the bundle member): the published layer a publish of this item replaces. The same keyed token the plain uncached read serves as `version` and a publish receipt serves as `version`. Send it back as `If-Match` on `POST /meta/:type/:name/publish` and a publish over a row that moved since this read is refused 409 `METADATA_CONFLICT` instead of replacing it. `null` when no active row is stored at that address — an item served from code or a package artifact alone — so the next publish creates one: pin it with `If-None-Match: *`. ABSENT from a server that does not serve it: absence means "not served", never "no row". Opaque — echo it verbatim, never parse it. |
15241525
| **overlayScope** | `Enum<'env'> \| null` | ✅ | Which scope the `overlay` row was read from: `env`, the environment layer — the only layer a read serves (ADR-0131 D6). `null` exactly when `overlay` is null. |
15251526
| **effective** | `any` | ✅ | LAYER 3 — the merged result, i.e. the value an ordinary `GET /meta/:type/:name` would return under `item`. `null` when the item resolves to nothing at all. |
15261527
| **draft** | `any` | optional | LAYER — the pending draft row exactly as stored: untranslated, ungoverned, with no injected columns (unlike the `?state=draft` item read, which serves the draft translated and governed). For the requested `packageId` when one is given. `null` when no draft is pending. A client building an edit buffer reads `draft ?? overlay ?? code`. ABSENT from a server that does not serve this layer: absence means "not served", never "no draft". |
@@ -2649,6 +2650,7 @@ The authoring surface of a metadata write. Closed: `copilot` is an AI assistant'
26492650
| **message** | `string` | optional | Optional human-readable note recorded with the publish history event. |
26502651
| **packageId** | `string \| null` | optional | ADR-0048 — the software package the draft being promoted was listed under, when the caller has one to state (`?package=<id>` on the REST door). Named, the publish promotes that package's draft and no other. ABSENT names no package: the publish promotes the draft a draft save that names no package writes — the draft of the one package the item's active rows are bound to, else its package-unbound draft, promoted into that package — and answers `404 NO_DRAFT` when neither exists, as the strict draft read does. For an item never published into a package it is the package-unbound draft, else the one package's draft. It is refused `409 RESOURCE_CONFLICT` when the active rows (or, with none and no package-unbound draft, the drafts) are bound to two or more packages, except a bundled type's member whose active rows a base package and a package declaring it both hold, with no package-unbound row beside them: the read naming no package serves the base's row, and the publish promotes the base's draft into it, as naming the base does (two packages neither of which declares the other are still refused). ⚠️ `null` is NOT the same as absent: the implementation branches on the KEY BEING PRESENT, and `null` pins the lookup to the package-UNBOUND row. Spread it in conditionally; a present-and-`undefined` key coerces to `null` downstream and makes a package-bound draft unfindable — a silent `no_draft`. |
26512652
| **member** | `string` | optional | Bundle member selector, for a metadata type whose identity is a pair (today only `email_template`, identified by `(name, locale)`): the member this request addresses, spelled as its discriminator value (`zh-CN`). Absent, the canonical member (`en-US` for `email_template`), which is what a bare-name read answers; naming the canonical value is the same request. It is not the response translation locale, which `?locale=` and `Accept-Language` choose. Refused with 400 `VALIDATION_ERROR` on a type that has no members, and for a blank value or one longer than a stored member can be (100 characters). A well-formed member with nothing stored or shipped answers as that door answers an absent item. |
2653+
| **parentVersion** | `string \| null` | optional | ADR-0008 optimistic-concurrency pin on the PUBLISHED layer: the version token of the active row the caller loaded and means to replace (on the REST door, the `If-Match` request header; the `/layers` read's `overlayVersion`, the plain read's `version` and a publish receipt's `version` serve it). A token that is not the current active row's at the address the promotion writes is refused 409 `METADATA_CONFLICT`, whose `currentVersion` names the active row's current token, and nothing is promoted: the draft stays pending. ⚠️ `null` is NOT the same as absent: a present `null` asserts "no active row here" (on the REST door, `If-None-Match: *`, which takes `*` alone and never beside `If-Match`), refused 409 when one exists; an ABSENT key is unpinned and promotes over whatever is live, as before. It pins the active row only — which draft is promoted is the address's, as without it. |
26522654
| **userTextLocales** | `string[]` | optional | The locales the user-facing sentences of this write's findings (`advisories[].userMessage`, and `issues[].userMessage` on its 422) are composed in, in ladder order: the locale the request names, then the workspace default. Each is read against the platform locale table, whole and then one subtag shorter at a time; a value that names no table language is passed over, and `en` is the last rung. Stated by the door that holds the request (the REST door and the dispatcher state `[ExecutionContext.locale, ExecutionContext.workspaceLocale]`), never read from a wire body. ABSENT ⇒ the sentences are composed in `en`. It selects a language only: what is judged, refused or saved does not depend on it. |
26532655

26542656

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

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -674,7 +674,7 @@ export class ProtocolHistoryAndPublishFacet {
674674
* `recordPendingDenialAudit`, rethrow. Skip it and the refusal is silent
675675
* again — the pre-#7748 state, not merely a worse one.
676676
*/
677-
static async promoteDraftForPublish(host: Pick<ProtocolHost, 'anonymousElevatedFlowRefusal' | 'assertRuntimeAuthoringRules' | 'classifyObjectContribution' | 'credentialChannelFor' | 'declinesStoredRow' | 'defaultRecordPageSaveRefusal' | 'engine' | 'ensureOverlayIndex' | 'externalBindingSaveRefusal' | 'getOverlayRepo' | 'isArtifactBacked' | 'isOverlayAllowed' | 'isRuntimeCreateAllowed' | 'isSealedManagedItem' | 'lockWriteRefusal' | 'metadataConflictRefusal' | 'namedBaseOverlayWriteRefusal' | 'objectExtensionItemRefusal' | 'objectNamespaceObjectNameClash' | 'objectNamespacePrefixViolation' | 'objectRegistrationRefusal' | 'optimisticConflictAuditEntry' | 'overlayPackageMismatchError' | 'overrideWriteVerdict' | 'packagelessAddress' | 'packagelessDraftAddress' | 'permissionSetNameCollisionRefusal' | 'readItemActiveRows' | 'resolveSduiManifest' | 'rethrowUnlessMetadataStoreUnprovisioned' | 'seedExternalIdSaveRefusal' | 'shippedArtifactsOf' | 'uninstalledNamedBaseRefusal' | 'unknownDatasourceSaveRefusal' | 'unknownGrantObjectSaveRefusal' | 'unknownPicklistBindingSaveRefusal'>, request: {
677+
static async promoteDraftForPublish(host: Pick<ProtocolHost, 'anonymousElevatedFlowRefusal' | 'assertRuntimeAuthoringRules' | 'classifyObjectContribution' | 'credentialChannelFor' | 'declinesStoredRow' | 'defaultRecordPageSaveRefusal' | 'engine' | 'ensureOverlayIndex' | 'externalBindingSaveRefusal' | 'getOverlayRepo' | 'isArtifactBacked' | 'isOverlayAllowed' | 'isRuntimeCreateAllowed' | 'isSealedManagedItem' | 'lockWriteRefusal' | 'metadataConflictRefusal' | 'namedBaseOverlayWriteRefusal' | 'objectExtensionItemRefusal' | 'objectNamespaceObjectNameClash' | 'objectNamespacePrefixViolation' | 'objectRegistrationRefusal' | 'optimisticConflictAuditEntry' | 'overlayPackageMismatchError' | 'overrideWriteVerdict' | 'packagelessAddress' | 'packagelessDraftAddress' | 'permissionSetNameCollisionRefusal' | 'readItemActiveRows' | 'resolveSduiManifest' | 'rethrowUnlessMetadataStoreUnprovisioned' | 'seedExternalIdSaveRefusal' | 'shippedArtifactsOf' | 'storedParentForToken' | 'uninstalledNamedBaseRefusal' | 'unknownDatasourceSaveRefusal' | 'unknownGrantObjectSaveRefusal' | 'unknownPicklistBindingSaveRefusal'>, request: {
678678
type: string; name: string; actor?: string; message?: string;
679679
/**
680680
* [#8907] ADR-0048 — the package binding of the draft being promoted,
@@ -728,6 +728,14 @@ export class ProtocolHistoryAndPublishFacet {
728728
member?: string;
729729
/** [#32656] The write request's `userTextLocales`, for the findings' `userMessage`. */
730730
userTextLocales?: readonly (string | undefined)[];
731+
/**
732+
* [#36601] `PublishMetaItemRequestSchema.parentVersion`: the
733+
* caller's pin on the active row this promotion replaces — a
734+
* token, `null` for "no active row here", absent for unpinned.
735+
* Stated by the per-item publish only; a package publish pins
736+
* nothing.
737+
*/
738+
parentVersion?: string | null;
731739
/**
732740
* [ADR-0144 D2 and D6, amended] The registry question this
733741
* promotion asks before the row goes live, stated by every producer
@@ -1330,6 +1338,25 @@ export class ProtocolHistoryAndPublishFacet {
13301338
// with no manifest promotes the draft as written, as it saves it.
13311339
const sduiManifest = host.resolveSduiManifest();
13321340
try {
1341+
// [#36601] The caller's pin on the PUBLISHED layer, judged on the
1342+
// active row at the address this promotion writes (`promoteInto`,
1343+
// the binding `repo.promoteDraft` writes the active row under):
1344+
// a token is matched in keyed form ({@link storedParentForToken},
1345+
// the save door's comparison) and handed to the store as the
1346+
// stored hash its `put` locks against, so a row published between
1347+
// this read and the write is refused there too; `null` asserts no
1348+
// active row. The draft's own pin is `expectedDraftHash` below:
1349+
// the two judge different rows. Without it the promotion replaces
1350+
// whatever is live, as before.
1351+
let expectedActiveHash: string | null | undefined;
1352+
if (request.parentVersion !== undefined) {
1353+
const activeHead = await repo.headAt(ref, {
1354+
state: 'active',
1355+
packageId: promoteInto,
1356+
...memberOption(request.member),
1357+
});
1358+
expectedActiveHash = await host.storedParentForToken(ref, request.parentVersion, activeHead.head?.hash ?? null);
1359+
}
13331360
const result = await repo.promoteDraft(ref, {
13341361
deriveActiveBody: (draftBody) => stampHtmlPageRequires(singularType, draftBody, sduiManifest),
13351362
// #4556 — NULL, not 'system', for an actor-less publish.
@@ -1358,6 +1385,8 @@ export class ProtocolHistoryAndPublishFacet {
13581385
// none), so a draft saved after the gate's read is refused as a
13591386
// conflict instead of being promoted unjudged.
13601387
expectedDraftHash: draftForGate ? draftForGate.hash : null,
1388+
// [#36601] …over the active row the caller pinned, when it pinned one.
1389+
...(expectedActiveHash !== undefined ? { expectedActiveHash } : {}),
13611390
// [#22877] …of the member that was judged.
13621391
...memberOption(request.member),
13631392
});
@@ -1377,6 +1406,8 @@ export class ProtocolHistoryAndPublishFacet {
13771406
? `${request.type}/${request.name} draft changed after this publish judged it, so nothing was `
13781407
+ `published. Publish again to judge and promote the current draft.`
13791408
: `${request.type}/${request.name} published row advanced while you held the draft.`,
1409+
// [#36601] A publish pinned "no active row here" is told so, as the save door's first-write pin is.
1410+
request.parentVersion === null && !(err instanceof DraftConflictError) ? 'active' : undefined,
13801411
);
13811412
// [#8594] Attached, not written — same reason as the lock gate
13821413
// above. The repository's own transaction has already unwound by

0 commit comments

Comments
 (0)