Skip to content

Commit 3014176

Browse files
fix(service-knowledge): widen the record-sync covered margin to the queue lease (#38577)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XDXvJPPtrTGfdDYhWWpihq5)_ Fixes #38556 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:知识库在重建前 30 秒内收到的记录改动会照常同步,不再被当成“重建已覆盖”而跳过;普通使用者无感。 - 为什么做:知识库检索大项里批量同步评审标出的罕见竞态——向量服务很慢时,一次还没写完的旧同步可能在重建之后落盘,把旧内容留在索引里。 - 出错会怎样:最坏是这 30 秒窗口内的改动多做一次正常同步(多一点向量调用);只改一个内部常量与注释,可直接撤回。 - 要你做什么:无。 ## Premise check Holds at `main` (d08d2ae). `coveredByBuild` (`knowledge-service.ts`) answers `covered` when `publishedAt < build.startedAt - RECORD_SYNC_COVER_MARGIN_MS`, and the constant was `5_000` with a docblock naming clock skew only. Nothing in `coveredByBuild` asks whether a sync of the record is still in flight (and a sync on another node is invisible to it), so a sync that re-read a record before a later write and whose store write lands after the walk leaves the older document, and the later write's message (published more than 5 s before the build began) completes as `covered`. ## What changes - `RECORD_SYNC_COVER_MARGIN_MS`: `5_000` → `30_000`, the queue adapter's default message lease (`DbQueueAdapterOptions.leaseMs`). - Its docblock names both guards (clock skew, a sync in flight), the cost (a normal sync for messages inside the margin) and what stays uncovered (a sync in flight longer than the margin, since a live handler keeps renewing its lease; skew beyond what the sync's own time leaves of the margin), and where it is repaired (the next purging build, ADR-0161 K1). - No change to `IQueueService`, the build's purge, or the per-message / batch paths outside `covered`. ## Choice and reasons Widened, not documented-only: - The only cost of a wider margin is a normal sync (one re-read, one embed, one write) for messages published in the 25 s that move from `covered` to synced; the backlog case `covered` exists for is messages published long before the walk, which stay covered. - 30 s moves the reach from "one sync slower than 5 s" (one slow provider answer; the in-repo embedder neither retries nor bounds a request) to "one sync slower than the lease a batch is sized to settle well inside" (`QueueBatchSubscribeOptions.maxBatch`). - A guard tied to the sync's own completion was considered: an in-process tracker cannot see a sync on another node, and `covered` is judged on the node that ran the build, so it would not be smaller and would not close the cross-node case. - The lease is not an exported constant (it is an inline default in `service-queue`, which `service-knowledge` depends on only for tests), so the value is written here and a test pins it equal to the adapter's real default; exporting one from `service-queue` sat outside this card's file surface. ## Tests New `src/knowledge-record-sync-cover-margin.test.ts` (beside the source, by the claim's file surface): - the margin equals `DbQueueAdapter`'s default `leaseMs`; - after a complete build that purged, a message published 10 s before the build's start is `synced` on both the per-message and the batch path, and repairs a document an in-flight sync wrote late; - a message published more than the margin before the start is `covered`, with no re-read. <details><summary>Readings at ee44d49</summary> - `pnpm --filter @objectstack/service-knowledge test`: Test Files 23 passed (23), Tests 784 passed (784). - `pnpm --filter @objectstack/service-knowledge typecheck`: exit 0 (tsc covers the new file, `--listFiles` 1 hit; `check:test-typecheck` OK). - `dispatch-gates --commands` (67 families): 66 exit 0; `check:dual-build-cjs-loads` exit 3, PREREQUISITE NOT MET (needs a whole-repo build), NOT MEASURED locally, CI runs it. `--ran` reconciliation: 67 accounted, 66 run, 1 NOT MEASURED. - `check-nul-bytes`: OK. </details> ## Ablation `node scripts/ablation-replace.mjs` restoring `= 5_000;` on disk (anchor 1 → 0, blob changed), same test file: 2 failed / 1 passed — `expected 5000 to be 30000` (lease pin) and `expected 'covered' to be 'synced'` (the inside-the-margin message). Restore verified: blob == HEAD, `git diff HEAD` empty. ## Acceptance notes - AGENTS.md asks a new pin for a component with a shared harness to go into that harness file; the claim placed the test beside the source because `src/__tests__/` is held by another in-flight claim. The harness is duplicated in small; folding it into `knowledge-build.test.ts` later is a follow-up for whoever holds that directory. ## Verification (two minutes) `pnpm --filter @objectstack/service-knowledge exec vitest run --maxWorkers=2 src/knowledge-record-sync-cover-margin.test.ts` — expect 3 passed. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 1332e2c commit 3014176

3 files changed

Lines changed: 186 additions & 5 deletions

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
'@objectstack/service-knowledge': patch
3+
---
4+
5+
Clause-②: no
6+
Metadata-protocol: none
7+
8+
A record-sync message now completes as `covered` only when the complete build that covers it began at least 30 s (the queue adapter's default message lease) after the message was published, up from 5 s. The margin guards a sync still in flight as well as clock skew: a sync that re-read a record before a later write, and whose store write landed after the build's walk, could leave the older document in the index while the later write's message was answered `covered`. A message inside the margin is synced as usual, which is the only cost. A sync in flight for longer than the margin stays uncovered until the next build that purges.
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The `covered` margin ({@link RECORD_SYNC_COVER_MARGIN_MS}) guards a sync
5+
* still in flight as well as clock skew: a message published inside the
6+
* margin of a complete build's start is synced, so a document an in-flight
7+
* sync wrote late over the walk's is repaired by the later write's message.
8+
*/
9+
10+
import { describe, it, expect, vi } from 'vitest';
11+
import type { AdapterContext, IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts';
12+
import type { KnowledgeDocument, KnowledgeSource } from '@objectstack/spec/ai';
13+
import { DbQueueAdapter, type JobEngine } from '@objectstack/service-queue';
14+
import { KnowledgeService } from './knowledge-service.js';
15+
import { RECORD_SYNC_COVER_MARGIN_MS } from './knowledge-record-sync-queue.js';
16+
17+
type Row = Record<string, unknown>;
18+
19+
/** Rows of one object; `find` applies scalar equality, `$and`, `id: { $gt }` and `id: { $in }`, ordered by id. */
20+
function makeEngine(initial: Row[]) {
21+
const rows = new Map<string, Row>(initial.map((r) => [String(r.id), { ...r }]));
22+
const matches = (row: Row, where: Record<string, unknown> | undefined): boolean => {
23+
if (!where) return true;
24+
for (const [key, value] of Object.entries(where)) {
25+
if (key === '$and') {
26+
if (!(value as Array<Record<string, unknown>>).every((c) => matches(row, c))) return false;
27+
continue;
28+
}
29+
if (value !== null && typeof value === 'object') {
30+
const among = (value as { $in?: unknown[] }).$in;
31+
if (among !== undefined) {
32+
if (!among.includes(row[key])) return false;
33+
continue;
34+
}
35+
const gt = (value as { $gt?: unknown }).$gt;
36+
if (gt === undefined) throw new Error(`engine double: condition on '${key}' is not implemented`);
37+
if (!(String(row[key]) > String(gt))) return false;
38+
continue;
39+
}
40+
if (row[key] !== value) return false;
41+
}
42+
return true;
43+
};
44+
const select = (where?: Record<string, unknown>) =>
45+
[...rows.values()].filter((r) => matches(r, where)).sort((a, b) => String(a.id).localeCompare(String(b.id)));
46+
const find = vi.fn(async (_object: string, query?: { where?: Record<string, unknown>; limit?: number }) => {
47+
const all = select(query?.where);
48+
return (typeof query?.limit === 'number' ? all.slice(0, query.limit) : all).map((r) => ({ ...r }));
49+
});
50+
const count = vi.fn(async (_object: string, query?: { where?: Record<string, unknown> }) => select(query?.where).length);
51+
return { rows, find, engine: { find, count } as unknown as IDataEngine };
52+
}
53+
54+
/** An adapter that lists its documents, so a complete build runs its purge. */
55+
function makeAdapter() {
56+
const docs = new Map<string, KnowledgeDocument>();
57+
const held: { fingerprint?: string; recipeHash?: string } = {};
58+
const adapter: IKnowledgeAdapter = {
59+
id: 'memory',
60+
embedding: { model: 'model-a', dimensions: 3 },
61+
async upsert(batch: KnowledgeDocument[]) {
62+
for (const doc of batch) docs.set(doc.id, doc);
63+
},
64+
async delete(ids: string[]) {
65+
for (const id of ids) docs.delete(id);
66+
},
67+
async search() {
68+
return [];
69+
},
70+
async listDocuments(_ctx: AdapterContext, page: { cursor?: string; limit: number }) {
71+
const all = [...docs.values()].map((d) => ({ documentId: d.id, ...(d.docHash ? { docHash: d.docHash } : {}) }));
72+
const start = page.cursor === undefined ? 0 : Number(page.cursor);
73+
const slice = all.slice(start, start + page.limit);
74+
return { documents: slice, ...(start + page.limit < all.length ? { nextCursor: String(start + page.limit) } : {}) };
75+
},
76+
async indexStatus() {
77+
return { ...held };
78+
},
79+
async beginBuild(ctx: AdapterContext) {
80+
if (held.fingerprint !== ctx.index!.fingerprint) {
81+
docs.clear();
82+
held.fingerprint = ctx.index!.fingerprint;
83+
delete held.recipeHash;
84+
}
85+
},
86+
async completeBuild(ctx: AdapterContext) {
87+
held.fingerprint = ctx.index!.fingerprint;
88+
held.recipeHash = ctx.index!.recipeHash;
89+
},
90+
};
91+
return { adapter, docs };
92+
}
93+
94+
const SOURCE: KnowledgeSource = {
95+
name: 'kb',
96+
label: 'Knowledge base',
97+
adapter: 'memory',
98+
source: { kind: 'object', object: 'kb_article', content: ['title', 'body'] },
99+
};
100+
101+
const message = (recordId: string) => ({ source: 'kb', object: 'kb_article', recordId, reason: 'event' });
102+
103+
/** A complete build of `kb` that ended `done` with its purge run, and when it began (epoch ms). */
104+
async function afterPurgingBuild() {
105+
const db = makeEngine([
106+
{ id: 'a1', title: 'Leave policy', body: 'Twenty days of paid leave' },
107+
{ id: 'a2', title: 'Travel policy', body: 'Economy class under six hours' },
108+
]);
109+
const { adapter, docs } = makeAdapter();
110+
const service = new KnowledgeService({
111+
dataEngine: db.engine,
112+
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
113+
});
114+
service.registerAdapter('memory', adapter);
115+
service.registerSource(SOURCE);
116+
const record = await service.rebuildSource('kb', { trigger: 'operator' });
117+
expect(record).toMatchObject({ status: 'done', result: { purged: 0 } });
118+
const startedAt = Date.parse(record.startedAt);
119+
expect(Number.isFinite(startedAt)).toBe(true);
120+
return { service, docs, db, startedAt };
121+
}
122+
123+
describe('record sync — the covered margin guards a sync still in flight', () => {
124+
it('is the queue adapter\'s default message lease', () => {
125+
const queue = new DbQueueAdapter({ engine: {} as unknown as JobEngine, options: { autoStart: false } });
126+
const leaseMs = (queue as unknown as { opts: { leaseMs: number } }).opts.leaseMs;
127+
expect(RECORD_SYNC_COVER_MARGIN_MS).toBe(leaseMs);
128+
});
129+
130+
it('a message published inside the margin of the build\'s start is synced, and repairs a document an in-flight sync wrote late', async () => {
131+
const { service, docs, db, startedAt } = await afterPurgingBuild();
132+
// The record was written 10 s before the build began; a sync that read it
133+
// before that write landed its store write after the walk's.
134+
db.rows.get('a1')!.title = 'Leave policy (revised)';
135+
const walked = docs.get('kb:a1')!;
136+
docs.set('kb:a1', { ...walked, content: 'Leave policy\nTwenty days of paid leave' });
137+
const publishedAt = startedAt - 10_000;
138+
139+
expect(await service.processRecordSync(message('a1'), publishedAt)).toBe('synced');
140+
expect(docs.get('kb:a1')!.content).toContain('Leave policy (revised)');
141+
142+
const batch = await service.processRecordSyncBatch([{ data: message('a2'), publishedAt }]);
143+
expect(batch).toEqual([{ ok: true, outcome: 'synced' }]);
144+
});
145+
146+
it('a message published more than the margin before the build\'s start is covered', async () => {
147+
const { service, db, startedAt } = await afterPurgingBuild();
148+
const publishedAt = startedAt - RECORD_SYNC_COVER_MARGIN_MS - 1;
149+
const reads = db.find.mock.calls.length;
150+
151+
expect(await service.processRecordSync(message('a1'), publishedAt)).toBe('covered');
152+
const batch = await service.processRecordSyncBatch([{ data: message('a2'), publishedAt }]);
153+
expect(batch).toEqual([{ ok: true, outcome: 'covered' }]);
154+
expect(db.find.mock.calls.length).toBe(reads);
155+
});
156+
});

‎packages/services/service-knowledge/src/knowledge-record-sync-queue.ts‎

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -209,12 +209,29 @@ export const RECORD_SYNC_BACKLOG_READ_INTERVAL_MS = 30_000;
209209

210210
/**
211211
* How much earlier than a build's start a message must have been published
212-
* for that build to cover it (`covered`). The publish time is stamped by the
213-
* publishing node's queue and the build's start by the building node's clock;
214-
* the margin absorbs the skew between two nodes' clocks. A message inside the
215-
* margin is synced as usual.
212+
* for that build to cover it (`covered`). A message inside the margin is
213+
* synced as usual; that normal sync is the margin's only cost. It guards two
214+
* things:
215+
*
216+
* - clock skew: the publish time is stamped by the publishing node's queue
217+
* and the build's start by the building node's clock;
218+
* - a sync still in flight: a sync that re-read the record before a later
219+
* write, and whose store write lands after the build's walk wrote the
220+
* record (or after its listing, for a record created and then deleted),
221+
* leaves the older document in the index. The later write's message must
222+
* then be synced, not covered, and it is whenever the build began within
223+
* the margin of that write.
224+
*
225+
* The margin is the queue adapter's default message lease
226+
* (`DbQueueAdapterOptions.leaseMs`, 30 s), which a batch is sized to settle
227+
* well inside (`QueueBatchSubscribeOptions.maxBatch`). What stays uncovered:
228+
* a sync in flight for longer than the margin (a live handler keeps renewing
229+
* its lease, so the lease does not bound it; a slow embedding provider is the
230+
* way there), plus skew beyond what the sync's own time leaves of the margin.
231+
* Such a stale document stays until the next build that purges, which is
232+
* where ADR-0161 K1 puts an index's correctness.
216233
*/
217-
export const RECORD_SYNC_COVER_MARGIN_MS = 5_000;
234+
export const RECORD_SYNC_COVER_MARGIN_MS = 30_000;
218235

219236
/** One message handed to `KnowledgeService.processRecordSyncBatch`: its payload, and when the queue says it was published (epoch ms). */
220237
export interface KnowledgeRecordSyncBatchItem {

0 commit comments

Comments
 (0)