Skip to content

A changed document is mined for decisions on the next sync pass - #239

Merged
zlareb1 merged 7 commits into
mainfrom
feat/knowledge-source-extract
Nov 4, 2026
Merged

zlareb1 merged 7 commits into
mainfrom
feat/knowledge-source-extract

Conversation

@zlareb1

@zlareb1 zlareb1 commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • New Feature

Changelog entry (one or two sentences a user of Loom can read without the diff; the release pull request collects these into the release notes):

The document-source sync now mines each document it writes into decision rows in the same pass, as loom decisions extract --apply does, within LOOM_KNOWLEDGE_SOURCE_SYNC_CAP_SHARE of the namespace's daily cost cap. knowledge.source.list and inspect show each source's pending, mined and given-up documents and the decision rows it tagged source-changed rather than rewriting them.

Why

A synced design document only reaches an agent before an edit once its decisions are rows in the repository's trunk code namespace. Until now an operator had to run loom decisions extract per document after each change. The sync worker already knows which documents changed, so it runs the same extraction on them: nobody has to remember a command or confirm a row, an unpinned extracted row is served as it is, and a pinned or attested row stays frozen (the extractor's existing rule: tagged source-changed, never rewritten).

Design

  • What is pending is derived, not queued. After every source's turn the pass mines each of the source's documents whose stored source_revision (in loom.documents, read by store.source_revisions, for every source kind) differs from the revision recorded as mined for it: mined: {source_uri: revision} in the source's sync state (loom.code_index_state, knowledge_source:<name>). The leg writes a revision there only once that document is settled (below), under the namespace's sources lease. A turn that raises, is stopped or is cancelled after writing files records nothing in the map, so the next pass finds those documents unmined. Why the sync state and not the document's metadata: a metadata write is a new document version (re-chunk, re-embed) racing the sync's own writes, while the state row is already the source's, written under its lease. Keyed by address, not file id, since a file that moves address is a new document whose rows cite the new address. Entries for documents no longer the source's are dropped on each write. pending_extract is the reported count.
  • Leg. Per document, decision_extract.extract_document(org, namespace, uri, dry_run=False, read_deadline=..., may_write=...) under the source's lease, customer.for_org(org, namespace=ns) and pipeline_actor("worker:knowledge-source-sync"). Rows go to the trunk code namespace as agent loom-decisions, source_class=derived, source_resource_id citing the document; decision.record and memory.delete_version audit rows go through audit.emit with the worker as the actor.
  • Writes, one unit at a time. Each candidate's writes (decision.record with its audit row, or a tags write) and each retire-step row run as one unit through asyncio.shield, held in the run's own TaskSet (passed as extract_document(..., writes=) and on through the write and retire steps, a fresh one when none is given; every unit is also registered for shutdown): a cancel never cuts a record from its audit row, and shutdown's drain_task_sets waits for an in-flight unit. Before each unit the run asks may_write, which the worker answers from the source lease's held and pass_context.stop_requested(); when it says no the run stops there (report.write_stopped), keeps what it wrote and retires nothing. No unit outlives the lease by more than one record.
  • Stops. A stopped pass (stop_requested, or PassStopped from check_stop) and a cancel end the leg with no state written. A lost source lease, seen by may_write or as LeaseLost from cluster_lease, ends that source's turn with nothing recorded and the leg goes on to the next source. A turn that fails with an exception records what it settled first. A failed read of a source's documents, or a failed state write for a source that waits, is that source's error (result.errors, note_failure) and the leg goes on.
  • Spend gates. The org switch is read once per pass (an unread switch stops the leg, fail closed). The cap is read before each document: namespace_over_cap(org, ns, operation="worker.knowledge_source_sync", share=knowledge_source_sync_cap_share, fail_open=False) after flushing the emitter, the conflict resolver's shape. A customer.GROUP_HOLDS hold pauses its namespace in a Held registry for hold_seconds(e); any other hold stops the leg. A hold, on a model read or on an embedding a write needs, is a wait, never a try, and a turn that tried nothing keeps the last mining turn's counts.
  • Time. A document's model reads stop at read_deadline, 30 s before the pass deadline, with nothing written (out_of_time). A document is not started with under 60 s of read time left; the pass counts as cut and the source's reason is pass_bound. knowledge_source_sync_max_pass_seconds now has a floor of 180: 90 s for the sync, then 60 s of read time and 30 s for the writes.
  • Cost. Each document runs in its own task with its own cost_accumulator.begin_op(); its emit_worker_cost_event_for(org, ns, "worker.knowledge_source_sync") runs in a finally after finish_writes(writes), which waits only for this run's units, so a write unit a cancel left running (its task copied the accumulator's context) is billed in the same row, and a concurrent run (a CLI extraction, say) neither blocks this row nor is billed in it. The pass's own accumulator (the sync's embedding spend in the .pass row) is untouched.
  • Extractor changes. extract_document stops at the first customer.HOLDS hold, on a model read or on an embedding a write needs (the restatement search, decision.record), sets report.held and retires nothing; before, a held read was a dropped window and a held embedding a refused candidate. It takes read_deadline (report.out_of_time) and may_write (report.write_stopped), and marks permanent refusals (Dropped.permanent). loom decisions extract exits 1 on a hold. _no_model_error is now no_model_error.
  • Setting. knowledge_source_sync_cap_share (LIVE, default 0.25, (0, 1]), the memory_conflict_resolver_cap_share shape.

Settle rules. A document is settled at its revision, and so not mined again until the sync writes a new one, when:

Outcome Settled Counted extract_error
mined, every write done or permanently refused (BLACKLISTED, PINNED_CONFLICT, VALIDATION_FAILED) yes extracted ''
could not run, a refusal of the moment (busy key, timeout, provider error), an exception after three tries on the revision one failure per try; unextracted when given up not_run, refused, failed:<error>
reads ran out with less than three quarters of a pass's read time after three tries; goes first in its source's next turn as above out_of_time
reads ran out with three quarters of a pass's read time or more at once unextracted too_large_for_pass
held, capped, switched off, switch unread, no model, pass bound, stopped, lease lost no, and no try counted extract_deferred held:<code>, held, over_cap, switched_off, switch_unread, no_model, pass_bound; cleared once nothing waits

Alternatives: a separate extraction worker would need its own cursor, lease and status row for work the sync pass already orders and bounds; running the leg inside each source's sync turn would let one source's extraction delay every other source's sync; a list of addresses appended by the sync turn (the first version of this PR) loses a write whenever the turn fails after it; one shielded task per document (the second version) could outlive the lease by a whole document's writes.

Scope and risk

  • Touches server/knowledge/app/source_sync.py (the leg), server/memory/app/decision_extract.py (holds, the read deadline, may_write, whole write units, permanent refusals), the sync-state wire model, two settings (one new, one floor raised), the CLI help of loom knowledge sync and loom decisions extract, docs.
  • Tenant isolation: the leg runs in-process with no auth context, as the sync does; the gate is the one on knowledge.source.add (a namespace admin registered the source). Model calls carry the source's org and namespace. The state row's error is a code (table above); the extractor's messages and document addresses go to the worker log only, and list shows the pending count, never the mined map.
  • Concurrency: one source is mined only under its lease; a write unit outlives a lost lease by at most one record, and a re-run by another copy reconciles against what that record wrote.
  • Rows a model writes reach agents unconfirmed, as the extraction design intends; the verbatim check and the frozen-row rule are unchanged.

Compatibility, rollout and rollback

  • Wire: KnowledgeSourceSync (in knowledge.source.list and inspect) gains pending_extract, last_extracted_at, extracted, flagged_pinned, unextracted, extract_error. Output only. loom decisions extract exits 1 on a held model call where it used to report dropped windows.
  • Rolling upgrade: an N-1 sync turn merges into the stored state and keeps the new keys; the documents it writes are mined by an N pass, since what is pending is derived from the documents. N-1 readers ignore the new keys.
  • First run: documents a source already holds have no mined revision, so the first passes mine each of them once, within the cap share and the per-pass bound.
  • Operator steps: LOOM_KNOWLEDGE_SOURCE_SYNC_MAX_PASS_SECONDS below 180 is now refused at startup. Otherwise none. The leg runs wherever LOOM_KNOWLEDGE_SOURCE_SYNC_ENABLED is on and a model is configured, and spends model calls on each changed document; LOOM_KNOWLEDGE_SOURCE_SYNC_CAP_SHARE bounds it.
  • Rollback: decision rows already written stay (served unconfirmed, removable with memory.delete); the extra state keys are ignored.

Tests

  • tests/unit/test_knowledge_source_sync.py:
    • mined in the same pass as the worker with the source's attribution, spend in a namespace row and not in the pass's accumulator, not mined again unchanged, mined again once changed;
    • durability: a document written by a turn that raised or was stopped before its state write is mined next pass; a leg-level LeaseLost (the lease's loss cancelling the body), PassStopped from check_stop in the leg and a cancel during _mine write no state and are mined next pass; a lease lost mid-write ends that source and the leg goes on to the next; a stopped pass ends the leg with nothing recorded;
    • spend: the cap read again before each document; a write unit a cancel left running is billed in the document's row;
    • a failed state write for a waiting source (OverloadedError from the sources lease) and a failed read of a source's documents are that source's error (errors, failed, note_failure), and the next source is still mined;
    • waits: over the cap share, switched off, switch unread, no model, gateway hold (no try counted, last counts kept), hold on every org (leg stops), pass bound inside a turn; each writes its reason, cleared once nothing waits;
    • settle rules: three failed tries give a revision up until rewritten; refused, raised and out-of-time tries count one failure per document; a permanent refusal settles the document; out of time with a whole pass's read time settles as too_large_for_pass, with less it goes first next pass; the time floor; a document no longer the source's leaves the map; the shared pass bound; sync_of shows the count, never the map.
  • tests/unit/test_knowledge_source_sync_linear.py and tests/unit/test_knowledge_source_recordings.py: a project's documents and a meeting's transcript are mined by the same leg (every kind's documents are read through store.source_revisions).
  • tests/unit/test_decision_extract.py: a held model read stops the run before any write; a hold on a write's embedding (ModelCallsDisabled, ModelCallRefused) is a hold, not a refused candidate; a hold on a later write keeps the record already written with its audit row and retires nothing; may_write turning false stops after the current record with no audit gap; a cancelled run finishes its current write and drain_task_sets covers it; a cancelled run's pending unit stays in its own set and finish_writes on it completes while another run's unit is still pending; a read deadline passed mid-read writes nothing and no audit row; a blacklisted candidate is a permanent refusal; the worker's writes are audited as the worker.
  • Integration (tests/integration/test_knowledge_sources.py, private ClickHouse and server, auth off, fake providers): a seeded source over a mocked folder store syncs one document and mines it into one decision row in the trunk namespace (agent loom-decisions, actor worker:knowledge-source-sync, derived, confidence 0.5, unpinned, source_resource_id = knowledge:<ns>/<uri>#<section>), one decision.record audit row with the worker actor, list showing extracted: 1, and nothing mined on the next pass. The folder store's responses are written in the test; no vendor credential or real content is used. With test_decision_extract_repo.py and test_decision_record_source.py: 18 passed on the head rebased after Uploaded files are ingested: the extractor service extracts them and a job publishes the next revision #229 and A recording source syncs a meeting's transcript as timestamped sections #248.
  • No paid model call was made.
  • Gates: make format lint typecheck; sdk_py_gen, sdk_py_client_gen, sdk_ts_gen, docs_reference, op_reach_census, settings_reference, settings_schema, settings_example; the LIVE, defaults and CLI snapshots; the full unit suite (26673 passed, 20 skipped, 1 xfailed) on 72d78398e; the last head, a018fc39e, changes comments, the queue filter and one test's setup, and its touched tests pass.

AI assistance in the code (leave one; writing this description with AI is fine):

  • AI-generated (an agent wrote most of the diff): Claude Code; checked against the sync and extractor code paths and the tests above.

  • I can explain every line of this diff and how it interacts with the rest of Loom.

Checklist

  • make format-check, make lint, make typecheck and make test-unit pass; the integration suite passes if server behaviour changed.
  • Generated files are regenerated in this PR, not by hand: the SDK op tables, docs/reference/configuration.md and the docs/reference/ tables (python scripts/codegen/docs_reference.py), the reach manifest, schemas/schema.sql (make schema-dump) and the Codex plugin copies (python3 scripts/codegen/agent_plugin_sync.py).
  • A new migration is additive and numbered after the latest on main; no merged migration is edited.
  • A behaviour change to any file a plugin ships (hooks/, lib/, bin/, skills/, .mcp.json, the Codex plugin-defaults.json) bumps both plugin manifests' version, and no other open PR uses that version.
  • The frontend builds (npm --prefix frontend run build) and its tests pass, if frontend/ changed.
  • Docs under docs/ describe the system as it now is, and this description names any operator steps and wire changes.
  • Repository text has no dates, people, host names, internal namespaces, ticket or decision numbers; the history goes in this description (tests/unit/test_public_copy.py).
  • Commits are signed off (git commit -s), as CONTRIBUTING.md asks.

🤖 Generated with Claude Code

@zlareb1
zlareb1 force-pushed the feat/knowledge-source-extract branch 3 times, most recently from af85415 to 4cb2f34 Compare November 4, 2026 03:06
@zlareb1
zlareb1 force-pushed the feat/knowledge-source-extract branch 3 times, most recently from 16bb66d to 72d7839 Compare November 4, 2026 04:45
zlareb1 and others added 7 commits November 4, 2026 05:13
After every source's turn the knowledge_source_sync pass mines, with
decision_extract.extract_document, each of the source's documents whose
stored revision is not the one recorded as mined for it in the source's
sync state; the revision is recorded only once that document's
extraction settled. Rows go to the trunk code namespace as agent
loom-decisions under the worker's actor, each write whole with its
audit row, and the run stops writing once the pass stops or the source's
lease is lost.

The leg reads the cap share (knowledge_source_sync_cap_share, fail
closed) before each document and the org switch once per pass, waits out
holds without counting a try, bills each document's spend to its
namespace, stops model reads before the pass's deadline, settles
permanent refusals and documents too large for a pass, and gives a
document up after three failed tries until it is written again.
knowledge.source.list and inspect show the pending count and the last
mining turn's counts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…rite a cancel left running

A lease seen lost by may_write ends that source's turn like LeaseLost from
the lease itself, and the leg goes on to the next source; only a stopped
pass ends the leg. A document's spend is emitted after the write units it
started finish, so a unit a cancel left running is billed in its row. The
pass bound inside a turn is the source's reason to wait, and the reason
clears once nothing waits. knowledge_source_sync_max_pass_seconds has a
floor of 180 s: 90 for the sync, 60 of read time and 30 for the writes.
The full-pass read share is its own constant, and reads_stopped names what
it checks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…write is that source's error

extract_document holds its write units in a TaskSet the caller passes
(writes=), and finish_writes waits only for those, so the sync worker
bills a unit a cancel left running without waiting for, or billing, a
concurrent run's. An empty TaskSet is falsy, so the set is compared with
None. The cost row is emitted in a finally after the wait. A failed state
write for a source that waits, and a failed read of a source's
documents, are that source's error and the leg goes on. Comments and the
extract help are reworded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
A recording source's transcript documents are read through
store.source_revisions like any other source's, so the leg mines them;
a test runs it over a meeting source. The knowledge page says the sync
mines transcripts too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
extract_document passes `writes` to the write and retire steps as it
passes may_write, so the context variable and the split of the function
are gone. Tests cover a cancelled run's pending unit held in its own set
while another run's is still pending, and a failed read of a source's
documents as that source's error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
Sources with nothing to mine and no stale count are left out while the
queues are built, the deferred reasons name pass_bound, and the lease
comment says a removed source has nothing to record. The pass-budget
test runs at the setting's 180 s floor with no share left to start a
source, instead of a value the setting refuses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
@zlareb1
zlareb1 force-pushed the feat/knowledge-source-extract branch from a018fc3 to 9d7bfc5 Compare November 4, 2026 05:15
@zlareb1
zlareb1 merged commit d84b044 into main Nov 4, 2026
19 checks passed
@zlareb1
zlareb1 deleted the feat/knowledge-source-extract branch November 4, 2026 05:17
@pufit pufit mentioned this pull request Nov 4, 2026
9 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant