Skip to content

Commit ad622d3

Browse files
fix(cluster): an object authored during a store outage is served by every replica after its resync (#31816)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi926TiHxhsZMVATUkqxg2xD2)_ Fixes #31722 Clause-②: yes (widening) Metadata-protocol: none Measured on the diff: one new public method, `ObjectStackProtocolImplementation.resyncMetadataMutationPubSub()`, and its result type `MetadataMutationResyncReport`, exported from `@objectstack/metadata-protocol`. Nothing is removed or made required. The claim read `no`; the measurement says `yes (widening)`, as it did for #31721. No metadata an author writes changes. ## 维护者速读 - 改了什么:多副本集群中,Redis 等共享存储断线期间在 A 副本上新建、修改或删除的对象,B 副本在自己的集群驱动重连(`cluster.resync`)后会自动收敛,不再需要重启。 - 为什么改:`metadata.mutated` 通道(让其他副本注册新对象的那条)是唯一没有重同步入口的通道;断线期间丢失的提示会让其他副本一直回答 `OBJECT_NOT_FOUND`(或旧定义、或已删除的对象),直到重启。 - 风险与回滚:单节点(默认内存驱动)完全不变,从不触发;重同步只读本副本自己的 `sys_metadata`,读失败时不删除任何注册项。回滚即撤销本 PR。 - 先看:`metadata-protocol` 的新文件 `protocol-mutation-resync.ts`(选哪些项重新收敛),以及 `service-cluster` 的 `metadata-cluster-bridge-plugin.ts`(注册一行)。 - 两分钟验证:`cd packages/runtime && pnpm exec vitest run src/cluster-metadata-mutation-resync.integration.test.ts`,两个内核共享一个 SQLite 文件和一条会丢消息的总线。 - 需要你做的:无。 ## What changes - **Lane 2 has a resync seam (`@objectstack/metadata-protocol`).** `resyncMetadataMutationPubSub()` reads `sys_metadata`'s active rows once, with only their address and `checksum` and never a body. It then re-converges each item a lost hint could have touched: - a row whose checksum moved since this replica last converged on it (a lost save or publish); - an item this replica converged on that has no active row now (a lost delete); - an item a hint or a local write named since the last convergence (a revert brings an earlier checksum back, so the checksum alone cannot tell). Each item goes through `applyRemoteMetadataMutation`, the applier a delivered hint runs, from this replica's own re-read. Nothing travels on the wire. A row that is gone takes the delivered delete's heal walk. - **The baseline.** `attachMetadataMutationPubSub` seeds a per-replica ledger with one active-row read. Every convergence keeps the ledger current. Hints and local writes mark items. Resyncs run one at a time, and an item touched during a resync stays marked. With no baseline (the seed read failed), the first resync re-converges every active row. - **A read that fails is never a delete.** - If the active-row read fails, the resync rejects and changes nothing. - If one item's re-read fails, that item is kept as this replica holds it and stays marked for the next resync. The failures are logged once per resync (`console.error`, with the items and the first cause). - **The bridge calls it (`@objectstack/service-cluster`).** `MetadataClusterBridgePlugin` registers lane 2 through `registerLaneResync` on the same `cluster.resync` event as lanes 1, 3, 4 (#31721) and 5 (#31597). A protocol that predates the seam is skipped, and a rejected resync is a warning, as for the other lanes. - **Docs.** `content/docs/kernel/cluster.mdx` §6.2 and the bridge docblock now describe lane 2's resync instead of "Lane 2 has no resync yet". ## Why #31721 left the `metadata.mutated` lane as the one lane without a resync. Its hint is what makes a peer re-run the ObjectQL registry write-through. So a hint lost during a store outage left every other replica answering `OBJECT_NOT_FOUND` for an object authored meanwhile (or serving its old body, or serving it after a delete) until restart. ### Step 0: full re-convergence vs a diff Measured on a booted showcase (`bootShowcase`, `OS_METADATA_WRITABLE=object`), with N objects authored and the lane attached: | N | Diff, nothing lost | Diff, 5 changed | Full re-apply of every row | Listener replays (full) | | --- | --- | --- | --- | --- | | 50 | ~1 ms, 50 unchanged | 12 ms, 5 converged | 97 ms | 50 | | 300 | 2 ms, 300 unchanged | 9 ms, 5 converged | 406 ms | 300 | The address-and-checksum read takes ~1 ms at both sizes. These are shared-box timings, so read them as ratios. **Choice: the diff.** A full re-apply costs one delivered-hint convergence per stored row on every reconnect. Each convergence also replays the item into the local mutation listeners, and some of those re-sync a whole family per event (authored hooks and actions). So the cost grows with the catalog even when nothing was lost. A since-timestamp re-read was ruled out: - a hard delete leaves no active row to carry a timestamp; - the writers' clocks are not this replica's. ### A finding from the measurement On the booted showcase, the first build's resync and seed reads were refused with `PermissionDeniedError` (a read under a context that carries no principal). Every resync would have failed on a secured stack. Both reads now carry `context: { isSystem: true }`, as the repository's own reads do. The fan-out harness now refuses a principal-less column-subset read, as the secured engine does, so this is pinned (A8a/A8b below). The two-kernel test has no security plugin, so it could not catch it. ## Tests - `packages/metadata-protocol/src/protocol.cluster-mutation-fanout.test.ts`: a new `[#31722] cluster.resync` describe with 10 cases. The shared harness gains a read fault (every read, or item re-reads only), the registered labels, and the principal-less refusal: - ⭐ an object authored while the hint was lost is served after the resync; - a lost update re-converges that item only, and an unchanged item is not re-applied; - a lost delete takes the heal walk; - a delete of a row present at attach is found from the baseline; - a revert to an earlier checksum after a delivered hint; - a local write on the peer is re-read; - a failed active-row read rejects and keeps every entry; - an item whose re-read fails is kept, logged once, and retried; - CONTROL: nothing lost means nothing is re-applied; - CONTROL: with no transport, the seam does nothing. - `packages/services/service-cluster/src/metadata-cluster-bridge-plugin.test.ts`: - the existing resync cases now assert lane 2 and the info line; - 2 new cases: a protocol that predates the seam, and a rejected protocol resync is a warning. - `packages/runtime/src/cluster-metadata-mutation-resync.integration.test.ts` (new): two `LiteKernel`s over one SQLite file, a lossy bus, a `test-bus` driver with liveness, and the real bridge. - ⭐ author on A with the hint lost. B does not know the object. B's `cluster.resync` runs. B serves the object and its row. - CONTROL: a delivered hint converges B with no resync. - CONTROL: on the `memory` driver, the seam is never called (R3: the in-process driver never emits `cluster.resync`). ### Ablations Each was run against the tests above, first on the pre-merge head and again on the merged head. All went red both times, and each restore left the file equal to HEAD. | # | Mutation | Red | | --- | --- | --- | | A1 | bridge lane-2 registration removed | 3 bridge cases; the runtime ⭐ through the built `dist` | | A2 | active-row read failure swallowed (rows = []) | the failed-read case | | A3 | a failed item re-read drops its key | the item-failure case | | A4 | no unchanged skip | 2 | | A5 | the hint's touch removed | 4 | | A6 | lane-2 resync registered before the in-process guard | 4 (the memory CONTROL included) | | A7 | the local write's touch removed | the local-write case | | A8a | the seed read without the system context | the baseline-delete case | | A8b | the resync read without the system context | 9 | The A1 runtime leg uses a preflight marker that is present in the pristine `dist`, absent under the mutation, and present after the restore. ## Acceptance notes - Delete semantics follow the delivered-hint path, because it is the same applier. A per-item re-read failure is logged and kept, not deleted. - The seed read runs once per attach, only where the bridge attaches (a driver that crosses a process boundary). - R3 holds: the `memory` driver never emits `cluster.resync`, and the bridge never attaches lane 2 on it. - Landing order: #31597 (PR #31785, the settings lane) edited the same bridge file and §6.2 and landed first. `main` is merged in after it (a merge commit). Lane 5 stays at `kernel:bootstrapped` with `subscribeResync()` in both phases; lane 2 registers at `kernel:ready` like lanes 1 to 4. ## Verification - Per touched package, `pnpm typecheck` and package-scoped lint (root eslint on the directory, `--no-inline-config`) exit 0. A full `vitest run`: | Package | Test files | Tests | | --- | --- | --- | | metadata-protocol | 329 passed, 4 skipped | 22607 passed, 26 skipped | | service-cluster | 11 | 158 | | runtime | 568 | 10424 passed, 19 skipped | - All of the above ran on the merged head `70a46315`. - `dispatch-gates.mjs --commands` was derived on `70a46315` and gave 104 commands. Each was run (all exit 0) and reconciled with `--ran`: 104 derived, 104 run, 0 NOT-MEASURED. `check-nul-bytes` exits 0. - Forced test edits: none. The existing bridge resync cases gained lane 2 in their assertions, and the fan-out suite's shared harness was extended. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (`packages/spec` untouched.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: n/a. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmQr9knGGTwQc6UKmnE --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 4ed2092 commit ad622d3

11 files changed

Lines changed: 831 additions & 14 deletions
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
'@objectstack/service-cluster': patch
4+
---
5+
6+
fix(cluster): an object authored while the cluster store was unreachable is served by every replica once its driver reconnects, without a restart
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: none
10+
11+
The `metadata.mutated` lane (the one that makes a peer register an object authored on another replica) now has a resync seam, `ObjectStackProtocolImplementation.resyncMetadataMutationPubSub()`, and `MetadataClusterBridgePlugin` calls it on the cluster driver's local `cluster.resync` event, as it already did for the other lanes. Before, a hint lost during a store outage left every other replica answering `OBJECT_NOT_FOUND` for the object (or serving its old body, or still serving it after a delete) until restart.
12+
13+
On the event the replica reads `sys_metadata`'s active rows once (address and checksum only) and re-converges each item a lost hint could have touched — a row whose checksum moved, an item with no active row left, and an item a hint or local write named since the last convergence — through the same applier a delivered hint runs, from its own re-read. Nothing travels on the wire. A failed read is never a delete: the registry is left as it is and the next resync re-reads. The in-process `memory` driver never emits the event, so a single node is unchanged.
14+
15+
New public surface: the method above and its result type `MetadataMutationResyncReport`, exported from `@objectstack/metadata-protocol`. Nothing is removed or made required.

‎content/docs/kernel/cluster.mdx‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -375,16 +375,24 @@ channel's own doc comment:
375375
event is never published to peers; each replica emits its own when its own
376376
connection returns. `MetadataClusterBridgePlugin` re-reads every attached
377377
lane on it: lane 1 drops the metadata list caches
378-
(`MetadataManager.resyncClusterPubSub()`), lane 3 re-converges every stored
379-
datasource and every held pool
380-
(`DatasourceAdminService.resyncDatasourceMutationPubSub()`), and lane 4
378+
(`MetadataManager.resyncClusterPubSub()`), lane 2 re-converges the object
379+
registry (`ObjectStackProtocolImplementation.resyncMetadataMutationPubSub()`),
380+
lane 3 re-converges every stored datasource and every held pool
381+
(`DatasourceAdminService.resyncDatasourceMutationPubSub()`), lane 4
381382
runs the connector reconcile
382383
(`AutomationEngine.resyncConnectorCredentialPubSub()`), and lane 5
383384
announces every settings namespace locally so each subscriber re-reads it
384385
(`SettingsService.resyncSettingsChangePubSub()`).
385386
`AuthzClusterBridgePlugin` advances the engine's write epoch, which retires
386-
cached grants. **Lane 2 has no resync yet**: it converges per item on the
387-
signals that are delivered, and fully at boot. A cache of your own
387+
cached grants. Lane 2 reads `sys_metadata`'s active rows once (address and
388+
checksum, never a body) and re-converges each item a lost signal could have
389+
touched: a row whose checksum moved since the replica last converged on it,
390+
an item it converged on that has no active row now, and an item a signal or
391+
a local write named since. Each goes through the same applier a delivered
392+
signal runs, from the replica's own re-read, so a row that is gone takes the
393+
delete's heal walk. A read that fails is never a delete: when the row read
394+
fails nothing changes, and an item whose own re-read fails is kept as the
395+
replica holds it, logged once, and re-read on the next resync. A cache of your own
388396
subscribes with `onClusterResync(cluster, handler)` from
389397
`@objectstack/service-cluster`. On the `memory` driver that subscription is
390398
a no-op, because nothing there can lose a connection.

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,9 @@ export type { MetadataMutationEvent, MetadataMutationProjector, MutationProjecti
164164
// never trusted content (receipt re-reads `sys_metadata` locally).
165165
export { METADATA_MUTATION_CLUSTER_CHANNEL } from './protocol.js';
166166
export type { ClusterMetadataMutationPayload } from './protocol.js';
167+
// [#31722] What the lane's resync seam (`resyncMetadataMutationPubSub()`)
168+
// reports after a cluster outage.
169+
export type { MetadataMutationResyncReport } from './protocol.js';
167170
// [#10219] The per-item publish notification the host bridges to the
168171
// kernel-wide `metadata:reloaded` announce. Exported for the same reason its
169172
// mutation sibling is: the subscriber lives in another package.

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

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
* `registerStoredObjectExtension`, `resyncStoredObjectExtensions`,
1212
* `onMetadataMutation`, `emitMetadataMutation`, `attachMetadataMutationPubSub`,
1313
* `detachMetadataMutationPubSub`, `applyRemoteMetadataMutation`,
14+
* `resyncMetadataMutationPubSub` (#31722, written here beside its lane),
1415
* `onMetaItemPublished`, `getOverlayRepo` moved out of `protocol.ts` whole by
1516
* `scripts/codemod-split-protocol.mjs`; `registerUninstallGuard` (#31232) was
1617
* written here in the same shape, beside `registerUninstallCleanup`.
@@ -56,6 +57,8 @@ import type {
5657
UninstallGuard,
5758
} from './protocol-package-lifecycle-types.js';
5859
import { METADATA_MUTATION_CLUSTER_CHANNEL } from './protocol-mutation-events.js';
60+
import { MetadataMutationResyncLedger, RESYNC_ROW_FIELDS } from './protocol-mutation-resync.js';
61+
import type { MetadataMutationResyncReport } from './protocol-mutation-resync.js';
5962
import type {
6063
ClusterMetadataMutationPayload,
6164
MetaItemPublishedEvent,
@@ -323,19 +326,34 @@ export class ProtocolClassHeadFacet {
323326
* surface hand-announcing. Local listeners first, then the bus, matching
324327
* `MetadataManager.notifyWatchers`' order.
325328
*/
326-
static emitMetadataMutation(host: Pick<ProtocolHost, 'notifyMutationListenersLocal' | 'publishMetadataMutation'>, evt: MetadataMutationEvent): void {
329+
static emitMetadataMutation(host: Pick<ProtocolHost, 'clusterResync' | 'notifyMutationListenersLocal' | 'publishMetadataMutation'>, evt: MetadataMutationEvent): void {
330+
// [#31722] A local write moves what this replica's registry holds for
331+
// the item, so the lane's resync re-reads it rather than trust the
332+
// row's checksum (a later revert can bring an earlier one back).
333+
if (evt.state !== 'draft') host.clusterResync?.touch(evt);
327334
host.notifyMutationListenersLocal(evt);
328335
host.publishMetadataMutation(evt);
329336
}
330337

331338
/** The body of `ObjectStackProtocolImplementation#attachMetadataMutationPubSub`; the method's docblock there is its contract. */
332-
static attachMetadataMutationPubSub(host: Pick<ProtocolHost, 'applyRemoteMetadataMutation' | 'clusterNodeId' | 'clusterPubSub' | 'clusterUnsubscribe' | 'detachMetadataMutationPubSub'>, pubsub: IPubSub, nodeId: string): () => void {
339+
static attachMetadataMutationPubSub(host: Pick<ProtocolHost, 'applyRemoteMetadataMutation' | 'clusterNodeId' | 'clusterPubSub' | 'clusterResync' | 'clusterUnsubscribe' | 'detachMetadataMutationPubSub' | 'findEnvironmentRows'>, pubsub: IPubSub, nodeId: string): () => void {
333340
if (host.clusterPubSub === pubsub && host.clusterNodeId === nodeId) {
334341
return () => host.detachMetadataMutationPubSub();
335342
}
336343
host.detachMetadataMutationPubSub();
337344
host.clusterPubSub = pubsub;
338345
host.clusterNodeId = nodeId;
346+
// [#31722] The resync baseline: which stored row each registry entry
347+
// was converged on, taken by one read now (see
348+
// `protocol-mutation-resync.ts`).
349+
const ledger = new MetadataMutationResyncLedger();
350+
host.clusterResync = ledger;
351+
ledger.seed(() => host.findEnvironmentRows('sys_metadata', {
352+
where: { state: 'active' },
353+
fields: [...RESYNC_ROW_FIELDS],
354+
// Platform plumbing: no caller to authorize, as the repository's own reads.
355+
context: { isSystem: true },
356+
}));
339357
host.clusterUnsubscribe = pubsub.subscribe<ClusterMetadataMutationPayload>(
340358
METADATA_MUTATION_CLUSTER_CHANNEL,
341359
(msg) => {
@@ -350,6 +368,7 @@ export class ProtocolClassHeadFacet {
350368
// `applyRegistryWriteThrough`'s `mode === 'publish'` gate),
351369
// and this guard keeps a peer honest about the same rule.
352370
if (p.event.state === 'draft') return;
371+
host.clusterResync?.touch(p.event);
353372
void host.applyRemoteMetadataMutation(p.event).catch((err) => {
354373
console.warn(
355374
`[Protocol] cluster metadata-mutation apply failed for `
@@ -365,13 +384,29 @@ export class ProtocolClassHeadFacet {
365384
}
366385

367386
/** The body of `ObjectStackProtocolImplementation#detachMetadataMutationPubSub`; the method's docblock there is its contract. */
368-
static detachMetadataMutationPubSub(host: Pick<ProtocolHost, 'clusterNodeId' | 'clusterPubSub' | 'clusterUnsubscribe'>): void {
387+
static detachMetadataMutationPubSub(host: Pick<ProtocolHost, 'clusterNodeId' | 'clusterPubSub' | 'clusterResync' | 'clusterUnsubscribe'>): void {
369388
if (host.clusterUnsubscribe) {
370389
try { host.clusterUnsubscribe(); } catch { /* idempotent */ }
371390
host.clusterUnsubscribe = undefined;
372391
}
373392
host.clusterPubSub = undefined;
374393
host.clusterNodeId = undefined;
394+
host.clusterResync = undefined;
395+
}
396+
397+
/** The body of `ObjectStackProtocolImplementation#resyncMetadataMutationPubSub`; the method's docblock there is its contract. */
398+
static async resyncMetadataMutationPubSub(host: Pick<ProtocolHost, 'applyRemoteMetadataMutation' | 'clusterPubSub' | 'clusterResync' | 'findEnvironmentRows'>): Promise<MetadataMutationResyncReport | undefined> {
399+
// No transport, no lane: a single node never missed a hint.
400+
const ledger = host.clusterResync;
401+
if (!host.clusterPubSub || !ledger) return undefined;
402+
return ledger.resync({
403+
readActiveRows: () => host.findEnvironmentRows('sys_metadata', {
404+
where: { state: 'active' },
405+
fields: [...RESYNC_ROW_FIELDS],
406+
context: { isSystem: true },
407+
}),
408+
converge: (evt) => host.applyRemoteMetadataMutation(evt),
409+
});
375410
}
376411

377412
/**

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ export interface ProtocolHost {
8383
readonly classifyObjectContribution: ObjectStackProtocolImplementation['classifyObjectContribution'];
8484
clusterNodeId: ObjectStackProtocolImplementation['clusterNodeId'];
8585
clusterPubSub: ObjectStackProtocolImplementation['clusterPubSub'];
86+
clusterResync: ObjectStackProtocolImplementation['clusterResync'];
8687
clusterUnsubscribe: ObjectStackProtocolImplementation['clusterUnsubscribe'];
8788
readonly codeOnlyCreateError: (typeof ObjectStackProtocolImplementation)['codeOnlyCreateError'];
8889
readonly codeOnlyOverrideError: (typeof ObjectStackProtocolImplementation)['codeOnlyOverrideError'];

0 commit comments

Comments
 (0)