Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(extract): DB link drains defer a page a concurrent writer moved instead of aborting (#6272)

time-attackb6a257f35e10
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 721dab0f11..53ba6f2590 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -8,7 +8,7 @@ src/commands/autopilot.ts 1642 ratchet refactor wave 1 split target (W4 autopilo
src/commands/doctor.ts 667 ratchet +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
src/commands/embed.ts 2227 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts)
src/commands/extract-conversation-facts.ts 2213 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start)
-src/commands/extract.ts 2616 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale; +25 GBRA-69: extract --source db reads snapshots and publishes derived links BATCH_SIZE pages at a time (readPageSnapshotsBatch in core/page-snapshot-batch.ts, replay in derived-links.ts replaceDerivedLinksBatchOrReplay); +2 GBRA-75 w7: the --source db links walk refreshes planner statistics (logic in planner-stats.ts plannerStatsForLinkDrain)
+src/commands/extract.ts 2626 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale; +25 GBRA-69: extract --source db reads snapshots and publishes derived links BATCH_SIZE pages at a time (readPageSnapshotsBatch in core/page-snapshot-batch.ts, replay in derived-links.ts replaceDerivedLinksBatchOrReplay); +2 GBRA-75 w7: the --source db links walk refreshes planner statistics (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 13 P2.16 (#6272): both unmanaged DB link drains defer and count a page a concurrent writer moved (skipped_concurrent_write) instead of aborting the run (classifier and skip line in core/derived-links.ts)
src/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codes
src/commands/serve-http.ts 931 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts)
src/core/ai/gateway.ts 4457 ratchet +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here)
diff --git a/src/commands/extract.ts b/src/commands/extract.ts
index 7a9047d427..59379038cf 100644
--- a/src/commands/extract.ts
+++ b/src/commands/extract.ts
@@ -50,7 +50,7 @@ import { resolveCandidateSources, resolveLinkFallbackDefault, loadLinkPageMetada
import { collectWantedLinks, isWantedPagesEnabled } from '../core/wanted-links.ts';
import { readLineGrammarSettings, statedRelationTypes } from '../core/line-grammar.ts';
import { effectiveLinkExtractorWatermark, linkExtractorWatermarkFor } from '../core/link-extraction-watermark.ts';
-import { replaceDerivedLinksBatchOrReplay, replaceDerivedLinksUnlessSettingsChanged, settingsChangedSkipLine, type DerivedLinkBatchItem } from '../core/derived-links.ts';
+import { concurrentWriteSkipLine, replaceDerivedLinksBatchOrReplay, replaceDerivedLinksDeferringConflicts, settingsChangedSkipLine, type DerivedLinkBatchItem } from '../core/derived-links.ts';
import { pageSnapshotKey } from '../core/page-snapshot-batch.ts';
import type { PageSnapshot } from '../core/page-state/types.ts';
export { reconcileSourceLinks, type SourceLinkReconciliationResult } from '../core/link-reconciliation.ts';
@@ -257,6 +257,8 @@ interface ExtractResult {
skipped_missing_target?: number;
skipped_attendance_incomplete?: number;
skipped_cross_source?: number;
+ /** #6272: pages a concurrent writer changed mid-run, left unstamped (DB links path, present when non-zero). */
+ skipped_concurrent_write?: number;
/** #5904: timeline writes the writer refused or left pending (DB path); the command exits non-zero. */
timeline_refused?: number;
}
@@ -1240,6 +1242,7 @@ export async function runExtract(engine: BrainEngine, args: string[], authority?
result.skipped_missing_target = r.skippedMissingTarget;
result.skipped_cross_source = r.skippedCrossSource;
if (r.skippedAttendanceIncomplete) result.skipped_attendance_incomplete = r.skippedAttendanceIncomplete;
+ if (r.skippedConcurrentWrite) result.skipped_concurrent_write = r.skippedConcurrentWrite;
}
if (subcommand === 'timeline' || subcommand === 'all') {
const r = await (await import('./extract-timeline-db.ts')).extractTimelineFromDB(engine, { dryRun, jsonMode, typeFilter, since, sourceIdFilter, inferDates });
@@ -1804,7 +1807,7 @@ async function extractLinksFromDB(
typeFilter: PageType | undefined,
since: string | undefined,
opts?: { includeFrontmatter?: boolean; sourceIdFilter?: string; stampWatermark?: boolean },
-): Promise<{ created: number; pages: number; unresolved: UnresolvedFrontmatterRef[]; skippedMissingTarget: number; skippedCrossSource: number; skippedAttendanceIncomplete: number }> {
+): Promise<{ created: number; pages: number; unresolved: UnresolvedFrontmatterRef[]; skippedMissingTarget: number; skippedCrossSource: number; skippedAttendanceIncomplete: number; skippedConcurrentWrite?: number }> {
const includeFrontmatter = opts?.includeFrontmatter ?? false;
const sourceIdFilter = opts?.sourceIdFilter;
// C3 (D6): the links_extracted_at watermark covers links AND timeline, so a
@@ -1887,7 +1890,7 @@ async function extractLinksFromDB(
const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));
const grammar = await readLineGrammarSettings(engine), lineGrammar = { enabled: grammar.enabled, allowUndeclaredTypes: grammar.allowUndeclaredTypes };
- let skippedSettingsChanged = 0;
+ let skippedSettingsChanged = 0, skippedConcurrentWrite = 0;
progress.start('extract.links_db', walkRefs.length);
const plannerTick = dryRun ? async () => {} : await plannerStatsForLinkDrain(engine, async () => walkRefs.length);
@@ -1905,7 +1908,9 @@ async function extractLinksFromDB(
});
writes.forEach(({ slug, source_id }, i) => {
const written = results[i];
- if (written) { created += written.created; processed++; processedRefs.push({ slug, source_id }); } else skippedSettingsChanged++;
+ if (written === 'settings_changed') skippedSettingsChanged++;
+ else if (written === 'concurrent_write') skippedConcurrentWrite++;
+ else { created += written.created; processed++; processedRefs.push({ slug, source_id }); }
progress.tick(1);
});
}
@@ -2023,6 +2028,7 @@ async function extractLinksFromDB(
console.log(`Links: ${label} ${created} from ${processed} pages (db source)`);
if (skippedAttendanceIncomplete) console.log(`Skipped ${skippedAttendanceIncomplete} page(s) with unresolved attendance; prior links and extraction watermarks were preserved.`);
if (skippedSettingsChanged) console.log(settingsChangedSkipLine(skippedSettingsChanged));
+ if (skippedConcurrentWrite) console.log(concurrentWriteSkipLine(skippedConcurrentWrite));
if (skippedMissingTarget > 0) {
console.log(`Skipped ${skippedMissingTarget} candidate(s) whose target page doesn't exist (references to non-pages are never persisted).`);
}
@@ -2047,7 +2053,7 @@ async function extractLinksFromDB(
// #2589: the counters ride the return value so machine consumers (and the
// --json path, which has no summary event on this path) can see the drops —
// "counted, never silent" must hold beyond human-mode console lines.
- return { created, pages: processed, unresolved, skippedMissingTarget, skippedCrossSource, skippedAttendanceIncomplete, ...(skippedSettingsChanged ? { skippedSettingsChanged } : {}) };
+ return { created, pages: processed, unresolved, skippedMissingTarget, skippedCrossSource, skippedAttendanceIncomplete, ...(skippedSettingsChanged ? { skippedSettingsChanged } : {}), ...(skippedConcurrentWrite ? { skippedConcurrentWrite } : {}) };
}
/**
@@ -2085,7 +2091,7 @@ export async function extractStaleFromDB(
*/
timeBudgetMs?: number;
},
-): Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number; skippedCrossSource?: number; skippedAttendanceIncomplete?: number; skippedChanged?: number; mentions?: MentionPassResult }> {
+): Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number; skippedCrossSource?: number; skippedAttendanceIncomplete?: number; skippedChanged?: number; skippedConcurrentWrite?: number; mentions?: MentionPassResult }> {
const { dryRun, jsonMode, sourceIdFilter, catchUp } = opts;
const includeFrontmatter = opts.includeFrontmatter ?? await resolveIncludeFrontmatter(engine);
const log = opts.quiet ? (..._args: unknown[]) => {} : console.log;
@@ -2172,7 +2178,7 @@ export async function extractStaleFromDB(
// in a source other than the origin's or 'default' — default-deny by
// design (source isolation) unless the #3908 flag is on, but distinct
// from a genuinely missing target.
- let skippedCrossSource = 0, skippedChanged = 0;
+ let skippedCrossSource = 0, skippedChanged = 0, skippedConcurrentWrite = 0;
const wantedEnabled = await isWantedPagesEnabled(engine);
const plannerTick = await plannerStatsForLinkDrain(engine, async () => totalStale);
@@ -2206,7 +2212,7 @@ export async function extractStaleFromDB(
continue;
}
const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });
- if (!snapshot) throw new Error('Link extraction origin changed during the stale scan');
+ if (!snapshot) { skippedConcurrentWrite++; continue; } // deleted since the stale scan: nothing to stamp
const fullContent = snapshot.page.compiled_truth + '\n' + snapshot.page.timeline;
const linkRows: LinkBatchInput[] = [];
if (!resolvers.has(page.source_id)) resolvers.set(page.source_id, makeResolver(engine, { mode: 'batch', sourceId: page.source_id }));
@@ -2245,8 +2251,10 @@ export async function extractStaleFromDB(
const linkOpts = { includeFrontmatter, lineGrammar: grammar, expectedEndpoints: capturedLinkEndpoints(linkRows, targetMetadata),
wanted: { producers: includeFrontmatter ? ['body', 'frontmatter'] as const : ['body'] as const, rows: wanted } };
const stampIso = page.updated_at.getTime() >= Date.parse(versionTs) ? page.updated_at_iso : versionTs;
- const written = await replaceDerivedLinksUnlessSettingsChanged(engine, origin, linkRows, linkOpts);
- if (!written) { skippedChanged++; continue; } // settings moved mid-run: not stamped, re-extracts next run
+ const written = await replaceDerivedLinksDeferringConflicts(engine, origin, linkRows, linkOpts);
+ // Settings moved, or a concurrent writer moved the page or an endpoint (#6272): not stamped, re-extracts next run.
+ if (written === 'settings_changed') { skippedChanged++; continue; }
+ if (written === 'concurrent_write') { skippedConcurrentWrite++; continue; }
linksCreated += written.created;
await retractRemovedTimelineEntries(engine, page.slug, page.source_id, fullContent);
for (const entry of parseTimelineEntries(fullContent)) {
@@ -2304,6 +2312,7 @@ export async function extractStaleFromDB(
if (mentionLine) log(mentionLine);
if (skippedAttendanceIncomplete) log(`Skipped ${skippedAttendanceIncomplete} page(s) with unresolved attendance; prior links and extraction watermarks were preserved.`);
if (skippedChanged) log(settingsChangedSkipLine(skippedChanged));
+ if (skippedConcurrentWrite) log(concurrentWriteSkipLine(skippedConcurrentWrite));
if (skippedMissingTarget > 0) {
log(`Skipped ${skippedMissingTarget} candidate(s) whose target page doesn't exist (references to non-pages are never persisted).`);
}
@@ -2318,11 +2327,12 @@ export async function extractStaleFromDB(
action: 'extract_stale_done', links_created: linksCreated, timeline_created: timelineCreated,
pages_processed: pagesProcessed, stale_remaining: staleRemaining, budget_hit: budgetHit,
skipped_missing_target: skippedMissingTarget, skipped_cross_source: skippedCrossSource,
- ...(skippedAttendanceIncomplete ? { skipped_attendance_incomplete: skippedAttendanceIncomplete } : {}), ...(skippedChanged ? { skipped_changed: skippedChanged } : {}), ...mentionJsonFields(mentions),
+ ...(skippedAttendanceIncomplete ? { skipped_attendance_incomplete: skippedAttendanceIncomplete } : {}), ...(skippedChanged ? { skipped_changed: skippedChanged } : {}),
+ ...(skippedConcurrentWrite ? { skipped_concurrent_write: skippedConcurrentWrite } : {}), ...mentionJsonFields(mentions),
}) + '\n');
}
return { linksCreated, timelineCreated, pagesProcessed, staleRemaining, skippedMissingTarget, skippedCrossSource,
- ...(skippedAttendanceIncomplete ? { skippedAttendanceIncomplete } : {}), ...(skippedChanged ? { skippedChanged } : {}), mentions };
+ ...(skippedAttendanceIncomplete ? { skippedAttendanceIncomplete } : {}), ...(skippedChanged ? { skippedChanged } : {}), ...(skippedConcurrentWrite ? { skippedConcurrentWrite } : {}), mentions };
}
/**
diff --git a/src/core/derived-links.ts b/src/core/derived-links.ts
index d90b8441e3..bf1107ff27 100644
--- a/src/core/derived-links.ts
+++ b/src/core/derived-links.ts
@@ -1,5 +1,5 @@
import type { BrainEngine, LinkBatchInput } from './engine.ts';
-import { assertPageRevision, type PageSnapshot } from './page-state/types.ts';
+import { assertPageRevision, PageRevisionConflictError, RevisionBackfillPendingError, type PageSnapshot } from './page-state/types.ts';
import { pipelined } from './page-state/transactions.ts';
import { executeRawJsonb } from './sql-query.ts';
import { pageSnapshotKey } from './page-snapshot-batch.ts';
@@ -64,10 +64,33 @@ export async function replaceDerivedLinksUnlessSettingsChanged(engine: Pick<Brai
catch (error) { if (error instanceof DerivedLinkSettingsChangedError) return null; throw error; }
}
+/**
+ * #6272: a concurrent writer moved a link endpoint after type resolution, or the origin itself after its snapshot
+ * read. Instance checks only: settings changes, backfill-pending revisions and every other error stay fatal.
+ */
+export function isConcurrentLinkWriteConflict(error: unknown): boolean {
+ return (error instanceof DerivedLinkEndpointChangedError && !(error instanceof DerivedLinkSettingsChangedError))
+ || (error instanceof PageRevisionConflictError && !(error instanceof RevisionBackfillPendingError));
+}
+
+/** A deferring caller's outcome for one origin: written, left stale by a settings change, or by a concurrent write. */
+export type DeferredDerivedLinkOutcome = { created: number; removed: number } | 'settings_changed' | 'concurrent_write';
+
+/** replaceDerivedLinksUnlessSettingsChanged for a run that defers (and counts) pages a concurrent writer moved. */
+export async function replaceDerivedLinksDeferringConflicts(engine: Pick<BrainEngine, 'replaceDerivedLinks'>,
+ ...args: Parameters<BrainEngine['replaceDerivedLinks']>): Promise<DeferredDerivedLinkOutcome> {
+ try { return await replaceDerivedLinksUnlessSettingsChanged(engine, ...args) ?? 'settings_changed'; }
+ catch (error) { if (isConcurrentLinkWriteConflict(error)) return 'concurrent_write'; throw error; }
+}
+
/** The operator line for pages a settings change left stale mid-run. */
export const settingsChangedSkipLine = (n: number) =>
`Skipped ${n} page(s) because the line-grammar settings changed during this run; they stay stale. Run \`gbrain extract --stale\` to finish them.`;
+/** The operator line for pages a concurrent write left stale mid-run. */
+export const concurrentWriteSkipLine = (n: number) =>
+ `Skipped ${n} page(s) another writer changed during this run (the page or a link target); their links and watermark were kept, so they stay stale. Run \`gbrain extract --stale\` to finish them.`;
+
export async function applyAttendanceDelta(tx: Pick<BrainEngine, 'executeRaw' | 'addLinksBatch'>,
origin: { id: string; slug: string; source_id: string; type: string }, remove: string[], additions: LinkBatchInput[]) {
if (origin.type !== 'meeting' || remove.length > 512 || additions.length > 256
@@ -178,18 +201,19 @@ export async function replaceDerivedLinksBatch(
/**
* Publish through replaceDerivedLinksBatch; when that transaction fails,
- * replay the origins one by one so every outcome is the unbatched one: null
- * for a settings-changed skip, and the first failing origin's error thrown
- * (after `onError`) with the origins before it committed.
+ * replay the origins one by one so every outcome is the unbatched one:
+ * `settings_changed` for a settings-changed skip, `concurrent_write` for an
+ * origin a concurrent writer moved (#6272), and any other failing origin's
+ * error thrown (after `onError`) with the origins before it committed.
*/
export async function replaceDerivedLinksBatchOrReplay(engine: Pick<BrainEngine, 'replaceDerivedLinks' | 'replaceDerivedLinksBatch'>,
- items: readonly DerivedLinkBatchItem[], onError?: (item: DerivedLinkBatchItem) => void): Promise<Array<{ created: number; removed: number } | null>> {
+ items: readonly DerivedLinkBatchItem[], onError?: (item: DerivedLinkBatchItem) => void): Promise<DeferredDerivedLinkOutcome[]> {
if (!items.length) return [];
try { return await engine.replaceDerivedLinksBatch(items); }
catch {
- const results: Array<{ created: number; removed: number } | null> = [];
+ const results: DeferredDerivedLinkOutcome[] = [];
for (const item of items) {
- try { results.push(await replaceDerivedLinksUnlessSettingsChanged(engine, item.origin, item.links, item.opts)); }
+ try { results.push(await replaceDerivedLinksDeferringConflicts(engine, item.origin, item.links, item.opts)); }
catch (error) { onError?.(item); throw error; }
}
return results;
diff --git a/test/extract-endpoint-revision.serial.test.ts b/test/extract-endpoint-revision.serial.test.ts
index de9b064d33..3026b4f25a 100644
--- a/test/extract-endpoint-revision.serial.test.ts
+++ b/test/extract-endpoint-revision.serial.test.ts
@@ -1,6 +1,8 @@
import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';
import type { BrainEngine, LinkBatchInput } from '../src/core/engine.ts';
import type { DerivedLinkOrigin, DerivedLinkReplacementOptions } from '../src/core/derived-links.ts';
+import { DerivedLinkEndpointChangedError, DerivedLinkSettingsChangedError, replaceDerivedLinksBatchOrReplay } from '../src/core/derived-links.ts';
+import { PageRevisionConflictError, RevisionBackfillPendingError } from '../src/core/page-state/types.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { runExtract, extractStaleFromDB } from '../src/commands/extract.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
@@ -93,11 +95,10 @@ for (const kind of ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] : [])]
const errorSpy = spyOn(console, 'error').mockImplementation((...args) => { errors.push(args.join(' ')); });
const exitSpy = spyOn(process, 'exit').mockImplementation(code => { throw new Error(`extract exited ${code}`); });
try {
- await expect(run()).rejects.toThrow(mode === 'stale' ? 'endpoint changed after type resolution' : 'extract exited 1');
- if (mode !== 'stale') {
- expect(exitSpy).toHaveBeenCalledWith(1);
- expect(errors).toContain('A derived link endpoint changed after type resolution');
- }
+ // #6272: the run defers the conflicted origin (unstamped, graph untouched) instead of aborting.
+ await run();
+ expect(exitSpy).not.toHaveBeenCalled();
+ expect(errors).not.toContain('A derived link endpoint changed after type resolution');
} finally {
engine.replaceDerivedLinks = original;
engine.replaceDerivedLinksBatch = originalBatch;
@@ -118,5 +119,75 @@ for (const kind of ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] : [])]
});
}
}
+
+ for (const mode of ['links', 'all', 'stale']) {
+ test(`${mode}: a later origin edited after its snapshot read is deferred unstamped; its siblings are written (#6272)`, async () => {
+ const slugs = ['notes/a', 'notes/b', 'notes/c'];
+ // a -> c, b -> c, c -> a: no origin links to b, so editing b moves no other origin's endpoint.
+ for (const [slug, to] of [['notes/a', 'notes/c'], ['notes/b', 'notes/c'], ['notes/c', 'notes/a']]) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `Links [[${to}]].` }, { sourceId });
+ }
+ const stamps = async () => Object.fromEntries((await engine.executeRaw<{ slug: string; links_extracted_at: string | null }>(
+ 'SELECT slug,links_extracted_at FROM pages WHERE source_id=$1 AND slug=ANY($2) ORDER BY slug', [sourceId, slugs])).map(r => [r.slug, r.links_extracted_at]));
+ const outgoing = async (slug: string) => (await engine.executeRaw<{ to_slug: string }>(
+ `SELECT t.slug AS to_slug FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id
+ WHERE f.source_id=$1 AND f.slug=$2 AND l.link_source='markdown' ORDER BY t.slug`, [sourceId, slug])).map(r => r.to_slug);
+ await engine.executeRaw('UPDATE pages SET links_extracted_at=NULL WHERE source_id=$1', [sourceId]);
+ const original = engine.replaceDerivedLinks, originalBatch = engine.replaceDerivedLinksBatch;
+ let edited = false;
+ // Another writer edits b after its snapshot was read, just as b's links are published.
+ const editLaterOrigin = async (origins: DerivedLinkOrigin[]) => {
+ if (edited || !origins.some(origin => origin.slug === 'notes/b')) return;
+ edited = true;
+ await engine.putPage('notes/b', { type: 'note', title: 'notes/b', compiled_truth: 'Edited by another writer: [[notes/a]].' }, { sourceId });
+ };
+ engine.replaceDerivedLinks = async (origin, links, opts) => { await editLaterOrigin([origin]); return original.call(engine, origin, links, opts); };
+ engine.replaceDerivedLinksBatch = async items => { await editLaterOrigin(items.map(item => item.origin)); return originalBatch.call(engine, items); };
+ const out: string[] = [];
+ const writeSpy = spyOn(process.stdout, 'write').mockImplementation(((chunk: string) => { out.push(String(chunk)); return true; }) as never);
+ const logSpy = spyOn(console, 'log').mockImplementation((...args) => { out.push(args.join(' ')); });
+ const exitSpy = spyOn(process, 'exit').mockImplementation(code => { throw new Error(`extract exited ${code}`); });
+ let stale: Awaited<ReturnType<typeof extractStaleFromDB>> | undefined;
+ try {
+ if (mode === 'stale') stale = await extractStaleFromDB(engine, { dryRun: false, jsonMode: true, sourceIdFilter: sourceId, includeFrontmatter: false, catchUp: false });
+ else await runExtract(engine, [mode, '--source', 'db', '--source-id', sourceId, '--json']);
+ } finally {
+ engine.replaceDerivedLinks = original;
+ engine.replaceDerivedLinksBatch = originalBatch;
+ writeSpy.mockRestore();
+ logSpy.mockRestore();
+ exitSpy.mockRestore();
+ }
+ expect(edited).toBe(true);
+ expect(exitSpy).not.toHaveBeenCalled();
+ const summary = out.map(line => { try { return JSON.parse(line); } catch { return null; } }).filter(Boolean).at(-1);
+ expect(summary.skipped_concurrent_write).toBe(1);
+ if (stale) expect(stale.skippedConcurrentWrite).toBe(1);
+ expect(await outgoing('notes/a')).toEqual(['notes/c']);
+ expect(await outgoing('notes/c')).toEqual(['notes/a']);
+ // The deferred origin kept nothing from the read it lost: no links from that read, no stamp.
+ expect(await outgoing('notes/b')).toEqual([]);
+ expect(out.join('\n')).not.toContain('extract exited');
+ const after = await stamps();
+ expect(after['notes/b']).toBeNull();
+ if (mode !== 'links') { expect(after['notes/a']).not.toBeNull(); expect(after['notes/c']).not.toBeNull(); }
+ // The next run finishes it from the new content.
+ if (mode === 'stale') await extractStaleFromDB(engine, { dryRun: false, jsonMode: true, quiet: true, sourceIdFilter: sourceId, includeFrontmatter: false, catchUp: false });
+ else await runExtract(engine, [mode, '--source', 'db', '--source-id', sourceId, '--json']);
+ expect(await outgoing('notes/b')).toEqual(['notes/a']);
+ for (const slug of slugs) await engine.executeRaw('DELETE FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);
+ });
+ }
+
+ test('only a real concurrent write defers; a synthetic revision_conflict, a backfill-pending revision and storage errors stay fatal (#6272)', async () => {
+ const item = { origin: { slug: 'notes/x', sourceId, expectedRevision: '00000000-0000-0000-0000-000000000000', sourceIncarnation: '00000000-0000-0000-0000-000000000000' }, links: [] };
+ const failing = (error: unknown) => ({ replaceDerivedLinks: async () => { throw error; }, replaceDerivedLinksBatch: async () => { throw error; } }) as unknown as BrainEngine;
+ expect(await replaceDerivedLinksBatchOrReplay(failing(new DerivedLinkEndpointChangedError('moved')), [item])).toEqual(['concurrent_write']);
+ expect(await replaceDerivedLinksBatchOrReplay(failing(new PageRevisionConflictError('a', 'b')), [item])).toEqual(['concurrent_write']);
+ expect(await replaceDerivedLinksBatchOrReplay(failing(new DerivedLinkSettingsChangedError()), [item])).toEqual(['settings_changed']);
+ for (const fatal of [Object.assign(new Error('synthetic'), { code: 'revision_conflict' }), new RevisionBackfillPendingError('a'), new TypeError('bad row')]) {
+ await expect(replaceDerivedLinksBatchOrReplay(failing(fatal), [item])).rejects.toBe(fatal);
+ }
+ });
});
}