Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

#6712 PR 3 L6: cheaper managed-sync publishes, statement budgets

garrytanf7abe6c4c27f
diff --git a/docs/architecture/key-files/core-persistence-capacity.md b/docs/architecture/key-files/core-persistence-capacity.md
index 165e095a15..c6aa791616 100644
--- a/docs/architecture/key-files/core-persistence-capacity.md
+++ b/docs/architecture/key-files/core-persistence-capacity.md
@@ -12,3 +12,10 @@ Cumulative write caps (permanent request ids, receipt bytes) and the paths that
- `src/core/persistence/refusal-breaker.ts` — `assertRefusalBreakerClosed`: `submitMaintenance` refuses before admission after `persistence.maintenance.refusal_breaker_threshold` (3; 0 off) same-code terminal refusals in 24 h for the same request `digest` (source, slug, intent with its revision and planner); `listSuppressedWrites` feeds doctor `maintenance_write_drift`. The ghost case (`canonical_file_missing`, tagged by `page-prepare.ts`, kept in `error_detail.origin`, returned by `liveFileDrift`) refuses before admission in `prepared-maintenance.ts`. Test: `test/maintenance-ghost-breaker-6696.test.ts`.
- Sync: `sync-run.ts` `preflightSyncCapacity` refuses `write_quota_insufficient` before a run's first admission; `sync-drain.ts` stops a later cap refusal `resumable` / `capacity_paused` (`drain.capacity_pause`). Test: `test/sync-capacity-preflight.test.ts`.
- Doctor: `persistence_capacity` (forecast), `persistence_compaction` and `persistence_counter_drift` (`src/commands/doctor/checks/persistence-compaction.ts`; one-statement comparison of counters with request and lifecycle reservations). Test: `test/doctor-persistence-compaction.test.ts`.
+
+## Publication cost
+
+What a managed publish costs in statements and round trips, and how it is measured (#6712 PR 3). Budgets: `test/managed-import-statement-budget.test.ts` (PGLite) and `test/e2e/managed-import-statement-budget.test.ts` (Postgres wire trace) count one YC-shaped page's publication transaction; `test/sync-status-statement-budget.test.ts` holds `sync status` to a fixed statement count at 61,000 receipts. Helpers: `test/helpers/yc-shaped-page.ts`, `statement-counter.ts`, `managed-import-budget.ts`, `latency-proxy.ts`.
+
+- `src/core/persistence/publication-timing.ts` (#6712 L6) — `timePublicationStep('apply' | 'effects', slug, run)` wraps a publication member's apply and its `queuePublicationEffects` call (`coordinator.ts`, `group-publish.ts`): process-local totals (`publicationStepTotals`) for tests and benchmarks, and one `[sync] publish <step> <slug>: Nms` line on stderr only under `GBRAIN_SYNC_TRACE`. It measures and never changes the outcome (a throwing step is timed and rethrown).
+- `addCodeReferenceLinks` in `src/core/engine-sql/links.ts` (#6712 L6) — a page's doc↔impl code-reference edges (`documents` from the page, `documented_by` back) in one set-based statement: endpoints resolve in the page's source under `FOR KEY SHARE`, a missing endpoint drops its edge, a repeated edge keeps its last context, and a re-import updates context and origin field in place. `import-file.ts` and `page-body/streamed-import.ts` call it once per page inside a savepoint (a failure leaves the page import intact), where each reference used to cost two sequential `addLink` statements.
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.md
index 582f19201b..5f9de48240 100644
--- a/docs/architecture/key-files/persistence-stalls.md
+++ b/docs/architecture/key-files/persistence-stalls.md
@@ -45,5 +45,5 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor
- `src/core/persistence/consumer-lane.ts` — #6317 (reporter ask 2): `consumerStatementEngine`, the Proxy that routes the consumer's own tick statements (idle probe, switch read, recovery and expired-claim scans, capacity, releases, floor) to `executeRawDirect` while the dual pool is active (`GBRAIN_DIRECT_DATABASE_URL` or the Supabase-derived direct URL), so the owner's round-trips avoid a transaction-mode pooler; `status().connection = { lane, pooler_mode, direct_host? }` says which lane is in use, and one `[persistence] phase=start reason=transaction_pooler` line prints when only a `prepare=false` URL exists.
- `src/core/persistence/consumer-diagnostics.ts` — #6317 (B3, I1): `hostConsumersReport` (the `host.consumers` block of `writer status --json`), `consumerOverlap` (two resident-kind full rows alive over 30 s), `ownersWithoutHeartbeat` (claim owners on running claims with no row) and `hostIdentityMismatches` (this process's `host.json` id differs from a binding owner's while the owner's checkout resolves on this filesystem or the machine id matches), read-only and shared by doctor and writer status.
- `src/core/postgres-engine/pool-stats.ts` — #6317 (C1, G1): `driverPoolStats(sql)` reads the vendored postgres.js driver's `sql.pool` getter (`vendor/postgres`, patch regenerated) for real `{checked_out, max, waiters}`; `enginePoolStats(engine)` labels the source (`driver` or `tracked_subset` from `pool-gauge.ts`). Filled into the heartbeat row, `writer status` running claims and `getPoolDiagnostics()`.
-- `src/core/persistence/publication-deadline.ts` (#6288 part 1, #6352; UC2) — what bounds a publish that neither resolves nor rejects. On Postgres the publish transaction is the real bound: `declareDurablePersistence` already sets a transaction-local `statement_timeout` (5 s) and `lock_timeout`, and `bindPublicationTimeouts` (first statement of `publishMutation`'s and `publishGroup`'s transactions, pipelined, no extra round trip) adds a transaction-local `idle_in_transaction_session_timeout` of `persistence.publication_ceiling_ms` (default 300000, 60000 to 3600000; never above the pool's own `GBRAIN_IDLE_TX_TIMEOUT`), so a publisher stuck between statements is ended by the server and commits nothing; both survive a transaction pooler that drops startup parameters. Never set on PGLite: it would enforce the bound, and a transaction it ends wedges the engine's only connection. `boundPublication` (the consumer's single path and `executeClaimedGroup`'s group publish and per-member fallback) settles only with the publish's own outcome, so nothing releases or reports a request or group while its transaction can still commit; at the ceiling the claim stamp reads `waiting_on: publication_deadline`, after `PUBLICATION_GRACE_MS` (30 s) it aborts the publication's signal (passed to `engine.transaction(fn, { signal })` through `publicationTransaction`: on Postgres the connection is discarded and nothing commits; the rejection waits for the transaction body to settle, then surfaces with the driver's `CONNECTION_CLOSED` code, so the claim is requeued for a retry; PGLite checks the signal only before BEGIN), and after `PUBLICATION_SETTLE_MS` (5 s) more the consumer lists it in `stuck_publications` and reports `restart_required` (its root stays held: restarting the owner is the recovery, never a promised reclaim). The lease keeps renewing, so a reclaim never races a publisher that may still write files. The wave 9 yield between groups is outside any one bound. `PublicationBound.later` is the scheduler seam (default a real unref'd timer); the unit test drives the three phases through a manual clock so a stalled runner cannot fire a phase early (the consumer's `clock` seam is separate). Tests: `test/persistence-publication-deadline.test.ts` (barriers after the token lock, after the file rename and before commit; the server-side idle end on Postgres; the wiring probe).
+- `src/core/persistence/publication-deadline.ts` (#6288 part 1, #6352; UC2) — what bounds a publish that neither resolves nor rejects. On Postgres the publish transaction is the real bound: `declareDurablePersistence` already sets a transaction-local `statement_timeout` (5 s) and `lock_timeout`, and `declarePublication` (#6712 L6: the opening statement of `publishMutation`'s and `publishGroup`'s transactions, the same `SELECT` as `declareDurablePersistence`, so no extra round trip even where a transaction-mode pooler turns pipelining off) adds a transaction-local `idle_in_transaction_session_timeout` of `persistence.publication_ceiling_ms` (default 300000, 60000 to 3600000; never above the pool's own `GBRAIN_IDLE_TX_TIMEOUT`), so a publisher stuck between statements is ended by the server and commits nothing; both survive a transaction pooler that drops startup parameters. Never set on PGLite: it would enforce the bound, and a transaction it ends wedges the engine's only connection. `boundPublication` (the consumer's single path and `executeClaimedGroup`'s group publish and per-member fallback) settles only with the publish's own outcome, so nothing releases or reports a request or group while its transaction can still commit; at the ceiling the claim stamp reads `waiting_on: publication_deadline`, after `PUBLICATION_GRACE_MS` (30 s) it aborts the publication's signal (passed to `engine.transaction(fn, { signal })` through `publicationTransaction`: on Postgres the connection is discarded and nothing commits; the rejection waits for the transaction body to settle, then surfaces with the driver's `CONNECTION_CLOSED` code, so the claim is requeued for a retry; PGLite checks the signal only before BEGIN), and after `PUBLICATION_SETTLE_MS` (5 s) more the consumer lists it in `stuck_publications` and reports `restart_required` (its root stays held: restarting the owner is the recovery, never a promised reclaim). The lease keeps renewing, so a reclaim never races a publisher that may still write files. The wave 9 yield between groups is outside any one bound. `PublicationBound.later` is the scheduler seam (default a real unref'd timer); the unit test drives the three phases through a manual clock so a stalled runner cannot fire a phase early (the consumer's `clock` seam is separate). Tests: `test/persistence-publication-deadline.test.ts` (barriers after the token lock, after the file rename and before commit; the server-side idle end on Postgres; the wiring probe).
- `src/core/persistence/sync-discovery.ts` (#6349 staged catch-up) — when an incremental delta (not `--full`, not company) exceeds the cursor bound (100,000 entries, 16 MiB; `_setCursorBoundForTest` lowers it), `stagedSyncTarget` gallops forward over `git rev-list --first-parent last..HEAD`, verifying every candidate's delta from the last synced commit against the bound (a net delta is not monotone, so no binary search), and discovery reruns pinned at the furthest fitting commit with no working-tree entries, recording `stagedHead`; the cursor carries it and `SyncResult.staged { target, head, stages }` reports it. One commit alone above the bound refuses `request_too_large` naming the commit. `commands/sync/perform.ts` loops a drain stage by stage to HEAD (the drain's one extra HEAD-moved pass is skipped for a staged result). Tests: `test/sync-staged-catchup.test.ts`.
diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.ts
index dd3bb36bc8..75c290434b 100644
--- a/src/core/engine-sql/chunks.ts
+++ b/src/core/engine-sql/chunks.ts
@@ -102,12 +102,12 @@ export async function upsertChunksOnce(
gatewayModel = gw.getEmbeddingModelProvenance();
} catch {}
const writesRows = chunks.length > 0;
- const columnRows = writesRows && !opts?.embeddingColumn ? memo('config:embedding-columns', async () =>
- (await exec.run<{ key: string; value: string }>(sqlFragment`SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns')`)).rows)
- .then(rows => rows, () => null) : undefined;
- const modelRows = writesRows && !gatewayModel ? memo('config:embedding-model', async () =>
- (await exec.run<{ value?: string }>(sqlFragment`SELECT value FROM config WHERE key = 'embedding_model'`)).rows)
+ // #6712 L6: the column and model keys are one statement (a round trip where pipelining is off).
+ const configRows = writesRows && (!opts?.embeddingColumn || !gatewayModel) ? memo('config:embedding-write', async () =>
+ (await exec.run<{ key: string; value: string }>(sqlFragment`SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns', 'embedding_model')`)).rows)
.then(rows => rows, () => null) : undefined;
+ const columnRows = opts?.embeddingColumn ? undefined : configRows;
+ const modelRows = gatewayModel ? undefined : configRows?.then(rows => rows && rows.filter(row => row.key === 'embedding_model'));
const sealed = seal !== undefined && opts?.pageId !== undefined && chunks.length > 0 ? opts.pageId : undefined;
const sealPage = () => exec.run<{ id: number }>(sqlFragment`UPDATE pages SET chunker_version = ${seal} WHERE slug = ${slug} AND source_id = ${sourceId} RETURNING id`);
const pages = sealed !== undefined ? [{ id: sealed }] : (await (seal === undefined
diff --git a/src/core/engine-sql/links.ts b/src/core/engine-sql/links.ts
index 2a46bda8c3..4ded4bf560 100644
--- a/src/core/engine-sql/links.ts
+++ b/src/core/engine-sql/links.ts
@@ -94,6 +94,63 @@ export async function addLink(
}
+/** One code path a markdown page cites (`src/core/sync.ts:42`), with the slug of its code page. */
+export interface CodeReference { codeSlug: string; path: string; line?: number }
+
+/**
+ * The doc↔impl edges for every code path one markdown page cites, in one
+ * statement (#6712 L6; the import paths wrote two savepointed addLink calls per
+ * reference). Each reference writes what the addLink pair wrote: page→code
+ * `documents` (context `cited at <path>:<line>`, or the path) and code→page
+ * `documented_by` (context the path), both `markdown` edges whose origin is the
+ * page, field `compiled_truth`. Endpoints resolve source-qualified in the
+ * page's source under FOR KEY SHARE in the same statement snapshot; an edge
+ * whose endpoint is missing is skipped alone (a code page not imported yet);
+ * an existing edge takes the new context and origin_field; a repeated edge
+ * keeps its last occurrence, as sequential upserts would. Returns the edges
+ * written (inserted or updated).
+ */
+export async function addCodeReferenceLinks(exec: Pick<SqlExecutor, 'executeRaw'>, slug: string, sourceId: string, refs: CodeReference[]): Promise<number> {
+ const edges = new Map<string, { from_slug: string; to_slug: string; link_type: string; context: string }>();
+ for (const ref of refs) {
+ for (const [from, to, linkType, context] of [
+ [slug, ref.codeSlug, 'documents', ref.line ? `cited at ${ref.path}:${ref.line}` : ref.path],
+ [ref.codeSlug, slug, 'documented_by', ref.path],
+ ] as const) {
+ const key = JSON.stringify([from, to, linkType]);
+ edges.delete(key);
+ edges.set(key, { from_slug: from, to_slug: to, link_type: linkType, context: sanitizeForJsonb(context) });
+ }
+ }
+ if (!edges.size) return 0;
+ const rows = [...edges.values()].map((edge, ord) => ({ ...edge, ord }));
+ const written = await executeRawJsonb<RelationshipKey>(exec,
+ `WITH v AS (
+ SELECT * FROM jsonb_to_recordset(($3::jsonb)->'rows') AS v(ord int, from_slug text, to_slug text, link_type text, context text)
+ ), endpoints AS (
+ SELECT p.id, p.slug FROM pages p
+ WHERE p.source_id = $1 AND p.slug IN (SELECT from_slug FROM v UNION SELECT to_slug FROM v)
+ ORDER BY p.id
+ FOR KEY SHARE
+ )
+ INSERT INTO links (from_page_id, to_page_id, link_type, context, link_source, origin_page_id, origin_field)
+ SELECT f.id, t.id, v.link_type, v.context, 'markdown', o.id, 'compiled_truth'
+ FROM v
+ JOIN endpoints f ON f.slug = v.from_slug
+ JOIN endpoints t ON t.slug = v.to_slug
+ LEFT JOIN endpoints o ON o.slug = $2::text
+ ORDER BY v.ord
+ ON CONFLICT (from_page_id, to_page_id, link_type, link_source, origin_page_id) DO UPDATE SET
+ context = EXCLUDED.context,
+ origin_field = EXCLUDED.origin_field
+ RETURNING from_page_id, to_page_id, link_type`,
+ [sourceId, slug],
+ [{ rows }],
+ );
+ await refreshRelationships(exec, written);
+ return written.length;
+}
+
export async function addLinksBatch(exec: SqlExecutor, links: LinkBatchInput[]): Promise<number> {
// #1861: pass the batch as one JSONB document via jsonb_to_recordset instead
// of N parallel unnest(${arr}::text[]). The old text[] array-literal path
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 416c369227..ab7c4847d3 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -38,6 +38,7 @@ import { embedMultimodal, currentEmbeddingSignature } from './embedding.ts';
import { embedBatchKeepingUsable, embedBatchWithBackoff } from './embed-retry.ts';
import { isEmbeddingZeroNormError, type EmbeddingZeroNormError } from './ai/embedding-guard.ts';
import { slugifyPath, slugifyCodePath, isCodeFilePath, hasMalformedPathSegment } from './sync.ts';
+import { addCodeReferenceLinks } from './engine-sql/links.ts';
import type { ChunkInput, Page, PageInput, PageType } from './types.ts';
import type { PageSnapshot } from './page-state/types.ts';
import { pipelined } from './page-state/transactions.ts';
@@ -831,39 +832,19 @@ export async function importFromContent(
// v0.19.0 E1 — doc↔impl linking: if this markdown page cites code paths
// (e.g. 'src/core/sync.ts:42'), create bidirectional edges to the code
- // page. addLink throws when either endpoint is missing (master tightened
- // this in v0.18.x), so we wrap each pair in try/catch — guides imported
- // before their code repo syncs are common, and the missing edges land
- // later via `gbrain reconcile-links` (Layer 8 D3, v0.21.0).
+ // page, all in one statement (addCodeReferenceLinks). An edge whose code
+ // page is missing is skipped — guides imported before their code repo
+ // syncs are common, and the missing edges land later via
+ // `gbrain reconcile-links` (Layer 8 D3, v0.21.0).
const codeRefs = extractCodeRefs(sanitizeRemoteBody(parsed.compiled_truth) + '\n' + sanitizeRemoteBody(parsed.timeline || ''));
// For doc↔impl edges, both endpoints are within the same source as the
// markdown page being imported. Cross-source edges (markdown in one
- // source, code in another) currently fail with "page not found" — a
- // faster failure mode than the pre-fix cross-product fan-out, which
- // silently wired edges to whichever same-slug page Postgres returned
- // first across sources.
- const linkOpts = sourceId
- ? { fromSourceId: sourceId, toSourceId: sourceId, originSourceId: sourceId }
- : undefined;
- for (const ref of codeRefs) {
- const codeSlug = slugifyCodePath(ref.path);
- // Forward: markdown guide → code page (this guide documents that code)
- try {
- await tx.transaction(savepoint => savepoint.addLink(
- slug, codeSlug,
- ref.line ? `cited at ${ref.path}:${ref.line}` : ref.path,
- 'documents', 'markdown', slug, 'compiled_truth',
- linkOpts,
- ));
- } catch { /* code page not yet imported — reconcile-links will catch it */ }
- // Reverse: code page → markdown guide (this code is documented by the guide)
- try {
- await tx.transaction(savepoint => savepoint.addLink(
- codeSlug, slug,
- ref.path, 'documented_by', 'markdown', slug, 'compiled_truth',
- linkOpts,
- ));
- } catch { /* same reason — silent skip */ }
+ // source, code in another) are skipped as missing — never the pre-fix
+ // cross-product fan-out, which silently wired edges to whichever
+ // same-slug page Postgres returned first across sources.
+ if (codeRefs.length) {
+ await tx.transaction(savepoint => addCodeReferenceLinks(savepoint, slug, sourceId || 'default',
+ codeRefs.map(ref => ({ codeSlug: slugifyCodePath(ref.path), path: ref.path, line: ref.line })))).catch(() => undefined);
}
if (!opts.coordinated) await verifyPageReadable(tx, slug, hash, sourceId, 'importFromContent');
await opts.beforeCommit?.(tx, slug);
diff --git a/src/core/page-body/streamed-import.ts b/src/core/page-body/streamed-import.ts
index e381830bf5..1904b6dccb 100644
--- a/src/core/page-body/streamed-import.ts
+++ b/src/core/page-body/streamed-import.ts
@@ -65,6 +65,7 @@ import { suffixedFrontmatterSlugHold } from '../persistence/suffixed-slug.ts';
import { logSlugFallback } from '../audit-slug-fallback.ts';
import { extractCodeRefs } from '../link-extraction.ts';
import { hasMalformedPathSegment, slugifyCodePath, slugifyPath } from '../sync.ts';
+import { addCodeReferenceLinks } from '../engine-sql/links.ts';
import { isEmbedSkipped } from '../embed-skip.ts';
import { sanitizeText } from '../batch-rows.ts';
import { applySegmentedBody, sealSegmentedPage, segmentedLivePage } from '../persistence/segmented-apply.ts';
@@ -326,7 +327,6 @@ async function importScanned(engine: BrainEngine, input: { file: FileHandle; bom
const meta = { type: parsed.type, title: parsed.title, frontmatter: parsed.frontmatter as JsonObject, page_kind: 'markdown' as const,
effective_date: effectiveDate, effective_date_source: effectiveDateSource, import_filename: filename, source_path: relativePath,
source_kind: null, source_uri: fileOriginUri(existing?.source_uri, sourceRoot, relativePath), ingested_via: null };
- const linkOpts = { fromSourceId: sourceId, toSourceId: sourceId, originSourceId: sourceId };
const refs = prepared.body.body_flags.has_protected ? [] : [...codeRefs.refs.values()];
const apply = async (tx: BrainEngine, preimage?: PageSnapshot | null) => {
if (existing) await tx.createVersion(slug, preimage ? { sourceId, preimage } : { sourceId });
@@ -337,10 +337,9 @@ async function importScanned(engine: BrainEngine, input: { file: FileHandle; bom
await addPageTags(tx, result.pageId, parsed.tags, 'frontmatter');
await writePageAliases(tx, slug, sourceId, { ...parsed, compiled_truth: '', timeline: '' }, opts.activePack, mentionPolicy);
if (result.complete) await sealSegmentedPage(tx, result.pageId);
- for (const ref of refs) {
- const codeSlug = slugifyCodePath(ref.path);
- await tx.transaction(savepoint => savepoint.addLink(slug, codeSlug, ref.line ? `cited at ${ref.path}:${ref.line}` : ref.path, 'documents', 'markdown', slug, 'compiled_truth', linkOpts)).catch(() => undefined);
- await tx.transaction(savepoint => savepoint.addLink(codeSlug, slug, ref.path, 'documented_by', 'markdown', slug, 'compiled_truth', linkOpts)).catch(() => undefined);
+ if (refs.length) {
+ await tx.transaction(savepoint => addCodeReferenceLinks(savepoint, slug, sourceId,
+ refs.map(ref => ({ codeSlug: slugifyCodePath(ref.path), path: ref.path, line: ref.line })))).catch(() => undefined);
}
const { verifyPageReadable } = await import('../import-file.ts');
await verifyPageReadable(tx, slug, hash, sourceId, 'importStreamedMarkdownFile');
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 4289bd0c2c..fe7a20db84 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -26,12 +26,13 @@ import { withFilesystemPublication } from './filesystem-guard.ts';
import { mayReprepare } from './semantic.ts';
import { tryAcquirePublicationCapacity } from './pool-capacity.ts';
import { queuePublicationEffects } from './effect-journal.ts';
+import { timePublicationStep } from './publication-timing.ts';
import type { GitCommitNote } from './effect-model.ts';
import { authorizePageVisibility } from './page-visibility.ts';
import { withNoRepoWriteThroughWarning } from '../write-through.ts';
import { assertUnboundPublication, classifyUnboundPage, unboundWriteWarning } from './unbound-source.ts';
import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, recoveryStagingFile, upgradeRecoveryStaging } from './staging.ts';
-import { bindPublicationTimeouts, publicationTransaction } from './publication-deadline.ts';
+import { declarePublication, publicationTransaction } from './publication-deadline.ts';
import { assertMutationProtocol, assertSharedSkillPersistence, declareDurablePersistence, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import { assertBundleRecoveryBinding, bundleFileHash, prepareBundleRecovery, publishStagedBundleFile, stageBundleFile, type MutationFile } from './bundle-files.ts';
import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
@@ -364,8 +365,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
await hooks.boundary?.('prepared', row);
}
const done = await publicationTransaction(engine, async tx => {
- await bindPublicationTimeouts(tx);
- await declareDurablePersistence(tx);
+ await declarePublication(tx);
const liveBinding = await guardOwnership(tx, row, hostId);
if (prepared.sourceExclusive && !prepared.exclusiveSources?.length) await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR UPDATE', [row.source_id]);
if (prepared.exclusiveSources?.length) await lockCoreSources(tx, prepared.sourceExclusive ? [row.source_id, ...prepared.exclusiveSources] : prepared.exclusiveSources);
@@ -425,7 +425,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
}
prepared.postimage = undefined;
// W1 finalization contract (docs/designs/BELIEF_LEDGER.md 5.1): the ledger append is the last canonical write before the receipt.
- const apply = () => prepared.apply(tx, snapshot);
+ const apply = () => timePublicationStep('apply', row.slug, () => prepared.apply(tx, snapshot));
const outcome = await withCoordinatedWrite(tx, [row.source_id], skill ? apply
: () => withBeliefBatch(tx, publicationBeliefOptions(row, prepared.additionalPageKeys, beliefReport), apply), publicationAttribution(row, prepared.trust));
if (!skill) await classifyUnboundPage(tx, row);
@@ -433,7 +433,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
const final = skill ? null : await publicationPostimage(tx, row, prepared);
decoratePublicationOutcome(row, prepared, outcome, final, files.length, skill);
await recordPublicationFenceTrend(tx, row, outcome);
- await queuePublicationEffects(tx, row, final, outcome, prepared);
+ await timePublicationStep('effects', row.slug, () => queuePublicationEffects(tx, row, final, outcome, prepared));
await hooks.boundary?.('before_commit', row);
const committed = await completeWrite(tx, current, 'committed', outcome, undefined, current);
transactionBodyCompleted = true;
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index eb7a615b31..dbf62f211d 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -50,9 +50,9 @@ import { setMemberAttribution, withCoordinatedWrite } from './context.ts';
import { publicationAttribution } from './attribution.ts';
import { tryAcquirePublicationCapacity } from './pool-capacity.ts';
import { queuePublicationEffects, queuesMentionLinks, reconcileFinishedBatch } from './effect-journal.ts';
+import { timePublicationStep } from './publication-timing.ts';
import { assertUnboundPublication, classifyUnboundPage } from './unbound-source.ts';
-import { declareDurablePersistence } from './protocol.ts';
-import { bindPublicationTimeouts, boundPublication, publicationLeaseMs, publicationTransaction, type PublicationBound } from './publication-deadline.ts';
+import { boundPublication, declarePublication, publicationLeaseMs, publicationTransaction, type PublicationBound } from './publication-deadline.ts';
import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';
import { authorizePageVisibility } from './page-visibility.ts';
import { withFilesystemPublication } from './filesystem-guard.ts';
@@ -285,8 +285,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
const keys = rows.flatMap((row, i) => [{ sourceId: row.source_id, slug: row.slug, incarnation: row.source_incarnation },
...(prepared[i]!.additionalPageKeys ?? []).map(key => key.sourceId === row.source_id ? { ...key, incarnation: row.source_incarnation } : key)]);
const ready = pipelined(tx, [
- () => bindPublicationTimeouts(opened),
- () => declareDurablePersistence(tx),
+ () => declarePublication(tx, opened),
() => guardOwnership(tx, head, hostId),
// A published file needs recovery even if this transaction rolls back; claims are verified first.
() => members.length ? tx.executeRaw(`UPDATE persistence_requests r SET publication_started=true FROM unnest($1::uuid[],$2::uuid[]) AS t(id,token)
@@ -297,7 +296,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
() => prepared.some(member => member.file && !member.noop) ? tx.executeRaw(HOST_BINDING_SQL, [head.worktree_id]) : Promise.resolve([]),
...storedAuthorizationReads(tx, rows, true),
]).then(results => {
- const [, , live, started, readOnly] = results as [unknown, unknown, Awaited<ReturnType<typeof guardOwnership>>, unknown[], boolean];
+ const [, live, started, readOnly] = results as [unknown, Awaited<ReturnType<typeof guardOwnership>>, unknown[], boolean];
if (String(live?.owner_epoch) !== String(binding.owner_epoch)) throw new OperationError('owner_unavailable', 'Owner epoch changed before publication.', 'Inspect the source owner with gbrain sources writer status; do not claim or transfer the source to push this write.');
if (started.length !== members.length) throw new OperationError('write_claim_lost', 'Execution claim changed before publication.', 'Another worker holds the request; inspect it rather than resubmitting.');
// A file target prepared before the source became a read-only mirror is never published (as in publishMutation, noop included).
@@ -350,14 +349,15 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
if (attribute) await setMemberAttribution(tx, publicationAttribution(row, member.trust));
}
member.postimage = undefined;
- const outcome = await withBeliefBatch(tx, publicationBeliefOptions(row, member.additionalPageKeys, beliefReport), () => member.apply(tx, snapshot));
+ const outcome = await withBeliefBatch(tx, publicationBeliefOptions(row, member.additionalPageKeys, beliefReport),
+ () => timePublicationStep('apply', row.slug, () => member.apply(tx, snapshot)));
await classifyUnboundPage(tx, row);
if (member.databaseOnlyReason === 'mirror_read_only') await classifyMirrorPage(tx, row);
const final = await publicationPostimage(tx, row, member);
decoratePublicationOutcome(row, member, outcome, final, file ? 1 : 0, false);
effects = async () => {
await recordPublicationFenceTrend(tx, row, outcome);
- await queuePublicationEffects(tx, row, final, outcome, member, singleWrite(row) ? {} : { deferBatchReconcile: true });
+ await timePublicationStep('effects', row.slug, () => queuePublicationEffects(tx, row, final, outcome, member, singleWrite(row) ? {} : { deferBatchReconcile: true }));
};
outcomes.push(outcome);
} catch (error) { throw tag(error, i); }
diff --git a/src/core/persistence/protocol.ts b/src/core/persistence/protocol.ts
index 4280a20e32..25bc855184 100644
--- a/src/core/persistence/protocol.ts
+++ b/src/core/persistence/protocol.ts
@@ -32,10 +32,15 @@ export async function declarePersistenceProtocol(tx: SqlEngine): Promise<void> {
* under that lock timeout. Later `declarePersistenceProtocol` calls on the
* same transaction engine are free.
*/
-/** Returns the brain id read under that lock (null when the row is missing). */
-export async function declareDurablePersistence(tx: SqlEngine, lockTimeout = '1s', statementTimeout = '5s'): Promise<string | null> {
- const [row] = await tx.executeRaw<{ brain: string | null }>(`SELECT set_config('gbrain.persistence_protocol','2',true),set_config('synchronous_commit','on',true),
- set_config('lock_timeout',$1,true),set_config('statement_timeout',$2,true),${BRAIN_SHARE}`, [lockTimeout, statementTimeout]);
+/**
+ * Returns the brain id read under that lock (null when the row is missing). `idleInTransaction` also sets a
+ * transaction-local idle bound in the same statement, first (a publication's, publication-deadline.ts).
+ */
+export async function declareDurablePersistence(tx: SqlEngine, lockTimeout = '1s', statementTimeout = '5s', idleInTransaction?: string): Promise<string | null> {
+ const idle = idleInTransaction === undefined ? '' : "set_config('idle_in_transaction_session_timeout',$3,true),";
+ const [row] = await tx.executeRaw<{ brain: string | null }>(`SELECT ${idle}set_config('gbrain.persistence_protocol','2',true),set_config('synchronous_commit','on',true),
+ set_config('lock_timeout',$1,true),set_config('statement_timeout',$2,true),${BRAIN_SHARE}`,
+ idleInTransaction === undefined ? [lockTimeout, statementTimeout] : [lockTimeout, statementTimeout, idleInTransaction]);
if ((tx as { _pageTransaction?: boolean })._pageTransaction === true) declared.add(tx);
return row?.brain ?? null;
}
diff --git a/src/core/persistence/publication-deadline.ts b/src/core/persistence/publication-deadline.ts
index 420ef6eb0e..d7e77a101d 100644
--- a/src/core/persistence/publication-deadline.ts
+++ b/src/core/persistence/publication-deadline.ts
@@ -21,6 +21,7 @@
import { AsyncLocalStorage } from 'node:async_hooks';
import type { BrainEngine } from '../engine.ts';
import { gucMilliseconds, resolveSessionTimeouts } from '../db.ts';
+import { declareDurablePersistence } from './protocol.ts';
export const PUBLICATION_CEILING_KEY = 'persistence.publication_ceiling_ms';
/** `persistence.publication_ceiling_ms`' default (60000 to 3600000 accepted). */
@@ -65,6 +66,14 @@ export async function bindPublicationTimeouts(tx: BrainEngine): Promise<void> {
await tx.executeRaw("SELECT set_config('idle_in_transaction_session_timeout',$1,true)", [`${publicationIdleTimeoutMs()}ms`]);
}
+/**
+ * #6712 L6: the publication's opening statement: the idle bound above (Postgres only, for the same reason) and
+ * `declareDurablePersistence` in one round trip. A refused SET fails the publication's transaction as above.
+ */
+export async function declarePublication(tx: BrainEngine, bound: Pick<BrainEngine, 'kind'> = tx): Promise<string | null> {
+ return declareDurablePersistence(tx, undefined, undefined, bound.kind === 'postgres' ? `${publicationIdleTimeoutMs()}ms` : undefined);
+}
+
/**
* `engine.transaction`, passing the current publication's signal on as `{ signal }`. An aborted transaction rejects
* while its body may still be parked, so a rejection waits for the body to settle first: nothing (recovery included)
diff --git a/src/core/persistence/publication-timing.ts b/src/core/persistence/publication-timing.ts
new file mode 100644
index 0000000000..4aaa4fb614
--- /dev/null
+++ b/src/core/persistence/publication-timing.ts
@@ -0,0 +1,26 @@
+/**
+ * #6712 L6: how long a publication transaction spends in each member's
+ * `apply` (the page and its projections) and in queueing its effects, the two
+ * steps a large page's publish time goes to. Totals are process-local and cost
+ * no statement; with `GBRAIN_SYNC_TRACE` set (the sync's opt-in hang-triage
+ * trace) each step also prints one stderr line naming the page, so nothing is
+ * logged by default.
+ */
+export type PublicationStep = 'apply' | 'effects';
+
+const totals: Record<PublicationStep, { ms: number; count: number }> = { apply: { ms: 0, count: 0 }, effects: { ms: 0, count: 0 } };
+
+export async function timePublicationStep<T>(step: PublicationStep, slug: string, run: () => Promise<T>): Promise<T> {
+ const started = performance.now();
+ try { return await run(); } finally {
+ const ms = performance.now() - started;
+ totals[step].ms += ms;
+ totals[step].count++;
+ if (process.env.GBRAIN_SYNC_TRACE) process.stderr.write(`[sync] publish ${step} ${slug}: ${Math.round(ms)}ms\n`);
+ }
+}
+
+/** Totals since process start: milliseconds and steps timed, per step. */
+export function publicationStepTotals(): Record<PublicationStep, { ms: number; count: number }> {
+ return { apply: { ...totals.apply }, effects: { ...totals.effects } };
+}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 4719e332ef..d687317f8b 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -2185,23 +2185,22 @@ export class PostgresEngine implements BrainEngine {
const formatted = rows?.[0]?.formatted ?? null;
// halfvec match first — halfvec contains "vec" so a /vector/i
// regex would shadow it. See readFactsEmbeddingDim's identical
- // ordering note.
- if (formatted && /halfvec\(\d+\)/i.test(formatted)) {
- this._factsEmbeddingCastSuffix = '::halfvec';
- } else {
- // Default to '::vector' (the pre-v0.41.15 behavior). On a brain
- // without the facts.embedding column yet (pre-v40), the cast
- // suffix is irrelevant — the INSERT would fail elsewhere
- // anyway. Caching the default still saves the SELECT on
- // subsequent inserts.
- this._factsEmbeddingCastSuffix = '::vector';
- }
+ // ordering note. Otherwise '::vector' (the pre-v0.41.15 behavior);
+ // on a brain without the facts.embedding column yet (pre-v40) the
+ // INSERT would fail elsewhere anyway.
+ const suffix = formatted && /halfvec\(\d+\)/i.test(formatted) ? '::halfvec' : '::vector';
+ // #6712 L6: a transaction engine is an Object.create clone of the engine it runs on, so a probe answered
+ // inside a transaction is cached on that root engine: one probe per process, not one per publication.
+ let root: PostgresEngine = this;
+ while (Object.getPrototypeOf(root) instanceof PostgresEngine) root = Object.getPrototypeOf(root) as PostgresEngine;
+ root._factsEmbeddingCastSuffix = suffix;
+ return suffix;
} catch {
// Probe failed — fall back to '::vector' default. Cache so we
// don't re-probe on every insert.
this._factsEmbeddingCastSuffix = '::vector';
+ return '::vector';
}
- return this._factsEmbeddingCastSuffix;
}
async insertFact(
diff --git a/test/e2e/engine-sql-links-code-references-postgres.test.ts b/test/e2e/engine-sql-links-code-references-postgres.test.ts
new file mode 100644
index 0000000000..2025f8fd5b
--- /dev/null
+++ b/test/e2e/engine-sql-links-code-references-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../engine-sql-links-code-references.test.ts'));
diff --git a/test/e2e/facts-embedding-cast-probe-postgres.test.ts b/test/e2e/facts-embedding-cast-probe-postgres.test.ts
new file mode 100644
index 0000000000..70ba20cf3d
--- /dev/null
+++ b/test/e2e/facts-embedding-cast-probe-postgres.test.ts
@@ -0,0 +1,43 @@
+/**
+ * #6712 PR 3 (L6): the facts.embedding cast probe runs once per process, not
+ * once per transaction.
+ *
+ * Protects: a fact insert inside a transaction caches the probed cast suffix on
+ * the engine the transaction runs on, so the next publication transaction
+ * skips the pg_attribute probe (one round trip per page publish).
+ * Fails when: the suffix is cached only on the transaction's clone and lost
+ * when the transaction ends.
+ * Seams: PostgresEngine.transaction (an Object.create clone of the engine).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+
+const databaseUrl = process.env.DATABASE_URL;
+const castSuffix = (engine: PostgresEngine) => (engine as unknown as { _factsEmbeddingCastSuffix: string | null })._factsEmbeddingCastSuffix;
+
+describe.skipIf(!databaseUrl)('facts embedding cast probe (postgres)', () => {
+ let engine: PostgresEngine;
+ beforeAll(async () => {
+ assertSafeE2eDatabaseUrl(databaseUrl!);
+ engine = new PostgresEngine();
+ await engine.connect({ database_url: databaseUrl! });
+ await engine.initSchema();
+ await engine.putPage('notes/cast-probe-example', { type: 'note', title: 'Cast probe example', compiled_truth: 'Body.', timeline: '' }, { sourceId: 'default' });
+ });
+ afterAll(async () => {
+ await engine.executeRaw("DELETE FROM facts WHERE source_markdown_slug='notes/cast-probe-example'");
+ await engine.executeRaw("DELETE FROM pages WHERE slug='notes/cast-probe-example' AND source_id='default'");
+ await engine.disconnect();
+ });
+
+ test('a fact insert inside a transaction leaves the probed suffix on the engine for the next transaction', async () => {
+ expect(castSuffix(engine)).toBeNull();
+ const row = (n: number) => ({ fact: `Example claim ${n}`, kind: 'fact' as const, entity_slug: 'notes/cast-probe-example', source: 'test', row_num: n, source_markdown_slug: 'notes/cast-probe-example' });
+ await engine.transaction(tx => tx.insertFacts([row(1)], { source_id: 'default' }));
+ expect(['::vector', '::halfvec']).toContain(castSuffix(engine)!);
+ await engine.transaction(tx => tx.insertFacts([row(2)], { source_id: 'default' }));
+ const [stored] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE source_markdown_slug='notes/cast-probe-example' AND expired_at IS NULL");
+ expect(stored!.n).toBe(2);
+ });
+});
diff --git a/test/e2e/managed-import-statement-budget.test.ts b/test/e2e/managed-import-statement-budget.test.ts
new file mode 100644
index 0000000000..92af214879
--- /dev/null
+++ b/test/e2e/managed-import-statement-budget.test.ts
@@ -0,0 +1,104 @@
+/**
+ * #6712 PR 3 (L6): the Postgres twin of test/managed-import-statement-budget.test.ts.
+ * One whole managed import of a YC-shaped page at 0.5x, 1x and 2x, counted at
+ * the socket by the env-gated wire trace (src/core/sql-trace.ts): `execute` and
+ * `simple` records are statements; `describe` records (the extra round trip a
+ * statement pays the first time a connection sees it) are reported, not
+ * budgeted. On Postgres the page publishes through publishGroup (a group of one
+ * on the consumer's lane), with its effects queued in the same transaction.
+ *
+ * Protects: every statement in the page's publication transaction runs the same
+ * number of times at every size except the chunked set-based inserts (at most
+ * one per 500 rows); the transaction stays within its budget; no statement text
+ * runs per row or per code reference anywhere in the sync.
+ * Fails when: a per-row statement enters the import, a chunked insert loses its
+ * batching, or the publication transaction grows past its budget.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { hasDatabase } from './helpers.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { readSqlTrace, type StatementRecord } from '../helpers/statement-counter.ts';
+import { byText, chunkOf, CHUNKED, PAGE_SLUG, prepareManagedImport, publicationOf } from '../helpers/managed-import-budget.ts';
+import type { YcShapedPage } from '../helpers/yc-shaped-page.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+/** About 10% over the measured publication transaction at 1x (#6712 L6 measured 67 on Postgres; 317 before code references were batched). */
+const PUBLICATION_BUDGET = 74;
+const PER_ROW_CEILING = 40;
+const SIZES = [0.5, 1, 2] as const;
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-import-budget-pg-'));
+afterAll(() => rmSync(home, { recursive: true, force: true }));
+
+type Measured = { page: YcShapedPage; records: StatementRecord[]; publication: StatementRecord[] };
+const runs = new Map<number, Promise<Measured>>();
+function measured(scale: number): Promise<Measured> {
+ const cached = runs.get(scale);
+ if (cached) return cached;
+ const run = measure(scale);
+ runs.set(scale, run);
+ return run;
+}
+async function measure(scale: number): Promise<Measured> {
+ // One file for every size: the trace buffers process-wide and flushes into the first file it was given.
+ const trace = join(home, 'trace.jsonl');
+ return withEnv({ GBRAIN_SQL_TRACE: trace, GBRAIN_SQL_TRACE_LABEL: 'import-budget', GBRAIN_HOME: join(home, `home-${scale}`) }, async () => {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!, 'instance', 6);
+ const sourceId = `budget-${String(scale).replace('.', '-')}`;
+ try {
+ const { page, run } = await prepareManagedImport(pg.engine, home, sourceId, scale);
+ const started = performance.timeOrigin + performance.now();
+ const result = await run();
+ const ended = performance.timeOrigin + performance.now();
+ expect(result.status).toBe('synced');
+ expect((await pg.engine.getPage(PAGE_SLUG, { sourceId }))?.slug).toBe(PAGE_SLUG);
+ await disposePersistenceConsumer(pg.engine);
+ // The trace flushes every second and at exit; wait until the publication's commit has landed.
+ for (let i = 0; ; i++) {
+ const records = readSqlTrace(trace).filter(record => record.t >= started && record.t <= ended);
+ try { return { page, records, publication: publicationOf(records) }; }
+ catch (error) { if (i >= 50) throw error; }
+ await Bun.sleep(100);
+ }
+ } finally {
+ await disposePersistenceConsumer(pg.engine);
+ await pg.close();
+ }
+ });
+}
+
+const d = hasDatabase() ? describe : describe.skip;
+d('managed import statement budget (Postgres)', () => {
+ test('the publication transaction runs every statement the same number of times at every size, except bounded chunks', async () => {
+ const [small, large] = [await measured(0.5), await measured(2)];
+ const smallCounts = byText(small.publication), largeCounts = byText(large.publication);
+ for (const text of new Set([...smallCounts.keys(), ...largeCounts.keys()])) {
+ const chunk = chunkOf(text);
+ if (chunk) {
+ for (const run of [small, large]) expect(byText(run.publication).get(text) ?? 0).toBeLessThanOrEqual(Math.ceil(chunk.rows(run.page) / chunk.rowsPerChunk));
+ continue;
+ }
+ expect({ text, count: largeCounts.get(text) ?? 0 }).toEqual({ text, count: smallCounts.get(text) ?? 0 });
+ }
+ for (const chunk of CHUNKED) expect([...largeCounts.keys()].some(text => chunk.pattern.test(text))).toBe(true);
+ }, 300_000);
+
+ test('the publication transaction stays within its budget at 1x', async () => {
+ const { publication } = await measured(1);
+ const statements = publication.filter(record => record.kind === 'execute' || record.kind === 'simple');
+ expect(statements.length).toBeLessThanOrEqual(PUBLICATION_BUDGET);
+ }, 300_000);
+
+ test('no statement runs per row or per code reference anywhere in the import', async () => {
+ for (const scale of SIZES) {
+ const { records, page } = await measured(scale);
+ expect(page.codeRefs.length * 2).toBeGreaterThan(PER_ROW_CEILING);
+ const hot = [...byText(records)].filter(([text, count]) => !chunkOf(text) && count >= PER_ROW_CEILING);
+ expect(hot).toEqual([]);
+ }
+ }, 300_000);
+});
diff --git a/test/e2e/sync-status-statement-budget-postgres.test.ts b/test/e2e/sync-status-statement-budget-postgres.test.ts
new file mode 100644
index 0000000000..ca4b12e495
--- /dev/null
+++ b/test/e2e/sync-status-statement-budget-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../sync-status-statement-budget.test.ts'));
diff --git a/test/engine-sql-links-code-references.test.ts b/test/engine-sql-links-code-references.test.ts
new file mode 100644
index 0000000000..05b6bc3d6a
--- /dev/null
+++ b/test/engine-sql-links-code-references.test.ts
@@ -0,0 +1,140 @@
+/**
+ * #6712 PR 3 (L6): `addCodeReferenceLinks` writes the doc↔impl edges of every
+ * code path a page cites in one statement, with the semantics of the
+ * per-reference addLink pair it replaced.
+ *
+ * Protects: the edges equal what sequential addLink pairs wrote for the same
+ * references (the oracle); endpoints resolve in the page's source only (a
+ * same-slug page in another source is never linked); a missing code page skips
+ * only its own edges; a re-import updates context and origin_field in place; a
+ * repeated edge keeps its last occurrence without a "cannot affect row a second
+ * time" error; on Postgres a concurrent delete of a linked endpoint waits for
+ * the writing transaction (the endpoints are locked).
+ * Fails when: endpoint resolution drops the source qualifier, a missing endpoint
+ * fails the batch, a conflict inserts a duplicate or leaves the old context, or
+ * duplicates reach one ON CONFLICT DO UPDATE.
+ * Seams: none; PGLite always, Postgres through
+ * test/e2e/engine-sql-links-code-references-postgres.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../src/core/postgres-engine.ts';
+import { addCodeReferenceLinks, type CodeReference } from '../src/core/engine-sql/links.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+const SOURCE = 'coderef-src';
+const OTHER = 'coderef-other';
+const DOC = 'guides/widget-guide';
+
+async function seed(engine: BrainEngine, codeSlugs: string[], opts: { source?: string; doc?: string } = {}) {
+ const source = opts.source ?? SOURCE;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT DO NOTHING', [source]);
+ await engine.putPage(opts.doc ?? DOC, { type: 'guide', title: 'Widget guide', compiled_truth: 'Guide body.' }, { sourceId: source });
+ for (const slug of codeSlugs) await engine.putPage(slug, { type: 'code', title: slug, compiled_truth: 'code' }, { sourceId: source });
+}
+
+type Edge = { from: string; to: string; type: string; context: string; source: string; origin: string | null; field: string | null };
+async function edges(engine: BrainEngine, source: string): Promise<Edge[]> {
+ return engine.executeRaw<Edge>(`SELECT f.slug AS "from", t.slug AS "to", l.link_type AS type, l.context, l.link_source AS source, o.slug AS origin, l.origin_field AS field
+ FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id LEFT JOIN pages o ON o.id=l.origin_page_id
+ WHERE f.source_id=$1 ORDER BY 1,2,3`, [source]);
+}
+
+/** What the import paths wrote before #6712 L6: one addLink pair per reference, each swallowing its own failure. */
+async function sequentialPairs(engine: BrainEngine, slug: string, source: string, refs: CodeReference[]) {
+ const opts = { fromSourceId: source, toSourceId: source, originSourceId: source };
+ for (const ref of refs) {
+ await engine.addLink(slug, ref.codeSlug, ref.line ? `cited at ${ref.path}:${ref.line}` : ref.path, 'documents', 'markdown', slug, 'compiled_truth', opts).catch(() => undefined);
+ await engine.addLink(ref.codeSlug, slug, ref.path, 'documented_by', 'markdown', slug, 'compiled_truth', opts).catch(() => undefined);
+ }
+}
+
+const REFS: CodeReference[] = [
+ { codeSlug: 'src-widgets-a-ts', path: 'src/widgets/a.ts', line: 12 },
+ { codeSlug: 'src-widgets-missing-ts', path: 'src/widgets/missing.ts', line: 3 },
+ { codeSlug: 'src-widgets-b-ts', path: 'src/widgets/b.ts' },
+ { codeSlug: 'src-widgets-a-ts', path: 'src/Widgets/a.ts', line: 40 },
+];
+
+for (const backend of testBackends()) {
+ describe(`addCodeReferenceLinks (${backend})`, () => {
+ let engine: BrainEngine;
+ beforeAll(async () => {
+ if (backend === 'pglite') { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engine = lite; }
+ else { const pg = new PostgresEngine(); await pg.connect({ database_url: requirePostgresTestDatabase(), poolSize: 4 }); await pg.initSchema(); engine = pg; }
+ }, 120_000);
+ afterAll(async () => {
+ if (backend === 'postgres') for (const id of [SOURCE, OTHER, `${SOURCE}-oracle`]) await engine.executeRaw('DELETE FROM sources WHERE id=$1', [id]);
+ await engine.disconnect();
+ });
+
+ test('writes exactly the edges sequential addLink pairs wrote: missing endpoints skipped alone, a repeated edge keeps its last context', async () => {
+ const oracle = `${SOURCE}-oracle`;
+ await seed(engine, ['src-widgets-a-ts', 'src-widgets-b-ts']);
+ await seed(engine, ['src-widgets-a-ts', 'src-widgets-b-ts'], { source: oracle });
+ await sequentialPairs(engine, DOC, oracle, REFS);
+ const written = await addCodeReferenceLinks(engine, DOC, SOURCE, REFS);
+ const got = await edges(engine, SOURCE);
+ expect(got).toEqual(await edges(engine, oracle));
+ expect(got).toEqual([
+ { from: DOC, to: 'src-widgets-a-ts', type: 'documents', context: 'cited at src/Widgets/a.ts:40', source: 'markdown', origin: DOC, field: 'compiled_truth' },
+ { from: DOC, to: 'src-widgets-b-ts', type: 'documents', context: 'src/widgets/b.ts', source: 'markdown', origin: DOC, field: 'compiled_truth' },
+ { from: 'src-widgets-a-ts', to: DOC, type: 'documented_by', context: 'src/Widgets/a.ts', source: 'markdown', origin: DOC, field: 'compiled_truth' },
+ { from: 'src-widgets-b-ts', to: DOC, type: 'documented_by', context: 'src/widgets/b.ts', source: 'markdown', origin: DOC, field: 'compiled_truth' },
+ ]);
+ expect(written).toBe(4);
+ });
+
+ test('endpoints resolve in the page source only: a same-slug code page in another source is never linked', async () => {
+ await seed(engine, ['src-widgets-c-ts'], { source: OTHER, doc: 'guides/other-guide' });
+ await seed(engine, []);
+ expect(await addCodeReferenceLinks(engine, DOC, SOURCE, [{ codeSlug: 'src-widgets-c-ts', path: 'src/widgets/c.ts' }])).toBe(0);
+ const crossing = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n 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 <> t.source_id AND $1 IN (f.source_id, t.source_id)`, [OTHER]);
+ expect(crossing[0]!.n).toBe(0);
+ });
+
+ test('a re-import updates context and origin_field of the existing edges in place', async () => {
+ await seed(engine, ['src-widgets-a-ts']);
+ await engine.executeRaw(`UPDATE links SET origin_field='frontmatter' FROM pages f WHERE f.id=links.from_page_id AND f.source_id=$1`, [SOURCE]);
+ const before = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM links');
+ await addCodeReferenceLinks(engine, DOC, SOURCE, [{ codeSlug: 'src-widgets-a-ts', path: 'src/widgets/a.ts', line: 99 }]);
+ const after = await edges(engine, SOURCE);
+ expect(after.filter(e => e.from === DOC && e.to === 'src-widgets-a-ts')).toEqual([
+ { from: DOC, to: 'src-widgets-a-ts', type: 'documents', context: 'cited at src/widgets/a.ts:99', source: 'markdown', origin: DOC, field: 'compiled_truth' }]);
+ expect(after.filter(e => e.from === 'src-widgets-a-ts')).toEqual([
+ { from: 'src-widgets-a-ts', to: DOC, type: 'documented_by', context: 'src/widgets/a.ts', source: 'markdown', origin: DOC, field: 'compiled_truth' }]);
+ expect(await engine.executeRaw('SELECT count(*)::int AS n FROM links')).toEqual(before);
+ });
+
+ test('no references write nothing and send no statement', async () => {
+ const calls: string[] = [];
+ const counting = { executeRaw: <R,>(sql: string, params?: unknown[]) => { calls.push(sql); return engine.executeRaw<R>(sql, params); } };
+ expect(await addCodeReferenceLinks(counting, DOC, SOURCE, [])).toBe(0);
+ expect(calls).toEqual([]);
+ expect(await addCodeReferenceLinks(counting, DOC, SOURCE, REFS)).toBeGreaterThan(0);
+ expect(calls).toHaveLength(1);
+ });
+
+ if (backend === 'postgres') test('a concurrent delete of a linked endpoint waits for the writing transaction', async () => {
+ await seed(engine, ['src-widgets-d-ts']);
+ let release!: () => void;
+ const held = new Promise<void>(resolve => { release = resolve; });
+ let wrote!: () => void;
+ const written = new Promise<void>(resolve => { wrote = resolve; });
+ const writer = engine.transaction(async tx => {
+ await addCodeReferenceLinks(tx, DOC, SOURCE, [{ codeSlug: 'src-widgets-d-ts', path: 'src/widgets/d.ts' }]);
+ wrote();
+ await held;
+ });
+ await written;
+ try {
+ await expect(engine.transaction(async tx => {
+ await tx.executeRaw("SET LOCAL lock_timeout = '300ms'");
+ await tx.executeRaw('DELETE FROM pages WHERE source_id=$1 AND slug=$2', [SOURCE, 'src-widgets-d-ts']);
+ })).rejects.toMatchObject({ code: '55P03' });
+ } finally { release(); await writer; }
+ });
+ });
+}
diff --git a/test/fixtures/goldens/sql-text/chunks.json b/test/fixtures/goldens/sql-text/chunks.json
index d226b48336..14b774097b 100644
--- a/test/fixtures/goldens/sql-text/chunks.json
+++ b/test/fixtures/goldens/sql-text/chunks.json
@@ -822,8 +822,8 @@
{
"lane": "tx",
"params": [],
- "sql": "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns')",
- "textSha256": "0c97097b286eb3415cffbfa812bc301187d88bc7a5266678332b0f4c8c571371"
+ "sql": "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns', 'embedding_model')",
+ "textSha256": "52b14422ab398f9e070b5981b6726357ba3dff2ad574a15e7b5b7a2679c6d582"
},
{
"lane": "tx",
@@ -920,8 +920,8 @@
{
"lane": "tx",
"params": [],
- "sql": "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns')",
- "textSha256": "0c97097b286eb3415cffbfa812bc301187d88bc7a5266678332b0f4c8c571371"
+ "sql": "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns', 'embedding_model')",
+ "textSha256": "52b14422ab398f9e070b5981b6726357ba3dff2ad574a15e7b5b7a2679c6d582"
},
{
"lane": "tx",
@@ -1195,8 +1195,8 @@
{
"lane": "tx",
"params": [],
- "sql": "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns')",
- "textSha256": "0c97097b286eb3415cffbfa812bc301187d88bc7a5266678332b0f4c8c571371"
+ "sql": "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns', 'embedding_model')",
+ "textSha256": "52b14422ab398f9e070b5981b6726357ba3dff2ad574a15e7b5b7a2679c6d582"
},
{
"lane": "tx",
diff --git a/test/helpers/latency-proxy.ts b/test/helpers/latency-proxy.ts
new file mode 100644
index 0000000000..f79ce57b8d
--- /dev/null
+++ b/test/helpers/latency-proxy.ts
@@ -0,0 +1,54 @@
+/**
+ * A TCP proxy that adds a fixed round-trip latency to a Postgres (or PgBouncer)
+ * endpoint, for convergence and timing tests: every chunk is delayed by half
+ * the round trip in each direction, preserving order. `drop()` destroys every
+ * live connection at once, as a pooler restart looks to its clients.
+ */
+import { createConnection, createServer, type Server, type Socket } from 'node:net';
+
+/** A TCP proxy that delays every chunk by half the configured round trip in each direction, preserving order. */
+export class LatencyProxy {
+ private server: Server;
+ private sockets = new Set<Socket>();
+ port = 0;
+ constructor(private target: { host: string; port: number }, private oneWayMs: number) {
+ this.server = createServer(client => this.accept(client));
+ }
+ async listen(): Promise<void> {
+ await new Promise<void>(done => this.server.listen(0, '127.0.0.1', done));
+ const address = this.server.address();
+ if (!address || typeof address === 'string') throw new Error('latency proxy has no port');
+ this.port = address.port;
+ }
+ private delayed(from: Socket, to: Socket): void {
+ const queue: { at: number; chunk: Buffer }[] = [];
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const drain = () => {
+ timer = undefined;
+ const now = performance.now();
+ while (queue.length && queue[0].at <= now) { const { chunk } = queue.shift()!; if (!to.destroyed) to.write(chunk); }
+ if (queue.length) timer = setTimeout(drain, Math.max(0, queue[0].at - performance.now()));
+ };
+ from.on('data', (chunk: Buffer) => {
+ queue.push({ at: performance.now() + this.oneWayMs, chunk });
+ if (!timer) timer = setTimeout(drain, this.oneWayMs);
+ });
+ from.on('end', () => { const close = () => (queue.length ? setTimeout(close, this.oneWayMs) : to.end()); close(); });
+ }
+ private accept(client: Socket): void {
+ const upstream = createConnection(this.target);
+ for (const socket of [client, upstream]) {
+ this.sockets.add(socket);
+ socket.on('close', () => this.sockets.delete(socket));
+ socket.on('error', () => { client.destroy(); upstream.destroy(); });
+ }
+ this.delayed(client, upstream);
+ this.delayed(upstream, client);
+ }
+ /** Mode (f): every live connection through the pooler drops at once, as a pooler restart looks to its clients. */
+ drop(): number { const n = this.sockets.size; for (const socket of this.sockets) socket.destroy(); return n; }
+ async close(): Promise<void> {
+ for (const socket of this.sockets) socket.destroy();
+ await new Promise<void>(done => this.server.close(() => done()));
+ }
+}
diff --git a/test/helpers/managed-import-budget.ts b/test/helpers/managed-import-budget.ts
new file mode 100644
index 0000000000..cfad45c47b
--- /dev/null
+++ b/test/helpers/managed-import-budget.ts
@@ -0,0 +1,83 @@
+/**
+ * #6712 PR 3 (L6): one whole managed import of a YC-shaped page, counted.
+ *
+ * The fixture is a Git checkout bound to a managed source whose first sync
+ * imports the code pages half of the page's code references point at (the
+ * other half stay missing, as for a guide imported before its code); the
+ * measured sync then imports the page through preparation, the publication
+ * transaction and its effect queueing. The caller supplies the statement
+ * records of the measured sync (PGLite: `countPgliteStatements`; Postgres: the
+ * `GBRAIN_SQL_TRACE` file), and `publicationOf` picks out the page's
+ * publication transaction (begin..commit on one connection, the one that
+ * inserts the page).
+ */
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { performManagedSync } from '../../src/core/persistence/sync-run.ts';
+import { slugifyCodePath } from '../../src/core/sync.ts';
+import type { SyncResult } from '../../src/commands/sync.ts';
+import { ycCodePath, ycShapedPage, type YcShapedPage } from './yc-shaped-page.ts';
+import type { StatementRecord } from './statement-counter.ts';
+
+export const PAGE_SLUG = 'companies/acme-example';
+/** Statements whose count grows with the page's rows by design: bounded chunks of a set-based write. */
+export const CHUNKED: Array<{ name: string; pattern: RegExp; rowsPerChunk: number; rows: (page: YcShapedPage) => number }> = [
+ { name: 'timeline insert', pattern: /^INSERT INTO timeline_entries \(page_id,date,source,summary,detail\) SELECT/, rowsPerChunk: 500, rows: page => page.timeline },
+ { name: 'facts insert', pattern: /^INSERT INTO facts \(/, rowsPerChunk: 500, rows: page => page.facts },
+];
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };
+export const flat = (sql: string) => sql.replace(/\s+/g, ' ').trim();
+
+/** Builds the checkout and source, imports the code pages, and commits the page; returns the measured sync. */
+export async function prepareManagedImport(engine: BrainEngine, home: string, sourceId: string, scale: number): Promise<{ page: YcShapedPage; root: string; run: () => Promise<SyncResult> }> {
+ const root = join(home, sourceId);
+ mkdirSync(join(root, 'companies'), { recursive: true });
+ git(root, 'init', '-q');
+ const page = ycShapedPage(scale);
+ for (let i = 0; i < page.codeRefs.length; i += 2) {
+ writeFileSync(join(root, `${slugifyCodePath(ycCodePath(i))}.md`), `---\ntitle: Module ${i}\n---\nWidget module source notes.\n`);
+ }
+ commit(root, 'code pages');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const first = await performManagedSync(engine, { sourceId, noPull: true, noEmbed: true });
+ if (first.status !== 'first_sync') throw new Error(`code page import ended ${first.status}`);
+ writeFileSync(join(root, `${PAGE_SLUG}.md`), page.text);
+ commit(root, 'page');
+ return { page, root, run: () => performManagedSync(engine, { sourceId, noPull: true, noEmbed: true }) };
+}
+
+const isStatement = (record: StatementRecord) => record.kind === 'execute' || record.kind === 'simple';
+
+/** The transaction that inserted the page: its statements in order (begin and commit included). */
+export function publicationOf(records: StatementRecord[]): StatementRecord[] {
+ const open = new Map<number, StatementRecord[]>();
+ for (const record of [...records].sort((a, b) => a.t - b.t)) {
+ if (!isStatement(record)) continue;
+ const text = flat(record.sql).toLowerCase();
+ if (text === 'begin') { open.set(record.conn, [record]); continue; }
+ const group = open.get(record.conn);
+ if (!group) continue;
+ group.push(record);
+ if (text !== 'commit' && text !== 'rollback') continue;
+ open.delete(record.conn);
+ if (text === 'commit' && group.some(r => /^INSERT INTO pages \(/.test(flat(r.sql)))) return group;
+ }
+ throw new Error('no committed transaction inserted the page');
+}
+
+/** Statement counts by normalized text. */
+export function byText(records: StatementRecord[]): Map<string, number> {
+ const counts = new Map<string, number>();
+ for (const record of records) if (isStatement(record)) counts.set(flat(record.sql), (counts.get(flat(record.sql)) ?? 0) + 1);
+ return counts;
+}
+
+export const chunkOf = (sql: string) => CHUNKED.find(chunk => chunk.pattern.test(sql));
diff --git a/test/helpers/statement-counter.ts b/test/helpers/statement-counter.ts
new file mode 100644
index 0000000000..442b659912
--- /dev/null
+++ b/test/helpers/statement-counter.ts
@@ -0,0 +1,53 @@
+/**
+ * #6712 PR 3 (L6): the statement counter both engines' budget tests read.
+ *
+ * Postgres: the env-gated wire trace (`GBRAIN_SQL_TRACE`, src/core/sql-trace.ts)
+ * records every round trip at the socket; `readSqlTrace` loads it. PGLite has
+ * no socket, so `countPgliteStatements` wraps the datastore's
+ * `execProtocolRaw` (every PGLite query, named or unnamed, every simple query
+ * and the transaction's BEGIN and COMMIT go through it) and decodes the frontend messages the same way the wire
+ * trace does: an Execute or a simple Query is one statement, carrying the text
+ * its Parse named. Both produce the same `StatementRecord` shape, so one
+ * classifier serves both engines.
+ */
+import { readFileSync } from 'node:fs';
+import type { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+
+export interface StatementRecord { t: number; conn: number; kind: string; sql: string; ms?: number }
+
+/** Statement records of a `GBRAIN_SQL_TRACE` file (round trips: `execute`, `simple`, `describe`, `connect`). */
+export function readSqlTrace(file: string): StatementRecord[] {
+ let text = '';
+ try { text = readFileSync(file, 'utf8'); } catch { return []; }
+ return text.split('\n').filter(Boolean).map(line => JSON.parse(line) as StatementRecord);
+}
+
+function cstring(buf: Uint8Array, at: number): [string, number] {
+ let end = at;
+ while (end < buf.length && buf[end] !== 0) end++;
+ return [Buffer.from(buf.buffer, buf.byteOffset + at, end - at).toString('utf8'), end + 1];
+}
+
+/** Counts the statements one PGLite engine sends until `stop()`. */
+export function countPgliteStatements(engine: PGLiteEngine): { records: StatementRecord[]; stop(): StatementRecord[] } {
+ const db = engine.db as unknown as { execProtocolRaw: (message: Uint8Array, opts?: unknown) => Promise<unknown> };
+ const original = db.execProtocolRaw;
+ const prepared = new Map<string, string>();
+ const records: StatementRecord[] = [];
+ let text = '';
+ let t = 0;
+ db.execProtocolRaw = function (this: unknown, message: Uint8Array, opts?: unknown) {
+ for (let at = 0; at + 5 <= message.length;) {
+ const type = message[at]!;
+ const length = new DataView(message.buffer, message.byteOffset + at + 1, 4).getInt32(0);
+ const body = message.subarray(at + 5, at + 1 + length);
+ if (type === 0x50) { const [name, next] = cstring(body, 0); text = cstring(body, next)[0]; prepared.set(name, text); }
+ else if (type === 0x42) { const [, next] = cstring(body, 0); text = prepared.get(cstring(body, next)[0]) ?? text; }
+ else if (type === 0x45) records.push({ t: ++t, conn: 1, kind: 'execute', sql: text });
+ else if (type === 0x51) records.push({ t: ++t, conn: 1, kind: 'simple', sql: cstring(body, 0)[0] });
+ at += 1 + length;
+ }
+ return original.call(this, message, opts);
+ };
+ return { records, stop: () => { db.execProtocolRaw = original; return records; } };
+}
diff --git a/test/helpers/yc-shaped-page.ts b/test/helpers/yc-shaped-page.ts
new file mode 100644
index 0000000000..29bace3997
--- /dev/null
+++ b/test/helpers/yc-shaped-page.ts
@@ -0,0 +1,38 @@
+/**
+ * #6712 PR 3 (L6): a deterministic company page shaped like a large production
+ * page (a YC-style company profile): prose sections, a facts fence, a long
+ * timeline and code-path references. At scale 1 it is about 337 KB with 1,012
+ * facts, 4,100 timeline rows and 50 code references; every count scales
+ * linearly with `scale`. Names are generic placeholders.
+ */
+export interface YcShapedPage { text: string; facts: number; timeline: number; codeRefs: string[] }
+
+export const YC_SHAPED_BASE = { facts: 1012, timeline: 4100, codeRefs: 50 } as const;
+
+export const ycCodePath = (i: number) => `src/widgets/module-${String(i).padStart(3, '0')}.ts`;
+
+const REPEAT = 16;
+
+export function ycShapedPage(scale = 1, version = 'v1'): YcShapedPage {
+ const facts = Math.round(YC_SHAPED_BASE.facts * scale);
+ const timeline = Math.round(YC_SHAPED_BASE.timeline * scale);
+ const refs = Math.round(YC_SHAPED_BASE.codeRefs * scale);
+ const day = (n: number) => new Date(Date.UTC(2012, 0, 1) + n * 86_400_000).toISOString().slice(0, 10);
+ const codeRefs = Array.from({ length: refs }, (_, i) => ycCodePath(i));
+ const sections = Math.max(1, Math.round(24 * scale));
+ const paragraphs = Array.from({ length: sections }, (_, i) =>
+ `## Section ${i} (${version})\n\nAcme Example ${'operating detail about widget-co customers, revenue lines and hiring plans. '.repeat(REPEAT)}`);
+ const refLines = codeRefs.map((path, i) => `- Implementation note ${i}: see ${path}:${20 + i} for the widget pipeline.`);
+ const rows = Array.from({ length: facts }, (_, i) =>
+ `| ${i + 1} | Claim ${i + 1} about acme-example ${version} | fact | 0.9 | world | medium | ${day(i)} | | fixture | |`);
+ const bullets = Array.from({ length: timeline }, (_, i) => `- **${day(i)}** | Event ${i + 1} at acme-example ${version}`);
+ const text = [
+ '---', 'type: company', 'title: Acme Example', '---', '', '# Acme Example', '', ...paragraphs.flatMap(p => [p, '']),
+ '## Code', '', ...refLines, '',
+ '## Facts', '', '<!--- gbrain:facts:begin -->',
+ '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',
+ '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|',
+ ...rows, '<!--- gbrain:facts:end -->', '', '<!-- timeline -->', '', ...bullets, '',
+ ].join('\n');
+ return { text, facts, timeline, codeRefs };
+}
diff --git a/test/managed-import-statement-budget.test.ts b/test/managed-import-statement-budget.test.ts
new file mode 100644
index 0000000000..782ad2ab47
--- /dev/null
+++ b/test/managed-import-statement-budget.test.ts
@@ -0,0 +1,111 @@
+/**
+ * #6712 PR 3 (L6): the statement budget of one whole managed import of a
+ * YC-shaped page (about 337 KB at 1x: 1,012 facts, 4,100 timeline rows, 50
+ * code references) on PGLite, at 0.5x, 1x and 2x.
+ *
+ * Protects: the import writes tables and bounded chunks, never one statement
+ * per row. In the page's publication transaction (preparation's writes, the
+ * page, its projections and the queued effects) every statement runs the same
+ * number of times at every size except the chunked set-based inserts, which
+ * stay within one statement per 500 rows; the transaction stays within its
+ * budget; and across the whole sync no statement text runs per row (the code
+ * references used to cost one addLink per edge, 100 at 1x).
+ * Fails when: a per-row (or per-reference) statement enters the import, a
+ * chunked insert loses its batching, or the publication transaction grows
+ * past its budget.
+ * Seams: the PGLite statement counter (test/helpers/statement-counter.ts).
+ * Postgres twin: test/e2e/managed-import-statement-budget.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { publicationStepTotals } from '../src/core/persistence/publication-timing.ts';
+import { countPgliteStatements, type StatementRecord } from './helpers/statement-counter.ts';
+import { byText, chunkOf, CHUNKED, PAGE_SLUG, prepareManagedImport, publicationOf } from './helpers/managed-import-budget.ts';
+import type { YcShapedPage } from './helpers/yc-shaped-page.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+/** About 10% over the measured publication transaction at 1x (#6712 L6 measured 69 on PGLite; 416 before code references were batched). */
+const PUBLICATION_BUDGET = 76;
+/** No statement text may run this often in one import: far above any fixed statement, far below one per row or reference. */
+const PER_ROW_CEILING = 40;
+const SIZES = [0.5, 1, 2] as const;
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-import-budget-'));
+/** One brain per page size, so each measured import is the first sync of its page. */
+const engines = new Map<number, PGLiteEngine>();
+beforeAll(async () => {
+ for (const scale of SIZES) {
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ engines.set(scale, engine);
+ }
+});
+afterAll(async () => {
+ for (const engine of engines.values()) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ rmSync(home, { recursive: true, force: true });
+});
+
+type Measured = { page: YcShapedPage; records: StatementRecord[]; publication: StatementRecord[] };
+const runs = new Map<number, Promise<Measured>>();
+function measured(scale: number): Promise<Measured> {
+ const cached = runs.get(scale);
+ if (cached) return cached;
+ const run = measure(scale);
+ runs.set(scale, run);
+ return run;
+}
+async function measure(scale: number): Promise<Measured> {
+ return withEnv({ GBRAIN_HOME: join(home, `home-${scale}`) }, async () => {
+ const engine = engines.get(scale)!;
+ try {
+ const { page, run } = await prepareManagedImport(engine, home, `budget-${String(scale).replace('.', '-')}`, scale);
+ const counter = countPgliteStatements(engine);
+ const timed = publicationStepTotals();
+ let result;
+ try { result = await run(); } finally { counter.stop(); }
+ expect(result.status).toBe('synced');
+ // The publication timed its member's apply and effect queueing.
+ expect(publicationStepTotals().apply.count).toBeGreaterThan(timed.apply.count);
+ expect(publicationStepTotals().effects.count).toBeGreaterThan(timed.effects.count);
+ expect((await engine.getPage(PAGE_SLUG, { sourceId: `budget-${String(scale).replace('.', '-')}` }))?.slug).toBe(PAGE_SLUG);
+ return { page, records: counter.records, publication: publicationOf(counter.records) };
+ } finally {
+ await disposePersistenceConsumer(engine);
+ }
+ });
+}
+
+describe('managed import statement budget (PGLite)', () => {
+ test('the publication transaction runs every statement the same number of times at every size, except bounded chunks', async () => {
+ const [small, large] = [await measured(0.5), await measured(2)];
+ const smallCounts = byText(small.publication), largeCounts = byText(large.publication);
+ for (const text of new Set([...smallCounts.keys(), ...largeCounts.keys()])) {
+ const chunk = chunkOf(text);
+ if (chunk) {
+ for (const run of [small, large]) expect(byText(run.publication).get(text) ?? 0).toBeLessThanOrEqual(Math.ceil(chunk.rows(run.page) / chunk.rowsPerChunk));
+ continue;
+ }
+ expect({ text, count: largeCounts.get(text) ?? 0 }).toEqual({ text, count: smallCounts.get(text) ?? 0 });
+ }
+ for (const chunk of CHUNKED) expect([...largeCounts.keys()].some(text => chunk.pattern.test(text))).toBe(true);
+ }, 240_000);
+
+ test('the publication transaction stays within its budget at 1x', async () => {
+ const { publication } = await measured(1);
+ expect(publication.length).toBeLessThanOrEqual(PUBLICATION_BUDGET);
+ }, 240_000);
+
+ test('no statement runs per row or per code reference anywhere in the import', async () => {
+ for (const scale of SIZES) {
+ const { records, page } = await measured(scale);
+ expect(page.codeRefs.length * 2).toBeGreaterThan(PER_ROW_CEILING);
+ const hot = [...byText(records)].filter(([text, count]) => !chunkOf(text) && count >= PER_ROW_CEILING);
+ expect(hot).toEqual([]);
+ }
+ }, 240_000);
+});
diff --git a/test/publication-timing.test.ts b/test/publication-timing.test.ts
new file mode 100644
index 0000000000..55c7b4701b
--- /dev/null
+++ b/test/publication-timing.test.ts
@@ -0,0 +1,38 @@
+/**
+ * #6712 PR 3 (L6): publication step timing.
+ *
+ * Protects: each timed step adds to its process-local total whether it
+ * resolves or throws (the error still reaches the caller); nothing is printed
+ * unless GBRAIN_SYNC_TRACE is set, and then one line per step names the step and
+ * the page. The wiring into the publication transaction is pinned by
+ * test/managed-import-statement-budget.test.ts.
+ */
+import { afterEach, expect, spyOn, test } from 'bun:test';
+import { publicationStepTotals, timePublicationStep } from '../src/core/persistence/publication-timing.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const writes: string[] = [];
+const spy = spyOn(process.stderr, 'write').mockImplementation(((chunk: string | Uint8Array) => { writes.push(String(chunk)); return true; }) as typeof process.stderr.write);
+afterEach(() => { writes.length = 0; });
+
+test('a timed step adds to its total and prints nothing by default', async () => {
+ const before = publicationStepTotals();
+ await withEnv({ GBRAIN_SYNC_TRACE: undefined }, async () => {
+ expect(await timePublicationStep('apply', 'notes/a', async () => { await Bun.sleep(5); return 7; })).toBe(7);
+ });
+ const after = publicationStepTotals();
+ expect(after.apply.count).toBe(before.apply.count + 1);
+ expect(after.apply.ms - before.apply.ms).toBeGreaterThanOrEqual(4);
+ expect(after.effects).toEqual(before.effects);
+ expect(writes.filter(line => line.startsWith('[sync] publish'))).toEqual([]);
+});
+
+test('a step that throws still counts and rethrows; GBRAIN_SYNC_TRACE prints one line per step', async () => {
+ const before = publicationStepTotals();
+ await withEnv({ GBRAIN_SYNC_TRACE: '1' }, async () => {
+ await expect(timePublicationStep('effects', 'notes/b', async () => { throw new Error('refused'); })).rejects.toThrow('refused');
+ });
+ expect(publicationStepTotals().effects.count).toBe(before.effects.count + 1);
+ expect(writes.filter(line => line.startsWith('[sync] publish'))).toEqual([expect.stringMatching(/^\[sync\] publish effects notes\/b: \d+ms\n$/)]);
+ spy.mockRestore();
+});
diff --git a/test/sync-convergence.serial.test.ts b/test/sync-convergence.serial.test.ts
index 5b5f48b3ae..c1ad584309 100644
--- a/test/sync-convergence.serial.test.ts
+++ b/test/sync-convergence.serial.test.ts
@@ -59,7 +59,6 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { execFileSync, spawn, type ChildProcess } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { appendFileSync, chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
-import { createConnection, createServer, type Server, type Socket } from 'node:net';
import { tmpdir } from 'node:os';
import { dirname, join, relative, resolve } from 'node:path';
import postgres from '#postgres';
@@ -75,6 +74,7 @@ import { PUBLICATION_CEILING_DEFAULT_MS, publicationLeaseMs } from '../src/core/
import { assertSafeE2eDatabaseUrl } from './helpers/db-guard.ts';
import { keylessBrainEnv } from './helpers/provider-env.ts';
import { withEnv } from './helpers/with-env.ts';
+import { LatencyProxy } from './helpers/latency-proxy.ts';
import type { ViolationClass } from '../scripts/persistence/model.ts';
const REPO_ROOT = resolve(import.meta.dir, '..');
@@ -271,55 +271,6 @@ function bigPage(facts: number, timeline: number, version: string): string {
}
const entityText = '---\ntype: person\ntitle: Alice Example\n---\n\nAlice Example works with acme-example.\n';
-// ---------------------------------------------------------------- the latency proxy
-
-/** A TCP proxy that delays every chunk by half the configured round trip in each direction, preserving order. */
-class LatencyProxy {
- private server: Server;
- private sockets = new Set<Socket>();
- port = 0;
- constructor(private target: { host: string; port: number }, private oneWayMs: number) {
- this.server = createServer(client => this.accept(client));
- }
- async listen(): Promise<void> {
- await new Promise<void>(done => this.server.listen(0, '127.0.0.1', done));
- const address = this.server.address();
- if (!address || typeof address === 'string') throw new Error('latency proxy has no port');
- this.port = address.port;
- }
- private delayed(from: Socket, to: Socket): void {
- const queue: { at: number; chunk: Buffer }[] = [];
- let timer: ReturnType<typeof setTimeout> | undefined;
- const drain = () => {
- timer = undefined;
- const now = performance.now();
- while (queue.length && queue[0].at <= now) { const { chunk } = queue.shift()!; if (!to.destroyed) to.write(chunk); }
- if (queue.length) timer = setTimeout(drain, Math.max(0, queue[0].at - performance.now()));
- };
- from.on('data', (chunk: Buffer) => {
- queue.push({ at: performance.now() + this.oneWayMs, chunk });
- if (!timer) timer = setTimeout(drain, this.oneWayMs);
- });
- from.on('end', () => { const close = () => (queue.length ? setTimeout(close, this.oneWayMs) : to.end()); close(); });
- }
- private accept(client: Socket): void {
- const upstream = createConnection(this.target);
- for (const socket of [client, upstream]) {
- this.sockets.add(socket);
- socket.on('close', () => this.sockets.delete(socket));
- socket.on('error', () => { client.destroy(); upstream.destroy(); });
- }
- this.delayed(client, upstream);
- this.delayed(upstream, client);
- }
- /** Mode (f): every live connection through the pooler drops at once, as a pooler restart looks to its clients. */
- drop(): number { const n = this.sockets.size; for (const socket of this.sockets) socket.destroy(); return n; }
- async close(): Promise<void> {
- for (const socket of this.sockets) socket.destroy();
- await new Promise<void>(done => this.server.close(() => done()));
- }
-}
-
// ---------------------------------------------------------------- one brain
interface Fault { point: FaultPoint; nth: number; marker: string; operation?: string; path?: string; action?: 'kill' | 'edit' | 'stall' | 'throw';
diff --git a/test/sync-status-statement-budget.test.ts b/test/sync-status-statement-budget.test.ts
new file mode 100644
index 0000000000..20332fa692
--- /dev/null
+++ b/test/sync-status-statement-budget.test.ts
@@ -0,0 +1,92 @@
+/**
+ * #6712 PR 3 (L6): `gbrain sync status` costs a fixed number of statements
+ * however many request rows the source has.
+ *
+ * Protects: the plain status (and the --detail status) of a source with 61,000
+ * terminal write receipts sends exactly as many statements as with 1,000, and
+ * the plain status stays within its round-trip budget, so its latency is
+ * bounded by round trips times RTT (the 5 s target at 57 ms leaves room for
+ * about 87), not by the size of the journal.
+ * Fails when: a status read turns per row (or per receipt), or the plain
+ * status grows past its budget.
+ * Seams: the PGLite statement counter; Postgres through the wire trace in
+ * test/e2e/sync-status-statement-budget-postgres.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../src/core/postgres-engine.ts';
+import { vacuumPersistenceQueues } from '../src/core/persistence/journal.ts';
+import { readSyncStatus } from '../src/core/persistence/sync-status.ts';
+import { countPgliteStatements, readSqlTrace, type StatementRecord } from './helpers/statement-counter.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+/** About 10% over the measured plain status (#6712 L6 measured 10 statements on PGLite, 14 on Postgres). */
+const PLAIN_BUDGET = { pglite: 11, postgres: 15 } as const;
+const home = mkdtempSync(join(tmpdir(), 'gbrain-status-budget-'));
+afterAll(() => rmSync(home, { recursive: true, force: true }));
+
+/** `rows` terminal receipts of managed imports: most committed, one in fifty failed, the newest within the last ten minutes. */
+async function seed(engine: BrainEngine, sourceId: string, rows: number) {
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ await engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,authority,intent_bytes,
+ terminal_reservation,state,error_code,error_message,intent,completed_at,updated_at,admitter_version)
+ SELECT 'local_cli','fixture',gen_random_uuid(),'put_page',$1,(SELECT incarnation FROM sources WHERE id=$1),'notes/n'||g,md5(g::text),'{}'::jsonb,0,0,
+ CASE WHEN g % 50 = 0 THEN 'failed' ELSE 'committed' END, CASE WHEN g % 50 = 0 THEN 'storage_error' END, CASE WHEN g % 50 = 0 THEN 'fixture failure' END,
+ jsonb_build_object('kind','managed_sync_import','path','notes/n'||g||'.md'),
+ now() - make_interval(secs => g), now() - make_interval(secs => g), '0.60.267.0'
+ FROM generate_series(1,$2::int) AS g`, [sourceId, rows]);
+ // PGLite has no autovacuum: the resident owner keeps the queue's planner statistics current as it grows, so the
+ // fixture does what that owner does (without statistics the --detail summary plans a nested loop over every receipt).
+ await vacuumPersistenceQueues(engine);
+}
+
+for (const backend of testBackends()) {
+ describe(`sync status statement budget (${backend})`, () => {
+ const trace = join(home, `trace-${backend}.jsonl`);
+ let engine: BrainEngine;
+ let counted: <T>(run: () => Promise<T>) => Promise<StatementRecord[]>;
+ const sources: string[] = [];
+ beforeAll(async () => {
+ await withEnv(backend === 'postgres' ? { GBRAIN_SQL_TRACE: trace, GBRAIN_SQL_TRACE_LABEL: 'status-budget' } : {}, async () => {
+ if (backend === 'pglite') {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engine = lite;
+ counted = async run => { const counter = countPgliteStatements(lite); try { await run(); } finally { counter.stop(); } return counter.records; };
+ } else {
+ const pg = new PostgresEngine(); await pg.connect({ database_url: requirePostgresTestDatabase(), poolSize: 1 }); await pg.initSchema(); engine = pg;
+ counted = async run => {
+ const started = performance.timeOrigin + performance.now();
+ await run();
+ const ended = performance.timeOrigin + performance.now();
+ // The trace flushes every second; one more flush lands the window.
+ await Bun.sleep(1200);
+ return readSqlTrace(trace).filter(record => record.t >= started && record.t <= ended);
+ };
+ }
+ });
+ });
+ afterAll(async () => {
+ if (backend === 'postgres') for (const id of sources) await engine.executeRaw('DELETE FROM sources WHERE id=$1', [id]);
+ await engine?.disconnect();
+ });
+
+ test('a 61,000-receipt source costs the same statements as a 1,000-receipt one, within budget', async () => {
+ const statements = (records: StatementRecord[]) => records.filter(record => record.kind === 'execute' || record.kind === 'simple').length;
+ const measured: Record<string, { plain: number; detail: number }> = {};
+ for (const rows of [1_000, 61_000]) {
+ const sourceId = `status-budget-${backend}-${rows}`;
+ sources.push(sourceId);
+ await seed(engine, sourceId, rows);
+ const plain = await counted(() => readSyncStatus(engine, sourceId, { detail: false }));
+ const detail = await counted(() => readSyncStatus(engine, sourceId, { detail: true }));
+ measured[rows] = { plain: statements(plain), detail: statements(detail) };
+ }
+ expect(measured[61_000]).toEqual(measured[1_000]!);
+ expect(measured[61_000]!.plain).toBeLessThanOrEqual(PLAIN_BUDGET[backend]);
+ }, 300_000);
+ });
+}