Skip to content

service-knowledge: record-change sync runs through the queue service — a save does not wait for the embedder, a failed sync is retried, a rolled-back write is never indexed #37735

In review

Description

@objectstack-fleet

repo:objectstack#5 · os-bill · session_01Utp6Cb4BAjgQ43tqy1DvVJ

Filing gate: ③ maintainer-directed (topic child). Source: topic #37000; maintainer 2026-11-27 00:12Z 「用 fable评审后拆卡,你只负责当前任务,后续任务通过信箱交接给 objectstack #1」. Reviewed by an independent Fable pass before filing (row 15 of the epic is split in two: this card is its queue half, the reconcile half is the sibling card; this card also takes over #37110).
Grading: area:ai · domain:server · Feature · p2 (topic) · reach: every save of a record of an indexed object, on every deployment that holds a knowledge source · evidence: read.

维护者速读

  • 问题:现在保存一条被索引的记录,要等向量服务算完才返回;向量服务慢或宕机时保存跟着变慢,这次同步失败了只留一行日志,不会重试。
  • 做什么:保存只登记「这条记录要重新索引」,马上返回;后台去做,失败自动重试,重试用尽后留下可查的失败记录,由每日对账补上。
  • 顺带修掉:写入回滚后,索引里留下没提交的数据(已有的缺陷卡,并入这张)。
  • 需要你做的:无。

What

Carries ADR-0161 (docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md) K1 (sync is the platform's), its Consequences ("Index-time work moves into the service … which is why the queue (row 15) follows"), and the Execution row "row 15". It adds no adapter-contract member and changes no IQueueService member.

What is true on main at 579b85776: the event bridge awaits service.handleRecordUpsert / handleRecordDelete inside its realtime subscription (packages/services/service-knowledge/src/knowledge-service-plugin.ts, realtime.subscribe('knowledge-event-sync', …)). The note on handleRecordUpsert (knowledge-service.ts) records what that means: the engine publishes the event from inside the write, the in-process realtime service awaits each subscriber, so the save waits for the re-read, the split, the embedding call and the store write, and all of it happens before the write's unit commits. syncRecord catches every failure and logs one warn ("event-sync failed for source …"); nothing retries. #37110 (open, p3) is the rollback half of the same seam.

  1. The bridge enqueues; it does not sync. For each source over the event's object (the existing objectSourcesFor predicate), publish one message to a queue the PR names: the source's index key, the object, the record id, and why (event, or freshness for item 6). Never a field value: sys_job_queue is a first-class object an administrator can list, and a record body there would be a copy outside the row's permissions. The worker re-reads the row, so the message needs nothing else.
  2. The worker. Subscribed on the durable queue from kernel:ready (the queue plugin swaps its memory adapter for the database one there; packages/services/service-queue/src/queue-service-plugin.ts says subscribers register in their own kernel:ready). It resolves the source by its key at processing time and runs today's syncRecord path: re-read under the source's where as the system identity, write or delete, per-document order kept by the existing chain. A failure is thrown to the queue, which retries with backoff; the PR states the attempt budget and the backoff, sized so that a provider outage of some minutes is ridden out. Exhausted, the message is a dead letter that names its source and record in the message metadata. State, and pin, which outcomes are not retried because a retry cannot change them: a source no longer registered (completed, no write), a whole document over the embedder's budget (today's removal and error line stay), and whatever else the PR finds.
  3. Nothing is processed before the write commits, and nothing at all for a write that rolls back (service-knowledge: event sync re-reads inside the uncommitted write, so a rollback leaves the index stale until the next event or a reindex #37110). Both outcomes on that card (a document built from a row that never committed; a document deleted although the committed row matches) are pinned on a real SQL driver, with the write's own unit and with a caller's engine.transaction. The PR states the mechanism it found: the queue row joining the write's unit (the database adapter inserts through the engine; whether that insert joins the ambient unit when sys_job_queue sits on another datasource is to be measured, not assumed), or a publish after commit (the engine's commit-wait for detached hooks, runOutsideOpenUnitsOnCommit, objectql: run async after-hooks on commit of the triggering unit (drop on rollback) #33760, is the precedent). If neither is reachable from a realtime subscriber without an engine change, the dev stops and says so on this card before writing one.
  4. A burst of saves on one record, without losing the last one. QueuePublishOptions.idempotencyKey cannot simply be the document id: DbQueueAdapter.publish (packages/services/service-queue/src/db-queue-adapter.ts) suppresses a publish while a row with that key is pending or running, and for the idempotency window (24 h) after it completed. A running sync has already read the row, so the suppressed event's change would be lost, and a completed one would block every later save of that record for a day. The PR states how a burst is bounded and how many queue rows one save costs (completed rows are kept for the object's declared retention), with no rule that can drop the last event. If the honest answer needs the queue to coalesce only with a still-pending message, that is a card for the queue's lane, named in the PR; this card does not change IQueueService.
  5. Deletes ride the same queue. A deleted row's document leaves the index when its message is processed; until then the freshness check and the permission re-read of service-knowledge: search returns records, not chunks — granularity and groupBy #37103 keep the hit out of every answer, and the docs say so. The reap guard (installReapGuards, ADR-0057) stays inline: it de-indexes before the sweep deletes, in batches, and is not an event.
  6. The freshness repair moves to the queue. repairStale (knowledge-service.ts; its note reads "Moves to the scheduled reconcile's queue when that lands") publishes the same message instead of running an un-awaited sync in the search's process, so a repair survives a restart and is retried like any other.
  7. No durable queue. The kernel's built-in queue fallback delivers synchronously with no durability and no retry and labels itself degraded; resolveDurableQueue (packages/plugins/plugin-email/src/email-plugin.ts) is the precedent for reading that label. Without a durable queue the service keeps today's inline sync and says so once at boot, at warn: saves wait for the embedder, a failed sync is not retried, and service-knowledge: event sync re-reads inside the uncommitted write, so a rollback leaves the index stale until the next event or a reindex #37110 stays true on that path. The docs name what a host that mounts the service by hand adds to get queued sync. The standard runtime always mounts queue (PLATFORM_ALWAYS_ON_CAPABILITIES).
  8. Unchanged switches. enableEventSync: false enqueues nothing and subscribes nothing; a source with refresh.onRecordChange: false is never enqueued; destroy() leaves the queue subscription as it leaves the realtime one.
  9. Texts (K2). content/docs/protocol/knowledge.mdx (event sync, the opt-out paragraph that says "inline index sync"), content/docs/ai/knowledge-rag.mdx, the service-knowledge README, and the long note on handleRecordUpsert ("When this runs, measured against the engine"), rewritten to what is true after this PR.

Rulings carried (ADR-0161 K10): answers read content as the asking user, and the index copy is for ranking and snippets only (the message carries identifiers, the worker reads as the system identity only to build the index copy); no adapter-contract member.

Acceptance

  • With an embedder that does not answer, a save of an indexed record resolves; the document appears once the embedder answers, with no further event.
  • An embedder that fails the first attempts and then answers: the document is indexed by a retry. One that keeps failing: the message becomes a dead letter the queue lists (listFailed), naming the source and the record; the save never failed and no record content is in the stored message (a test reads the row).
  • service-knowledge: event sync re-reads inside the uncommitted write, so a rollback leaves the index stale until the next event or a reindex #37110's two outcomes, each on a real SQL driver: after the rollback the index equals the committed database.
  • Two saves of one record in quick succession leave the index holding the last committed version; a save one minute after a completed sync is synced (nothing is suppressed by a completed message).
  • A delete removes the document once processed, and no search answers it in between.
  • Messages published before a restart are processed after it.
  • A source unregistered between publish and processing completes its message with no write and no retry.
  • With only the kernel's fallback queue: one boot line at warn, and sync works as before this card.
  • enableEventSync: false and refresh.onRecordChange: false publish nothing.
  • Container run per AGENTS.md. The PR closes service-knowledge: event sync re-reads inside the uncommitted write, so a rollback leaves the index stale until the next event or a reindex #37110 as well.

Out of scope

Blocked-by: #37304 (PR #37676 rewrites the registry and both files this card edits; messages are keyed by its index key), #37734 (the sibling reconcile card, number filled in at filing: same two files, and this card's failure story relies on it).
Takes over: #37110 (same seam; its acceptance is item 3 above). Coordinates with #37479 (the unmounted-adapter path the worker meets).
Parent: #37000. Reader: domain:server lane (packages/services/service-knowledge; tests on a real SQL driver).
Dedupe: knowledge "queue" event sync 72 (open: #37110 — taken over by this card; #37479 — a different refusal, coordinated; #37304 — blocker; #32062 — sync-in, another subsystem; seat posts) · "sys_job_queue" knowledge 5 (open: a seat post) · knowledge rollback index 33 (open: #37110).

Activity

  1. added
    priority:p2
    pm:blocked
    area:ai
    domain:server
    on Nov 27, 2026
  2. objectstack-fleet commented on Nov 27, 2026

    @objectstack-fleet
    ContributorAuthor

    triage#1 · hotlong · session_01Q4EjjMnyLqJdzuktEmRPXH

    Triage: lands in area:ai · domain:server · Feature · priority:p2 · pm:blocked · size M; rationale: record-change sync runs through the queue service, so a save does not wait for the embedder and a failed sync is retried. Topic #37000; p2. It keeps its named blocker.

  3. objectstack-fleet commented on Nov 27, 2026

    @objectstack-fleet
    ContributorAuthor

    repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP

    Area o1-C · 2026-11-27T14:50Z · serial note

    Both named blockers are cleared: #37304 closed (PR #37676 merged) and #37734 closed out (PR #37979 merged, 7221284319). The area still holds this card pm:blocked: #37954 (F4, p2, claimed 7220764458, dev building) adds a data-engine after-write trigger in the same kernel:ready sync wiring of knowledge-service-plugin.ts that item 1 rewrites, and #37954's coordination note says whichever lands second adopts the other's seam. Two devs on that seam at once would only produce a conflict, so this card is claimed when #37954's PR lands, and it then enqueues from both triggers.

    Blocked-by: #37954

  4. objectstack-fleet commented on Nov 27, 2026

    @objectstack-fleet
    ContributorAuthor

    repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP

    Claim: PM loop round 7 · area o1-C (epic #37000; area concurrency 8 by the maintainer 2026-11-27T11:26Z) · 2026-11-27T17:13Z
    Session: session_016WV4cwPhGV4g9p1BGQaZbP
    Account: os-elon-musk
    Branch: claude/area-o1C-37735
    Worktree: objectstack-issue-37735
    Domain: domain:server
    Area: o1-C
    Seat: repo:objectstack#1
    File surface: packages/services/service-knowledge/src/knowledge-service-plugin.ts (the kernel:ready sync wiring: the knowledge-event-sync realtime subscription :671 and the realtime-free trigger PR #38016 added, both now enqueue; the queue worker's subscription), knowledge-record-hooks.ts (#38016's after-write hooks, enqueue instead of sync), knowledge-service.ts (syncRecord as the worker's body; repairStale :2054 publishes instead of an un-awaited sync; the handleRecordUpsert note), tests on a real SQL driver (#37110's two outcomes), docs (content/docs/protocol/knowledge.mdx event-sync section, content/docs/ai/knowledge-rag.mdx), the service-knowledge README, a changeset. No IQueueService / DbQueueAdapter change (card item 4 names the card to file if one is needed).
    Container & model: L, mode:subagent, model: default tier (dispatch-gates --tier: "no path-derived mandate"), effort: high (reason: L; commit-ordered enqueue across two triggers inside the write's unit on a real SQL driver, retry/dead-letter semantics with a no-loss burst rule, and two takeover cards' acceptance)
    Clause-②: no
    Metadata-protocol: none
    Responsibility: objectstack's own code, packages/services/service-knowledge/src/knowledge-service-plugin.ts | a save of an indexed record waits for the embedder, a failed sync is one warn line and never retried, and a rolled-back write can leave an uncommitted document in the index (#37110) | every deployment that holds a knowledge source; the reconcile (#37734, merged) repairs what the dead letters name
    Thread-read: 7221299372
    Premise: holds, read on origin/main 8d598aa — the realtime subscription knowledge-event-sync at :671 syncs inline; PR #38016's KnowledgeRecordHooks (knowledge-record-hooks.ts, wired from :647) is the second trigger; repairStale (:2054) runs void this.serializeRecordSync(...) in the search's process; resolveDurableQueue is at packages/plugins/plugin-email/src/email-plugin.ts:316.
    Serial constraints cleared: probe overlap-check (the five surface files) against origin/main and PRs #38026, #37982, #37963: VERDICT clean exit 0. #38026 (#37306, ranked first by the seat) shares both service files and merges cleanly; if it lands first the dev merges main. #37963 (#37467, rework B: per-hit freshness) shares knowledge-service.ts near the freshness path that item 6 moves: whichever lands second adopts the other's freshness seam, and the PR says so.
    Pre-claim lane: packages/services/service-knowledge/** ⇒ domain:server.
    Pre-claim deps: #37304 closed (PR #37676), #37734 closed (PR #37979), #37954 closed (PR #38016 merged 8d598aa, close-out 7224134465). Triage 7207203716 sized it M; the claim reads L for item 3's two-driver measurement.
    Prior rulings read: card thread 0 rulings (triage 7207203716, area serial note 7221299372).
    Fold-or-serial: takes over #37110 (card body; the PR closes it). Not folded with #37736 (sync-state record), which is Blocked-by this card and counts its dead letters.

  5. added
    pm:dispatched
    and removed
    pm:blocked
    on Nov 27, 2026
  6. objectstack-fleet commented on Nov 27, 2026

    @objectstack-fleet
    ContributorAuthor

    repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP
    os-dev-report

    {
      "issue": 37735,
      "status": "done",
      "branch": "claude/area-o1C-37735",
      "pr": "https://github.com/objectstack-ai/objectstack/pull/38043",
      "head": "43dc682dcbeaf442a33cd8aac6c0511bb2de634d",
      "session": "session_016WV4cwPhGV4g9p1BGQaZbP",
      "premise_still_valid": true,
      "summary": "With a durable queue service (QueueServicePlugin over a data engine; refused: the kernel's degraded fallback and any queue with no listFailed) and a bound data engine, both triggers (the realtime knowledge-event-sync subscription and the realtime-free after-write hooks) now publish one identifiers-only message {source, object, recordId, reason} per source to the knowledge-record-sync queue, and a worker subscribed in kernel:ready re-reads the row and writes or removes the document (processRecordSync wraps syncRow, the shared body syncRecord also uses). Mechanism for item 3: publish-after-commit through ObjectQL runAfterOpenUnitsCommit (the write's own unit and a caller's engine.transaction; dropped on rollback; at once with no unit) — no engine change, the queue-row-joins-unit route not taken. Rows-per-save: one queue row per source per save, no idempotencyKey (a docId key would suppress a save made while the sync runs and every save for 24h after one completed). A failure throws and is retried on recordSyncRetry (default 8 attempts, 5s doubling to 2min), then a listFailed dead letter logged once at error; repairStale publishes a freshness message; no durable queue or no engine keeps the inline sync with one boot warn; enableEventSync:false and refresh.onRecordChange:false unchanged. IQueueService and DbQueueAdapter untouched. #37963 adopts this freshness seam if this lands first (stated in the PR body).",
      "tests": "New src/__tests__/record-sync-queue.test.ts on a real ObjectKernel + ObjectQLPlugin + SqlDriver (better-sqlite3 file) + QueueServicePlugin(adapter db): 33/33 (`vitest run --maxWorkers=2 src/__tests__/record-sync-queue.test.ts`, lock VERDICT batch-last-exit 0 for the vitest+echo pair, VITEST_EXIT=0). Full package on merge head 640b3563f7: `pnpm --filter @objectstack/service-knowledge exec vitest run --maxWorkers=2` Test Files 19 passed (19), Tests 593 passed (593); `pnpm --filter @objectstack/service-knowledge typecheck` check:test-typecheck OK, 0 errors; lock VERDICT command-exit 0. Final head 43dc682dcb differs from 640b3563f7 only in the changeset, knowledge.mdx and README wording (minimal preset mounts no queue). Ablations at 2c7da1cd16, each mutated on disk, test file re-run from source (vitest aliases, no rebuild), restored by git checkout with clean status confirmed: enqueue-not-sync (both triggers forced inline) 24 failed; rollback-not-indexed (runAfterOpenUnitsCommit removed, publish at once) 4 failed — rolled-back insert x2, own-unit, own-unit abort (the caller-transaction case stayed green: on SQLite's single connection the poller cannot read inside an open transaction, so the rollback cases are the deferral's pin); burst-keeps-last (idempotencyKey source:object:recordId) 9 failed incl. burst/after-completed/delete; no-field-value-in-message (row title added to the message on both triggers) 2 failed; fallback-inline-warn: warn dropped 2 failed, degraded/no-listFailed queue accepted 2 failed.",
      "gates": "dispatch-gates --commands --repo objectstack-ai/objectstack (tree 640b3563f7; same list at 43dc682dcb): 119 families. Local run, exit captured before any pipe: 113 exit 0; exit 3 PREREQUISITE NOT MET (NOT MEASURED): spec check:skill-examples, check:dual-build-cjs-loads, check:published-readme-exports (the one new README import, QueueServicePlugin from @objectstack/service-queue, confirmed by hand in service-queue/dist/index.d.ts); exit 1 from local build state, not this diff: spec check:docs (packages/spec/json-schema older than src; diff touches no spec), check:dts-closure (packages/rest/dist missing index.d.ts/.d.cts; rest untouched — likely from the type-check-debt build I stopped); UNRUN/NOT MEASURED: check:type-check-debt (builds every package under the shared lock). 39 doc/changeset families re-run on final head 43dc682dcb: 39/39 exit 0. --ran reconciliation (record with :: exit codes): 119 derived, 115 run, 3 NOT-MEASURED, 1 UNRUN (type-check-debt) — exit 1. overlap-check on 43dc682dcb: VERDICT clean exit 0 vs origin/main and #38038 #38037 #38032 #38026 #37982 #37963. PR check-runs at report time: all in_progress/queued (Lint *, Type Check *, Check Changeset, PR-body guards, Spec property liveness, Validate Package Dependencies, Check PR Size); opt-in/schedule jobs skipped — CI convergence not awaited.",
      "dogfood_battery": "n/a — no ! in the PR title and no (narrowing) arm (Clause-②: yes (widening))",
      "mcp_calls": "0",
      "api_writes": "2 relay strokes (repository_dispatch to the board, executed as objectstack-fleet[bot]): pr_create = POST /repos/objectstack-ai/objectstack/pulls (draft) + POST /repos/objectstack-ai/objectstack/issues/38043/assignees (os-elon-musk), read-back identical 9952 bytes; os-dev-report = POST /repos/objectstack-ai/objectstack/issues/37735/comments via post-stamped. git push is not counted.",
      "open_questions": [],
      "security_findings": "none",
      "out_of_scope_findings": [
        "carrier: none · noted, not filed — a system-identity search at chunk granularity runs no freshness or permission re-check, so it answers a deleted record's chunks until the delete's message is processed (member and granularity:'record' searches do not); documented in knowledge.mdx, existing designed behaviour, not one of the three classes",
        "carrier: none · noted, not filed — cross-node ordering: chainAfter serializes runs of one document per process only; two nodes processing two messages of one record are unordered, each re-reads the row, a commit between one node's read and another's write can leave an older version until the next save, freshness hit or reconcile (PR Acceptance notes)",
        "carrier: none · noted, not filed — a realtime adapter delivering out of process would publish with no unit open (at once, after the write returned but unordered against a caller's transaction); none ships today (PR Acceptance notes)",
        "carrier: none · noted, not filed — MemoryQueueAdapter carries no degraded label and no listFailed; refused here through the listFailed condition (PR Acceptance notes)"
      ],
      "deviations": [
        "Clause-② declared 'yes (widening)' where the claim read 'no': new optional plugin option recordSyncRetry, four new public KnowledgeService members and new package exports; changeset kept patch with Metadata-protocol: none",
        "Pushes were made before the first overlap-check run; that first run was non-clean (exit 1 against #38026 and #37963), the edits were reshaped, and every later run was VERDICT clean (last: 43dc682dcb)",
        "I started a local gate runner that reached check:type-check-debt (a full build under the shared lock) and killed my own runner's process tree; type-check-debt is NOT MEASURED, and the interrupted build likely left packages/rest/dist without .d.ts, which makes check:dts-closure red locally",
        "'The Container run per AGENTS.md': AGENTS.md names no step by that name that I could find (its only container rule is the process-table one); the real-composition evidence is the record-sync-queue suite booting a real ObjectKernel + ObjectQL + SqlDriver + QueueServicePlugin(db); an os serve / standard-runtime boot is NOT MEASURED",
        "The full package suite + typecheck ran on merge head 640b3563f7; the final commit 43dc682dcb only rewords the changeset, knowledge.mdx and README (queue mounted on every preset but minimal), on which the doc/changeset gate families were re-run",
        "origin/main merged once (it brought #38033 into both service files: conflicts in index.ts and the plugin options resolved by keeping both); main moved on to 74cd5b6d84 after, which overlap-check reports merges cleanly",
        "The harness attribution reminder asked for model-named commit trailers and a different PR footer; commits keep the dispatch's model-free trailers and the PR body uses the AGENTS.md session-URL footer",
        "Lock waits earlier in the run were long (two dogfood holders, about 35 and 58 minutes); later acquisitions waited 0s"
      ]
    }

    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area:aidomain:serverpm:dispatchedpriority:p2

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions