Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge origin/master into #6007

garrytand6cf09d85a4c
diff --cc scripts/module-size-limits.tsv
index 0b6c35223a,c8d143f471..5cf45cefa8
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@@ -19,9 -19,9 +19,9 @@@ src/core/cycle/extract-atoms.ts 1808 ra
src/core/engine.ts 2678 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse)
src/core/import-file.ts 2178 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
-src/core/operations.ts 336 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts)
+src/core/operations.ts 337 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +1 #6007: pageBatchOperations import (spread shares the pages line)
src/core/pglite-engine.ts 2926 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts)
- src/core/postgres-engine.ts 2914 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216)
+ src/core/postgres-engine.ts 2917 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured)
src/core/search/hybrid.ts 1584 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key
src/core/types.ts 2124 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field)
src/core/minions/queue.ts 2522 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys
diff --cc src/core/persistence/service.ts
index ab4257989a,79a0a1aee1..6ba2644042
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@@ -15,18 -16,11 +16,31 @@@ import { contentRefusalFromReceipt } fr
import { heldFileDiagnostic } from './verb-errors.ts';
import { isMissingPageMessage } from './page-identity.ts';
- interface Service {
- consumer: PersistenceConsumer; stopping: boolean; unregisterStop?: () => void; unregisterReopen?: () => void;
- /** Waiters keyed by request row id; the consumer settles them in-process the moment it finishes a request. */
- settled: Map<string, Set<() => void>>;
- /** Recent claim-to-settle durations (ms), newest last, for pending retry_after_ms estimates. */
- publishMs: number[];
- }
+ interface Service { consumer: PersistenceConsumer; stopping: boolean; unregisterStop?: () => void; unregisterReopen?: () => void; }
const services = new WeakMap<BrainEngine, Service>();
- const receiptReads = new WeakMap<BrainEngine, Map<string, { read: Promise<WriteRequest | null>; abort: AbortController }>>();
- /** Cross-process commits (another owner) are not signalled; waiters re-read at this cadence. */
- const WAIT_FALLBACK_POLL_MS = 250;
- const PUBLISH_SAMPLES = 20;
+ type ProgressRead = { row: WriteRequestProgress | null } | { error: unknown } | { cancelled: true };
+ const receiptReads = new WeakMap<BrainEngine, Map<string, { read: Promise<ProgressRead>; abort: AbortController }>>();
+ const settledWaiters = new WeakMap<BrainEngine, Map<string, Set<(row: WriteRequest) => void>>>();
++/** #6007: when this process last settled requests, for pending retry_after_ms estimates. */
++const settlements = new WeakMap<BrainEngine, number[]>();
++const SETTLEMENT_SAMPLES = 21;
++function recordSettlement(engine: BrainEngine): void {
++ let times = settlements.get(engine);
++ if (!times) { times = []; settlements.set(engine, times); }
++ times.push(performance.now());
++ if (times.length > SETTLEMENT_SAMPLES) times.shift();
++}
++/**
++ * #6007: a pending receipt's retry_after_ms from this process's recent pace:
++ * `remaining` requests at the median gap between settlements, clamped to
++ * 250 ms-30 s. Null until this process has settled at least two requests.
++ */
++export function estimatedRetryAfterMs(engine: BrainEngine, remaining: number): number | null {
++ const times = settlements.get(engine) ?? [];
++ if (times.length < 2 || remaining <= 0) return null;
++ const gaps = times.slice(1).map((at, i) => at - times[i]!).sort((a, b) => a - b);
++ return Math.round(Math.min(30_000, Math.max(250, gaps[Math.floor(gaps.length / 2)]! * remaining)));
++}
const preparers = new Map<string, { prepare: PrepareMutation; target: 'page' | 'skill_bundle' }>();
export function registerMutationPreparer(operation: string, prepare: PrepareMutation, target: 'page' | 'skill_bundle' = 'page'): void {
preparers.set(operation, { prepare, target });
@@@ -71,16 -65,9 +85,9 @@@ export function startPersistenceConsume
}
return prior.consumer;
}
- const settled = new Map<string, Set<() => void>>();
- const publishMs: number[] = [];
- const consumer = new PersistenceConsumer(engine, config, preparePersistedMutation, {
- onSettled: (id, elapsedMs) => {
- publishMs.push(elapsedMs);
- if (publishMs.length > PUBLISH_SAMPLES) publishMs.shift();
- for (const wake of settled.get(id) ?? []) wake();
- },
- });
- const service: Service = { consumer, stopping: false, settled, publishMs };
+ const consumer = new PersistenceConsumer(engine, config, preparePersistedMutation,
- { onSettled: row => { for (const listener of settledWaiters.get(engine)?.get(row.id) ?? []) listener(row); } });
++ { onSettled: row => { recordSettlement(engine); for (const listener of settledWaiters.get(engine)?.get(row.id) ?? []) listener(row); } });
+ const service: Service = { consumer, stopping: false };
services.set(engine, service);
const lifecycle = engine as BrainEngine & { registerBeforeDisconnect?: (run: () => Promise<void>) => unknown };
const unregister = lifecycle.registerBeforeDisconnect?.(() => stopPersistenceConsumer(engine));
@@@ -127,88 -113,110 +133,121 @@@ export function assertPersistenceAccept
'Nothing new was accepted. After the owner restarts, resubmit with the same request_id so a write that was already accepted is never applied twice.');
}
}
+ /** DX-A3: pending heads that need intervention, not more waiting. */
+ export const BLOCKED_WRITE_REASONS = ['recovery_required', 'owner_unavailable', 'unexpected_file_bytes', 'unexpected_staging_bytes'] as const;
+ const FATAL_READ_REASONS: readonly PgAccessReason[] = ['auth_failed', 'permission_denied', 'tenant_not_found', 'db_missing', 'schema_missing', 'storage_corrupt'];
+ /** CEO-A7: the first poll waits this long (at most half the wait) for an in-process handoff; later polls back off from 50 to 250 ms. */
+ export const WRITE_POLL_START_MS = 200;
+ export type WriteWait =
+ | { kind: 'terminal' | 'pending'; row: WriteRequest }
+ | { kind: 'blocked'; row: WriteRequest; request_id: string; cause: typeof BLOCKED_WRITE_REASONS[number]; command: string }
+ | { kind: 'read_failed'; row: WriteRequest; request_id: string; reason: PgAccessReason; transient: boolean; sqlstate?: string;
+ attempts: number; message: string; why: string };
/**
+ * Waits for an admitted write and classifies how the wait ended. A request this
+ * process publishes is handed over by its consumer without a read; otherwise a
+ * narrow progress read polls, and the full row is read once when terminal. The
+ * waiter's own cancelled reads are not failures; database read failures are
+ * classified (`read_failed`) instead of reading as a still-pending write.
* The waiter never owns a provider, database connection, or kernel lock.
- * #6007: between receipt reads it sleeps until the in-process consumer settles
- * this request (or a short fallback for commits made by another process),
- * instead of re-reading every 50 ms for the whole wait.
*/
- export async function waitForWrite(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, waitMs = 5000): Promise<WriteRequest> {
- if (isTerminal(row)) return row;
- // The admission transaction has committed: publish now, not after the idle backoff.
- startPersistenceConsumer(engine, config).wake();
+ export async function awaitWrite(engine: BrainEngine, row: WriteRequest, config: GBrainConfig,
+ opts: { waitMs?: number; signal?: AbortSignal } = {}): Promise<WriteWait> {
+ if (isTerminal(row)) return { kind: 'terminal', row };
+ const consumer = startPersistenceConsumer(engine, config);
const service = services.get(engine)!;
- let reads = receiptReads.get(engine);
- if (!reads) { reads = new Map(); receiptReads.set(engine, reads); }
- const deadline = performance.now() + waitMs;
- let signalled = false;
+ const id = row.id;
+ let handed: WriteRequest | undefined;
let wake: (() => void) | undefined;
- const listener = () => { signalled = true; wake?.(); };
- let listeners = service.settled.get(row.id);
- if (!listeners) { listeners = new Set(); service.settled.set(row.id, listeners); }
- listeners.add(listener);
- let pause = 50;
+ let waiters = settledWaiters.get(engine);
+ if (!waiters) { waiters = new Map(); settledWaiters.set(engine, waiters); }
+ const listeners = waiters.get(id) ?? new Set();
+ const listener = (settled: WriteRequest) => { handed = settled; wake?.(); };
+ listeners.add(listener); waiters.set(id, listeners);
+ // The admission transaction has committed: publish now, not after the idle backoff.
+ consumer.wake();
+ const waitMs = opts.waitMs ?? 5000;
+ const deadline = performance.now() + waitMs;
+ const firstPoll = Math.min(WRITE_POLL_START_MS, waitMs / 2);
+ let delay = firstPoll, failure: { error: unknown; attempts: number } | undefined;
try {
- while (!service.stopping && performance.now() < deadline) {
- // The first pause is a plain 50 ms, as before: a commit that lands inside it
- // returns with its first effects already running, like it always has.
- if (pause === 50) await new Promise(resolve => setTimeout(resolve, Math.min(pause, Math.max(1, deadline - performance.now()))));
- else if (!signalled) {
- let sleeper: ReturnType<typeof setTimeout> | undefined;
- await new Promise<void>(resolve => { wake = resolve; sleeper = setTimeout(resolve, Math.min(pause, Math.max(1, deadline - performance.now()))); })
- .finally(() => { wake = undefined; if (sleeper) clearTimeout(sleeper); });
- }
- signalled = false;
- pause = WAIT_FALLBACK_POLL_MS;
+ while (!service.stopping && !opts.signal?.aborted) {
+ if (handed) { row = handed; handed = undefined; if (isTerminal(row)) return { kind: 'terminal', row }; }
const remaining = deadline - performance.now();
- if (service.stopping || remaining <= 0) break;
- let pending = reads.get(row.id);
- const ownsRead = !pending;
- if (!pending) {
- if (reads.size >= 4) continue;
- const abort = new AbortController();
- const id = row.id;
- const read = getWriteRequestById(engine, row.id, engine.kind === 'postgres' ? abort.signal : undefined)
- .catch(() => null).finally(() => { if (reads.get(id)?.read === read) reads.delete(id); });
- pending = { read, abort };
- reads.set(id, pending);
+ if (remaining <= 0) break;
+ await new Promise<void>(resolve => {
+ const done = () => { clearTimeout(timer); wake = undefined; opts.signal?.removeEventListener('abort', done); resolve(); };
+ const timer = setTimeout(done, Math.min(delay, remaining));
+ wake = done; opts.signal?.addEventListener('abort', done, { once: true });
+ });
+ if (handed || service.stopping || opts.signal?.aborted || performance.now() >= deadline) continue;
+ delay = delay === firstPoll ? 50 : Math.min(250, delay * 2);
+ if (consumer.holds(id)) continue;
+ const read = await readProgress(engine, id, deadline - performance.now());
+ if ('cancelled' in read) continue;
+ if ('error' in read) {
+ failure = { error: read.error, attempts: (failure?.attempts ?? 0) + 1 };
+ const { classifyPgAccessError } = await import('../pg-access-classify.ts');
+ if (FATAL_READ_REASONS.includes(classifyPgAccessError(read.error).reason)) break;
+ continue;
}
- let timer: ReturnType<typeof setTimeout> | undefined;
- const found = await Promise.race([
- pending.read,
- new Promise<null>(resolve => { timer = setTimeout(() => { if (ownsRead) pending.abort.abort(); resolve(null); }, remaining); }),
- ]).finally(() => { if (timer) clearTimeout(timer); });
- if (found) row = found;
- if (isTerminal(row)) return row;
+ failure = undefined;
+ if (!read.row) continue;
+ row = { ...row, ...read.row };
+ if (isTerminal(row)) return { kind: 'terminal', row: await getWriteRequestById(engine, id).catch(() => null) ?? row };
}
- return row;
} finally {
listeners.delete(listener);
- if (!listeners.size && service.settled.get(row.id) === listeners) service.settled.delete(row.id);
+ if (!listeners.size && waiters.get(id) === listeners) waiters.delete(id);
+ }
+ if (handed) row = handed;
+ if (isTerminal(row)) return { kind: 'terminal', row };
+ if (failure) {
+ const { classifyPgAccessError } = await import('../pg-access-classify.ts');
+ const diagnosis = classifyPgAccessError(failure.error);
+ return { kind: 'read_failed', row, request_id: row.request_id, reason: diagnosis.reason, transient: diagnosis.transient,
+ ...(diagnosis.sqlstate ? { sqlstate: diagnosis.sqlstate } : {}), attempts: failure.attempts, message: diagnosis.message, why: diagnosis.remediation };
+ }
+ const cause = BLOCKED_WRITE_REASONS.find(reason => reason === row.blocked_reason);
+ return cause ? { kind: 'blocked', row, request_id: row.request_id, cause, command: `gbrain sources writer status ${row.source_id} --json` } : { kind: 'pending', row };
+ }
+ /** At most four progress reads per engine; concurrent waiters on one request share a read. */
+ async function readProgress(engine: BrainEngine, id: string, remaining: number): Promise<ProgressRead> {
+ let reads = receiptReads.get(engine);
+ if (!reads) { reads = new Map(); receiptReads.set(engine, reads); }
+ let pending = reads.get(id);
+ const ownsRead = !pending;
+ if (!pending) {
+ if (reads.size >= 4) return { cancelled: true };
+ const abort = new AbortController();
+ const shared = reads;
+ const read: Promise<ProgressRead> = getWriteRequestProgress(engine, id, engine.kind === 'postgres' ? abort.signal : undefined)
+ .then(row => ({ row }), error => abort.signal.aborted ? { cancelled: true as const } : { error })
+ .finally(() => { if (shared.get(id)?.read === read) shared.delete(id); });
+ pending = { read, abort };
+ reads.set(id, pending);
}
+ const owned = pending;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ return Promise.race([owned.read, new Promise<ProgressRead>(resolve => {
+ timer = setTimeout(() => { if (ownsRead) owned.abort.abort(); resolve({ cancelled: true }); }, remaining);
+ })]).finally(() => { if (timer) clearTimeout(timer); });
+ }
+ /** Compatibility form of `awaitWrite`: the latest row, terminal or still pending. */
+ export async function waitForWrite(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, waitMs = 5000): Promise<WriteRequest> {
+ return (await awaitWrite(engine, row, config, { waitMs })).row;
}
+/**
+ * #6007: wait for several admitted writes against one deadline. Requests of
+ * one source publish oldest first, so waiting on each in order costs one
+ * waiter at a time; rows not reached by the deadline keep their last state.
+ */
+export async function waitForWrites(engine: BrainEngine, rows: readonly WriteRequest[], config: GBrainConfig, waitMs = 5000): Promise<WriteRequest[]> {
+ const deadline = performance.now() + waitMs;
+ const settled: WriteRequest[] = [];
+ for (const row of rows) settled.push(await waitForWrite(engine, row, config, Math.max(0, deadline - performance.now())));
+ return settled;
+}
- /**
- * #6007: a pending receipt's retry_after_ms from this process's recent
- * publication times: `remaining` requests at the median duration, clamped to
- * 250 ms-30 s. Null when this process has not published anything yet.
- */
- export function estimatedRetryAfterMs(engine: BrainEngine, remaining: number): number | null {
- const samples = [...(services.get(engine)?.publishMs ?? [])].sort((a, b) => a - b);
- if (!samples.length || remaining <= 0) return null;
- const median = samples[Math.floor(samples.length / 2)]!;
- return Math.round(Math.min(30_000, Math.max(250, median * remaining)));
- }
/** B4: what a terminal receipt means for the caller, without guessing a mutation. */
function terminalReceiptHint(row: WriteRequest, reason: string): string {
const what = `The ${row.operation ? `${row.operation} ` : ''}write (request_id ${row.request_id}) ended ${row.state} with ${reason}; it will not publish.`;