Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Wave B PR 2 lane 2d: stream segmented pages through export
garrytanff2b218b569e
diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.mdindex df3c60b2d6..54ce030ea9 100644--- a/docs/architecture/key-files/commands-3.md+++ b/docs/architecture/key-files/commands-3.md@@ -27,7 +27,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/eval.ts` — `gbrain eval` command: single-run table + A/B config comparison. Sub-subcommand dispatch on `args[0]` routes `gbrain eval export` + `gbrain eval prune` + `gbrain eval replay` into session-capture handlers; bare `gbrain eval --qrels …` fall-through preserves the legacy IR-metrics flow. `gbrain eval cross-modal` is in the dispatch (the user-facing path is the cli.ts no-DB branch — `src/commands/eval.ts:cross-modal` only fires when callers re-enter with an existing engine).-- `src/commands/export.ts` + `src/core/export-snapshot.ts` + `src/core/export-stage.ts` + `src/core/export-publish.ts` — local Markdown export collects source/page/canonical-withdrawal/tag/raw state in one export-scoped repeatable-read read-only transaction, using 256-key ID batches and private disk-backed SQLite staging. Primary-key page reads reuse the canonical withdrawal overlay without source-wide slug scans under stale planner statistics. Each 256-key batch groups by source and retains only one capacity-checked withdrawal ledger at a time; bodies with no literal `gbrain:facts:` marker skip normalization, while malformed/orphan markers still use canonical SQL fingerprinting. No engine defaults or shared migration iterators change. Explicit source selection is validated; restore-only selects one source through `resolveRestoreTarget` (`src/core/restore-target.ts`, shared with `gbrain storage status`) and checks its recorded file path through the existing native path resolver. The manifest rejects unsafe paths, same/cross-source aliases, case/Unicode and file-prefix collisions before destination output, preserving the `<slug>.md` and `.raw/<name>.json` layout. Existing planned paths refuse rather than overwrite. The portable first-party native addon anchors no-follow directories and publishes leaves with atomic no-replace operations, retaining an exclusive persistent `.gbrain-export-status` marker; success requires flushed data and a final COMPLETE line. Unsupported native capabilities fail closed without a pathname fallback. A fresh destination is the retry path; unrelated files are never pruned. Fixed capacity/time limits fail visibly, never truncate. This is a historical snapshot, not a database backup or a sandbox against another same-user process renaming directories. See [safe export](../../storage-tiering.md#safe-export). Engine-free `export --help` documents scope, no-overwrite publication and incomplete-output recovery. Pinned by both-engine export safety/independent-roundtrip/snapshot/failure-release suites, the 100001-page scale fixture with staging bytes and full export SQL statement accounting, the native publication/compiled-wrapper suite, actual CLI help tests, and the PostgreSQL export E2E wrapper.+- `src/commands/export.ts` + `src/core/export-snapshot.ts` + `src/core/export-stage.ts` + `src/core/export-publish.ts` — local Markdown export collects source/page/canonical-withdrawal/tag/raw state in one export-scoped repeatable-read read-only transaction, using 256-key ID batches and private disk-backed SQLite staging. Primary-key page reads reuse the canonical withdrawal overlay without source-wide slug scans under stale planner statistics. Each 256-key batch groups by source and retains only one capacity-checked withdrawal ledger at a time; bodies with no literal `gbrain:facts:` marker skip normalization, while malformed/orphan markers still use canonical SQL fingerprinting. No engine defaults or shared migration iterators change. Explicit source selection is validated; restore-only selects one source through `resolveRestoreTarget` (`src/core/restore-target.ts`, shared with `gbrain storage status`) and checks its recorded file path through the existing native path resolver. The manifest rejects unsafe paths, same/cross-source aliases, case/Unicode and file-prefix collisions before destination output, preserving the `<slug>.md` and `.raw/<name>.json` layout. Existing planned paths refuse rather than overwrite. The portable first-party native addon anchors no-follow directories and publishes leaves with atomic no-replace operations, retaining an exclusive persistent `.gbrain-export-status` marker; success requires flushed data and a final COMPLETE line. Unsupported native capabilities fail closed without a pathname fallback. A fresh destination is the retry path; unrelated files are never pruned. Fixed capacity/time limits fail visibly, never truncate. This is a historical snapshot, not a database backup or a sandbox against another same-user process renaming directories. See [safe export](../../storage-tiering.md#safe-export). Engine-free `export --help` documents scope, no-overwrite publication and incomplete-output recovery. Wave B PR 2: a segmented page streams (`segmentedExportMarkdown`: serializeMarkdown's head, the trusted stored body through `readBodyRange` with the same withdrawal overlay, the timeline separator before the first timeline byte) into its own stage file (`ExportStage.addStream`, a full collection per 1 MiB read), published with the native path API; its payload estimate is `body_bytes`, the per-page limit is `exportPayloadLimit(pages.max_bytes)` (32 MiB while segmented storage is off), a streamed page adds 1 ms per KiB to the 10-minute snapshot deadline and stage files must leave 512 MiB free on the staging filesystem (`test/e2e/large-pages-export.test.ts`: inline vs segmented same bytes at 2 and 20 MiB, export(import(F)) == F, a gated 128 MiB memory arm). Pinned by both-engine export safety/independent-roundtrip/snapshot/failure-release suites, the 100001-page scale fixture with staging bytes and full export SQL statement accounting, the native publication/compiled-wrapper suite, actual CLI help tests, and the PostgreSQL export E2E wrapper.- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into bounded windows via `src/core/facts/conversation-windows.ts` (#6267: eligibility per 30-min gap group of ≥2 messages decided before windowing; windows close at 30 messages or when the rendered text with its header would exceed 6,500 chars; oversized turns split at sentence boundaries with the speaker prefix repeated; a trailing single reply of an eligible group is its own window, never glued across a gap; nothing is clipped and an unrepresentable header fails the page before prior-fact cleanup; a page's frontmatter `conversation_segment_gap_minutes`, an integer from 1 to 10080, overrides the gap for that page, and any other value is ignored with a stderr warning naming the accepted range), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES` = `CONVERSATION_BODY_MAX_BYTES` in `conversation-parser/body.ts`, `PAGE_MAX_BYTES` + 1 MiB = 25 MiB, measured on the parser input; `readConversationBodyForParsing` stats a `raw_transcript` sidecar and throws `ConversationBodyTooLargeError` over the cap before any read, the snapshot carries `oversizedSidecarBytes`, and a size skip writes a `skipped_too_large` receipt to `page_extraction_state` (doctor `extraction_input_truncated`) that a later run under the cap clears; test `test/conversation-facts-oversized-sidecar.test.ts`); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd` (a DEFAULT cap is dropped with a warning when the extraction or parser chat model is unpriced, via `src/core/facts/conversation-budget.ts` `conversationFactsCostCap` (#5823); explicit CLI/caller/cycle caps stay fail-closed and a `no_pricing` stop reports `budget_reason`/`budget_model`, exits 1 and names `pricing.overrides`); **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); **`--background` via `maybeBackground`**; and **speaker-shaped-fold decline** — when the parse reports `unrecognized_headings` containing a speaker-shaped label (1-2 title-cased words, not in the doc-heading stoplist — the stoplist gates the DECLINE only, so a miss is warn-noise, never data loss) AND the parse produced fewer than two distinct speakers, the page is declined instead of extracted under wrong attribution: counted in `pages_skipped_unrecognized_speaker` (Result/CLI/cycle surfaces), warned to stderr with the folding pattern id, and deliberately NON-terminal (no durable audit row and no orphan cleanup, so a future parser/pattern fix retries the page); multi-speaker pages with folds proceed warn-only. The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source, and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). `deleteOrphanFactsForPage(engine, sourceId, slug)` provides delete-orphans-first replay safety — wipes facts from a prior crashed run for this (sourceId, slug) before re-extracting, so a terminal audit row can never certify a partial insertFacts failure. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Additive `pages_skipped_unparsed`, `pages_skipped_type_mismatch`, `pages_skipped_insufficient_turns`, and `pages_skipped_since` explain the unchanged `pages_skipped` aggregate across core, CLI, workers, and cycle sources; durable completion remains separate. `--dry-run` stops after segmentation, with no parser-fallback, extractor, or embedding calls and no durable knowledge/checkpoint/receipt/rollup writes. The narrow `python-dict-utterance` registry format and its quoted/nested-example rejection are documented in [conversation parser patterns](../conversation-parser-patterns.md). Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-diagnostics.serial.test.ts` (pool workers, per-page lock skip + exit 3, delete-orphans-first replay, D15 preflight, `--workers` round-trip). `src/commands/doctor.ts` reads the same outcomes, which survive checkpoint GC. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Explicit `slugs` batches contain page failures like the pool (cancellation and budget stops halt); logs carry only the closed reason and a retry command. Completion requires every in-scope segment (exactly `--segment-limit` counts). Extracted rows take `facts.default_visibility` (resolved once per run); audit rows stay private. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed delete-first. `no_match`, errors, cancellation, and dry runs never become durable negatives, bar `facts/conversation-skip.ts` (prose meetings, single emails, undated turns). Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. On a managed brain the core runs `managedDerivedFactsPreflight` (local writer, active source) before any provider work, and a page's facts and terminal (or non-extractable) audit row are buffered, then replace the prior extractor batch in one `replaceDerivedFactsForPage` transaction after source activity, page id, revision and parser-input snapshot are rechecked under the page lock, so a failed or raced re-extraction keeps the prior batch; the CLI no longer refuses up front and receipt pages are skipped. Tests: `test/managed-facts-writers.test.ts`, `test/managed-unsupported-preflight.serial.test.ts` (refusal before spend for an unaccepted writer).diff --git a/native/locks/README.md b/native/locks/README.mdindex d42e82404a..18a27285a2 100644--- a/native/locks/README.md+++ b/native/locks/README.md@@ -61,9 +61,13 @@ within Node-API v3 and the existing Windows platform minimum.## Export publication`export-publication.h` adds `beginExport(absoluteDestination)`,-`publishExportFile(handle, relativePath, Buffer)`, `completeExport(handle)` and-idempotent `closeExport(handle)`. `nativeExportPublisher()` loads these four-synchronous methods asynchronously through the same literal addon imports.+`publishExportFile(handle, relativePath, Buffer)`,+`publishExportFileFrom(handle, relativePath, absoluteSource)`, `completeExport(handle)` and+idempotent `closeExport(handle)`. `publishExportFileFrom` copies a staged regular+file (an absolute path, leaf symlinks and reparse points refused) through 1 MiB+reads into the same no-replace leaf publication, so a large page is never held+whole in memory. `nativeExportPublisher()` loads these five synchronous methods+asynchronously through the same literal addon imports.Export handles have their own registry and cleanup hook; they cannot be passedto lock operations, or vice versa. There is no filesystem fallback when theaddon or an OS primitive is unavailable.diff --git a/native/locks/export-publication.h b/native/locks/export-publication.hindex aa1abd81fe..c0f4f10589 100644--- a/native/locks/export-publication.h+++ b/native/locks/export-publication.h@@ -125,7 +125,7 @@ static unsigned long export_verify(export_handle *handle, export_dir *dir) {#endif}-static unsigned long export_write(os_handle handle, const void *data, size_t length) {+static unsigned long export_write_all(os_handle handle, const void *data, size_t length) {const char *cursor = data;while (length) {size_t amount = length > 0x40000000 ? 0x40000000 : length;@@ -140,7 +140,12 @@ static unsigned long export_write(os_handle handle, const void *data, size_t lencursor += written;length -= (size_t)written;}- return export_flush(handle);+ return 0;+}++static unsigned long export_write(os_handle handle, const void *data, size_t length) {+ unsigned long error = export_write_all(handle, data, length);+ return error ? error : export_flush(handle);}static bool export_component(const char *name) {@@ -441,12 +446,56 @@ failed:return export_fail(env, "begin", error);}-static napi_value publish_export_file(napi_env env, napi_callback_info info) {+#define EXPORT_COPY_BYTES (1024 * 1024)++/* Copies a regular file the caller staged (an absolute path, opened without following a leaf link) in bounded reads. */+static unsigned long export_copy(os_handle target, const char *source) {+ char *buffer = malloc(EXPORT_COPY_BYTES);+ if (!buffer) return export_invalid();+ unsigned long error = 0;+#ifdef _WIN32+ wchar_t *wide = export_wide(source);+ if (!wide) { free(buffer); return export_invalid(); }+ os_handle input = CreateFileW(wide, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,+ FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_SEQUENTIAL_SCAN, NULL);+ free(wide);+ if (input == INVALID_LOCK_HANDLE) error = export_error();+ BY_HANDLE_FILE_INFORMATION info;+ if (!error && !GetFileInformationByHandle(input, &info)) error = export_error();+ if (!error && (info.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT))) error = export_invalid();+ while (!error) {+ DWORD got = 0;+ if (!ReadFile(input, buffer, EXPORT_COPY_BYTES, &got, NULL)) { error = export_error(); break; }+ if (!got) break;+ error = export_write_all(target, buffer, got);+ }+#else+ os_handle input = source[0] == '/' ? open(source, O_RDONLY | O_NOFOLLOW | O_CLOEXEC) : INVALID_LOCK_HANDLE;+ if (input == INVALID_LOCK_HANDLE) error = source[0] == '/' ? export_error() : export_invalid();+ struct stat info;+ if (!error && fstat(input, &info) != 0) error = export_error();+ if (!error && !S_ISREG(info.st_mode)) error = export_invalid();+ while (!error) {+ long got = read(input, buffer, EXPORT_COPY_BYTES);+ if (got < 0) { if (errno == EINTR) continue; error = export_error(); break; }+ if (!got) break;+ error = export_write_all(target, buffer, (size_t)got);+ }+#endif+ unsigned long close_error = export_close_file(input);+ free(buffer);+ if (!error) error = close_error;+ return error ? error : export_flush(target);+}++/* Publishes argv[2], a Buffer, or with `from_path` the absolute path of a staged regular file copied in bounded reads. */+static napi_value publish_export(napi_env env, napi_callback_info info, bool from_path) {napi_value argv[3];export_handle *handle = export_get(env, info, 3, argv);if (!handle) return NULL;if (!handle->root || handle->failed || handle->completed) return export_fail(env, "inactive handle", 0);char *path = export_string(env, argv[1]);+ char *source = from_path ? export_string(env, argv[2]) : NULL;void *data = NULL;size_t length = 0;bool buffer = false;@@ -455,15 +504,15 @@ static napi_value publish_export_file(napi_env env, napi_callback_info info) {os_handle temporary = INVALID_LOCK_HANDLE;bool published = false;if ((error = export_verify(handle, handle->root))) goto failed;- if (!path || !strcmp(path, EXPORT_MARKER) ||+ if (!path || !strcmp(path, EXPORT_MARKER) || (from_path ? !source :napi_is_buffer(env, argv[2], &buffer) != napi_ok || !buffer ||- napi_get_buffer_info(env, argv[2], &data, &length) != napi_ok) { error = export_invalid(); goto failed; }+ napi_get_buffer_info(env, argv[2], &data, &length) != napi_ok)) { error = export_invalid(); goto failed; }char *leaf = NULL;parent = export_walk(handle->root, path, &leaf, &error);if (!parent) goto failed;temporary = export_create(parent, handle->temporary, &error);if (temporary == INVALID_LOCK_HANDLE) goto failed;- if ((error = export_write(temporary, data, length))) goto failed;+ if ((error = from_path ? export_copy(temporary, source) : export_write(temporary, data, length))) goto failed;if ((error = export_verify(handle, parent))) goto failed;if ((error = export_publish(parent, handle->temporary, leaf, temporary))) goto failed;published = true;@@ -483,10 +532,19 @@ failed:unsigned long close_error = export_close_dirs(parent, handle->root);if (!error) error = close_error;free(path);+ free(source);if (error) { handle->failed = true; return export_fail(env, "publish", error); }return export_undefined(env);}+static napi_value publish_export_file(napi_env env, napi_callback_info info) {+ return publish_export(env, info, false);+}++static napi_value publish_export_file_from(napi_env env, napi_callback_info info) {+ return publish_export(env, info, true);+}+static void export_uncomplete(export_handle *handle) {#ifdef _WIN32LARGE_INTEGER offset;diff --git a/native/locks/locks.c b/native/locks/locks.cindex e85f13da45..b3a9236f2e 100644--- a/native/locks/locks.c+++ b/native/locks/locks.c@@ -321,6 +321,7 @@ NAPI_MODULE_INIT() {{"close", NULL, close_lock, NULL, NULL, NULL, napi_default, state},{"beginExport", NULL, begin_export, NULL, NULL, NULL, napi_default, publisher},{"publishExportFile", NULL, publish_export_file, NULL, NULL, NULL, napi_default, publisher},+ {"publishExportFileFrom", NULL, publish_export_file_from, NULL, NULL, NULL, napi_default, publisher},{"completeExport", NULL, complete_export, NULL, NULL, NULL, napi_default, publisher},{"closeExport", NULL, close_export, NULL, NULL, NULL, napi_default, publisher},#ifdef _WIN32diff --git a/native/locks/manifest.json b/native/locks/manifest.jsonindex 2bee588ec1..e8c77c6ee7 100644--- a/native/locks/manifest.json+++ b/native/locks/manifest.json@@ -2,39 +2,39 @@"version": 1,"napi": 3,"zig": "0.14.1",- "input_sha256": "93c31a185cca8bfdf8a58fbb79d81bafcc8c377b4a0625eb39571c68115dde84",+ "input_sha256": "9f4f646beaed859ce5d130a05e8eaa43e67006d3b0b7655eea01de5d4bbae03b","artifacts": {"linux-x64-glibc": {- "sha256": "8370d9d1b62cdd7ee518035ef558496096c2acc045e10c5c582692a3004d4d49",- "bytes": 16464+ "sha256": "6194329dbb1a410aca6614ceaa9b5cf1ff4c1c0c9fad3d7106e59ebe2ce1ebce",+ "bytes": 17296},"linux-arm64-glibc": {- "sha256": "ca8a2b9efedbc0568fc8c017e52ca561d68dee97c45b679405bedd4f09431784",- "bytes": 16544+ "sha256": "78dfa5e3b3cbe1e192a0d86e0282ce14e363c7c80fabe7f70b830358ae7b7a63",+ "bytes": 17280},"linux-x64-musl": {- "sha256": "704c847c4f9d6713997ebdfea2f7d00ab2accb58a5f4cc57b8ca83bebd1a35c7",- "bytes": 15976+ "sha256": "6810aef4a80309a1d95f4386c640d685e7025e31aedb85279f76f50df0712b08",+ "bytes": 16808},"linux-arm64-musl": {- "sha256": "c2be13cfb32fb44b5415e541452988406e60473c051b2266add664ca85fa0979",- "bytes": 16120+ "sha256": "b75c7c8cbbadb81e66fc970ddb09efb9c3ec7515bb89c2ae9d7155ef7600fa44",+ "bytes": 16872},"darwin-x64": {- "sha256": "3d4fff3b91a6c1d80f0efd39bcb0f8bca5df369463510cf9c8f0645aeafbfaf6",- "bytes": 27910+ "sha256": "f3614608756acd50a32ebe4fe32736713a74f0d41b3493a9441892243864a8c8",+ "bytes": 28013},"darwin-arm64": {- "sha256": "1caa3889223ef912a190fea43891d402b7c75d134415bb1ba8de0a9b791e0833",- "bytes": 70512+ "sha256": "bb54b41a741baedded5e8379bc8ddde8a0fbd5386e665138a240bf47497ea789",+ "bytes": 70608},"win32-x64": {- "sha256": "04e8bea13fe224cb12d6f71fefc67390be1777eb64cd5d129daf54b2872d53ff",- "bytes": 35328+ "sha256": "0c1d2cd059268ce654f7eb0442dcfb9d196f85cfdd2235c77295c9cfa0edc3eb",+ "bytes": 36352},"win32-arm64": {- "sha256": "1ec55b4859643655882a7f486af04d5d49391605d5d96343b432e9bff08b855b",- "bytes": 31744+ "sha256": "99ac2c187ad37d48890da702729a54c598363858840c507ebe88fb629b045ff8",+ "bytes": 32768}}}diff --git a/native/locks/prebuilds/darwin-arm64.node b/native/locks/prebuilds/darwin-arm64.nodeindex 6267bcad85..749d01ced4 100755Binary files a/native/locks/prebuilds/darwin-arm64.node and b/native/locks/prebuilds/darwin-arm64.node differdiff --git a/native/locks/prebuilds/darwin-x64.node b/native/locks/prebuilds/darwin-x64.nodeindex fca6976d54..bcef0ff471 100755Binary files a/native/locks/prebuilds/darwin-x64.node and b/native/locks/prebuilds/darwin-x64.node differdiff --git a/native/locks/prebuilds/linux-arm64-glibc.node b/native/locks/prebuilds/linux-arm64-glibc.nodeindex a6a49dffe0..49aae38ff6 100755Binary files a/native/locks/prebuilds/linux-arm64-glibc.node and b/native/locks/prebuilds/linux-arm64-glibc.node differdiff --git a/native/locks/prebuilds/linux-arm64-musl.node b/native/locks/prebuilds/linux-arm64-musl.nodeindex 4a18b23aa9..99fb4177e4 100755Binary files a/native/locks/prebuilds/linux-arm64-musl.node and b/native/locks/prebuilds/linux-arm64-musl.node differdiff --git a/native/locks/prebuilds/linux-x64-glibc.node b/native/locks/prebuilds/linux-x64-glibc.nodeindex 74dadd6436..e837a28a1b 100755Binary files a/native/locks/prebuilds/linux-x64-glibc.node and b/native/locks/prebuilds/linux-x64-glibc.node differdiff --git a/native/locks/prebuilds/linux-x64-musl.node b/native/locks/prebuilds/linux-x64-musl.nodeindex 159a9bb2de..6664cfbd8f 100755Binary files a/native/locks/prebuilds/linux-x64-musl.node and b/native/locks/prebuilds/linux-x64-musl.node differdiff --git a/native/locks/prebuilds/win32-arm64.node b/native/locks/prebuilds/win32-arm64.nodeindex 6766c155c7..ae414675b2 100755Binary files a/native/locks/prebuilds/win32-arm64.node and b/native/locks/prebuilds/win32-arm64.node differdiff --git a/native/locks/prebuilds/win32-x64.node b/native/locks/prebuilds/win32-x64.nodeindex a21a9fa6c0..2c83ecb2eb 100755Binary files a/native/locks/prebuilds/win32-x64.node and b/native/locks/prebuilds/win32-x64.node differdiff --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjsindex df505a90bc..4fd946fb5b 100644--- a/scripts/check-orphan-modules.mjs+++ b/scripts/check-orphan-modules.mjs@@ -72,7 +72,7 @@ const PERMITTED_TEST_ONLY = [{ path: 'src/core/ingestion/sources/file-watcher.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision' },{ path: 'src/core/ingestion/sources/gstack-learnings.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision' },{ path: 'src/core/ingestion/sources/inbox-folder.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision (docs/guides/data-ingestion.md promises the inbox folder)' },- { path: 'src/core/ingestion/sources/markdown-greenfield.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision (docs/migrations/v0.41.2-markdown-greenfield.md)' }, { path: 'src/core/page-body/read-range.ts', reason: 'held: Wave B PR 2 segment reader (lane F); the get_page, page-window and evidence lanes of the same PR wire it into their reads' },+ { path: 'src/core/ingestion/sources/markdown-greenfield.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision (docs/migrations/v0.41.2-markdown-greenfield.md)' },];const RULES = {diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex 2e3fdf947c..b642698c3c 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -194,7 +194,7 @@ src/core/engine-sql/salience.ts listEnrichCandidates sql METAsrc/core/engine-sql/timeline.ts getTimeline sql NONE not the page body: SELECT * FROM pages inside a LATERAL used for the page id onlysrc/core/enrichment-service.ts enrichEntity call:putPage INLINEsrc/core/enrichment-service.ts enrichEntity call:serializeMarkdown INLINE-src/core/export-snapshot.ts readExportPage field STREAM export refuses a segmented page: segmented page: getter throws page_body_segmented (streaming export in PR 2)+src/core/export-snapshot.ts readExportPage field STREAM inline pages only: a segmented page skips the overlay here and streams through segmentedExportMarkdown (readBodyRange, trusted stored)src/core/export-snapshot.ts readExportPage sql STREAMsrc/core/extract-ner.ts extractNerLinks field STREAMsrc/core/extract-takes-from-pages.ts extractTakesFromPages call:serializePageToMarkdown SEGWdiff --git a/src/commands/export.ts b/src/commands/export.tsindex e33d6b3fda..b7d26961f0 100644--- a/src/commands/export.ts+++ b/src/commands/export.ts@@ -8,10 +8,12 @@ import { loadStorageConfig, isDbOnly } from '../core/storage-config.ts';import { resolveSourceId } from '../core/source-resolver.ts';import { ALL_SOURCES, assertValidSourceId } from '../core/source-id.ts';import { resolveRestoreTarget, restoreFilePath } from '../core/restore-target.ts';-import { ExportStage, EXPORT_PAYLOAD_LIMIT, EXPORT_SNAPSHOT_MS, exportPathKey } from '../core/export-stage.ts';+import { ExportStage, EXPORT_SNAPSHOT_MS, EXPORT_STREAM_BYTES_PER_MS, exportPathKey, exportPayloadLimit } from '../core/export-stage.ts';import { publishExport } from '../core/export-publish.ts';import { nativeFileTarget } from '../core/persistence/native-file-target.ts';-import { readExportPage, readExportWithdrawals } from '../core/export-snapshot.ts';+import { readExportPage, readExportWithdrawals, segmentedExportMarkdown } from '../core/export-snapshot.ts';+import { readPageBodyPolicy } from '../core/page-body/limits.ts';+import { isSegmentedPage } from '../core/page-body/page-shape.ts';function option(args: string[], name: string): string | undefined {const indices = args.flatMap((arg, i) => arg === name || arg.startsWith(name + '=') ? [i] : []);@@ -54,8 +56,9 @@ a fresh directory. See docs/storage-tiering.md#safe-export.`);stage = new ExportStage();const staged = stage;const started = Date.now();+ let streamedBytes = 0;const checkDeadline = () => {- if (Date.now() - started > EXPORT_SNAPSHOT_MS) throw new Error('Export snapshot time limit reached. Select a smaller scope with --source, --type or --slug-prefix.');+ if (Date.now() - started > EXPORT_SNAPSHOT_MS + streamedBytes / EXPORT_STREAM_BYTES_PER_MS) throw new Error('Export snapshot time limit reached. Select a smaller scope with --source, --type or --slug-prefix.');};await engine.transaction(async tx => {await tx.executeRaw('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');@@ -65,13 +68,15 @@ a fresh directory. See docs/storage-tiering.md#safe-export.`);if (restoreOnly) ({ source, repo } = await resolveRestoreTarget(tx, source, repo));const storage = restoreOnly && repo ? loadStorageConfig(repo) : null;if (restoreOnly && !storage) throw new Error('--restore-only requires a storage tiering config (gbrain.yml with a storage section).');+ const payloadLimit = exportPayloadLimit((await readPageBodyPolicy(tx)).maxBytes);let cursor = '0';for (;;) {checkDeadline();const batch = await tx.executeRaw<{ id: string; slug: string; source_id: string; source_path: string | null; source_path_bytes: number; raw_count: number; bytes: number }>(`SELECT p.id::text, left(p.slug,4097) AS slug, p.source_id, left(p.source_path,4097) AS source_path, octet_length(p.source_path) AS source_path_bytes,(SELECT count(*) FROM raw_data r WHERE r.page_id=p.id) AS raw_count,- octet_length(p.compiled_truth)::bigint + octet_length(p.timeline) + octet_length(p.frontmatter::text)+ CASE WHEN p.body_storage='segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth)::bigint + octet_length(p.timeline) END+ + octet_length(p.frontmatter::text)+ octet_length(p.title) + octet_length(p.slug) + COALESCE(octet_length(p.source_path),0)+ COALESCE((SELECT sum(octet_length(r.data::text)+octet_length(r.source)) FROM raw_data r WHERE r.page_id=p.id),0)+ COALESCE((SELECT sum(octet_length(t.tag)) FROM tags t WHERE t.page_id=p.id),0) AS bytes@@ -91,12 +96,17 @@ a fresh directory. See docs/storage-tiering.md#safe-export.`);if (!isDbOnly(key.slug, storage)) continue;if (existsSync(nativeFileTarget(repo, restoreFilePath(repo, key.slug, key.source_path, Number(key.source_path_bytes), await scannerSlugRootMode(tx, batchSource, repo))))) continue;}- if (Number(key.bytes) > EXPORT_PAYLOAD_LIMIT) throw new Error('Export page payload limit exceeded. No destination output was published.');+ if (Number(key.bytes) > payloadLimit) throw new Error('Export page payload limit exceeded. No destination output was published.');const snapshot = await readExportPage(tx, key, withdrawals);const page = snapshot.page;// #5966: the slug stamp rule lives in slugStampedFrontmatter (markdown.ts), shared with every render.- staged.add(page.slug + '.md', 'file', serializeMarkdown(slugStampedFrontmatter(page.slug, page.frontmatter ?? {}), page.compiled_truth, page.timeline,- { type: page.type, title: page.title, tags: snapshot.tags }));+ const frontmatter = slugStampedFrontmatter(page.slug, page.frontmatter ?? {});+ const meta = { type: page.type, title: page.title, tags: snapshot.tags };+ if (isSegmentedPage(page)) {+ streamedBytes += Number(key.bytes);+ const head = serializeMarkdown(frontmatter, '', '', meta).slice(0, -1);+ await staged.addStream(page.slug + '.md', Number(key.bytes), payloadLimit, segmentedExportMarkdown(tx, page, withdrawals, head));+ } else staged.add(page.slug + '.md', 'file', serializeMarkdown(frontmatter, page.compiled_truth, page.timeline, meta));const raw = Number(key.raw_count) ? await tx.getRawData(page.slug, undefined, { sourceId: page.source_id, includeDeleted: true }) : [];if (raw.length) {const parts = page.slug.split('/');diff --git a/src/core/export-publish.ts b/src/core/export-publish.tsindex e6c06d8fad..389d439148 100644--- a/src/core/export-publish.ts+++ b/src/core/export-publish.ts@@ -42,8 +42,9 @@ export async function publishExport(stage: ExportStage, destination: string, tic}const handle = publisher.beginExport(root);try {- for (const row of stage.db.query<{ path: string; payload: string }, []>("SELECT path, payload FROM paths WHERE kind='file' ORDER BY path").iterate()) {- publisher.publishExportFile(handle, row.path, Buffer.from(row.payload));+ for (const row of stage.db.query<{ path: string; payload: string; file: string | null }, []>("SELECT path, payload, file FROM paths WHERE kind='file' ORDER BY path").iterate()) {+ if (row.file !== null) publisher.publishExportFileFrom(handle, row.path, stage.filePath(row.file));+ else publisher.publishExportFile(handle, row.path, Buffer.from(row.payload));await tick(row.path);}publisher.completeExport(handle);diff --git a/src/core/export-snapshot.ts b/src/core/export-snapshot.tsindex 729a06b3be..a208b16859 100644--- a/src/core/export-snapshot.ts+++ b/src/core/export-snapshot.ts@@ -3,6 +3,12 @@ import { overlayCanonicalBodies } from './page-state/snapshot.ts';import type { PageWithdrawal } from './page-state/types.ts';import { rowToPage } from './utils.ts';import { EXPORT_PAYLOAD_LIMIT } from './export-stage.ts';+import { isSegmentedPage } from './page-body/page-shape.ts';+import { openSegmentedBody, readBodyRange } from './page-body/read-range.ts';+import { TIMELINE_SEPARATOR } from './page-window/document.ts';+import type { Page } from './types.ts';++const EXPORT_COLLECT_BYTES = 1024 * 1024;/** Withdrawals are entity-scoped: `subject` is the entity slug, '*' applies to every page. */export type ExportWithdrawal = PageWithdrawal & { subject: string };@@ -28,10 +34,46 @@ export async function readExportPage(tx: BrainEngine, key: { id: string; source_[key.id, key.source_id, key.slug]);if (!row) throw new Error('Export snapshot unexpectedly lost a selected page.');const page = rowToPage(row);- if (page.compiled_truth.includes('gbrain:facts:') || page.timeline.includes('gbrain:facts:')) {- const applicable = withdrawals.filter(w => w.subject === '*' || w.subject === page.slug)- .map(({ visibility, fact_hash, withdrawn_at, purged }) => ({ visibility, fact_hash, withdrawn_at, ...(purged ? { purged: true } : {}) }));- Object.assign(page, await overlayCanonicalBodies(tx.executeRaw.bind(tx), page.compiled_truth, page.timeline, applicable));+ if (!isSegmentedPage(page) && (page.compiled_truth.includes('gbrain:facts:') || page.timeline.includes('gbrain:facts:'))) {+ Object.assign(page, await overlayCanonicalBodies(tx.executeRaw.bind(tx), page.compiled_truth, page.timeline, applicableWithdrawals(page.slug, withdrawals)));}return { page, tags: row.export_tags as string[] };}++function applicableWithdrawals(slug: string, withdrawals: ExportWithdrawal[]): PageWithdrawal[] {+ return withdrawals.filter(w => w.subject === '*' || w.subject === slug)+ .map(({ visibility, fact_hash, withdrawn_at, purged }) => ({ visibility, fact_hash, withdrawn_at, ...(purged ? { purged: true } : {}) }));+}++/**+ * The Markdown file of a segmented page, piece by piece: `head` (serializeMarkdown's frontmatter and blank line), the+ * truth, TIMELINE_SEPARATOR before the first timeline byte, the timeline and the final newline. Each segment is read+ * once (readBodyRange, trusted stored body) with the overlay readExportPage gives an inline page, so the bytes are+ * those serializeMarkdown gives the same page read inline. A full collection every EXPORT_COLLECT_BYTES read keeps the+ * reads' garbage (protocol buffers, decoded texts) from piling up as in the streamed import (ingest.ts): a 127 MiB page+ * peaked ~700 MiB above a 2 MiB one without it, 8-55 MiB with it.+ */+export async function* segmentedExportMarkdown(tx: BrainEngine, page: Page, withdrawals: ExportWithdrawal[], head: string): AsyncIterable<Uint8Array | string> {+ const body = await openSegmentedBody(tx, { pageId: page.id, ledger: { withdrawals: applicableWithdrawals(page.slug, withdrawals) } });+ let uncollected = 0;+ const collect = (bytes: number) => {+ uncollected += bytes;+ if (uncollected < EXPORT_COLLECT_BYTES) return;+ Bun.gc(true);+ uncollected = 0;+ };+ yield head;+ for await (const piece of readBodyRange(tx, { pageId: page.id, space: 'stored', start: 0, end: Infinity, audience: 'trusted', region: 'truth', body })) {+ yield piece.bytes;+ collect(piece.bytes.length);+ }+ let separated = false;+ for await (const piece of readBodyRange(tx, { pageId: page.id, space: 'stored', start: 0, end: Infinity, audience: 'trusted', region: 'timeline', body })) {+ if (!piece.bytes.length) continue;+ if (!separated) yield TIMELINE_SEPARATOR;+ separated = true;+ yield piece.bytes;+ collect(piece.bytes.length);+ }+ yield '\n';+}diff --git a/src/core/export-stage.ts b/src/core/export-stage.tsindex fea65ae304..03d8b9f310 100644--- a/src/core/export-stage.ts+++ b/src/core/export-stage.ts@@ -1,12 +1,22 @@import { Database } from 'bun:sqlite';-import { mkdtempSync, rmSync } from 'node:fs';+import { closeSync, mkdirSync, mkdtempSync, openSync, rmSync, statfsSync, writeSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';+import { PAGE_MAX_BYTES } from './page-size-policy.ts';export const EXPORT_MARKER = '.gbrain-export-status';export const EXPORT_PAYLOAD_LIMIT = 32 * 1024 * 1024;export const EXPORT_STAGE_LIMIT = 8 * 1024 * 1024 * 1024;export const EXPORT_SNAPSHOT_MS = 10 * 60 * 1000;+/** Snapshot time each byte of a streamed (segmented) page adds: 1 MiB/s, well under the measured read rate. */+export const EXPORT_STREAM_BYTES_PER_MS = 1024 * 1024 / 1000;+/** Free space a streamed stage file must leave on the staging filesystem. */+export const EXPORT_STAGE_FREE_RESERVE = 512 * 1024 * 1024;++/** A page's payload limit: the page ceiling plus the metadata headroom the 32 MiB limit gives a 24 MiB page. */+export function exportPayloadLimit(maxBytes: number): number {+ return Math.max(maxBytes, PAGE_MAX_BYTES) + EXPORT_PAYLOAD_LIMIT - PAGE_MAX_BYTES;+}export function exportPathKey(path: string): string {const parts = path.split('/');@@ -22,20 +32,56 @@ export class ExportStage {readonly directory = mkdtempSync(join(tmpdir(), 'gbrain-export-'));readonly db = new Database(join(this.directory, 'manifest.sqlite'));bytes = 0;+ /** Bytes of streamed stage files, bounded by the staging filesystem's free space rather than the SQLite stage. */+ fileBytes = 0;pages = 0;+ private files = 0;constructor() {- this.db.exec('PRAGMA journal_mode=OFF; PRAGMA synchronous=OFF; PRAGMA cache_size=-4096; PRAGMA max_page_count=2097152; CREATE TABLE paths (key TEXT PRIMARY KEY, path TEXT NOT NULL, kind TEXT NOT NULL, payload BLOB)');+ this.db.exec('PRAGMA journal_mode=OFF; PRAGMA synchronous=OFF; PRAGMA cache_size=-4096; PRAGMA max_page_count=2097152; CREATE TABLE paths (key TEXT PRIMARY KEY, path TEXT NOT NULL, kind TEXT NOT NULL, payload BLOB, file TEXT)');this.add(EXPORT_MARKER, 'marker');}add(path: string, kind: 'file' | 'directory' | 'marker', payload?: string): void {exportPathKey(path);- const parts = path.split('/');const size = payload === undefined ? 0 : Buffer.byteLength(payload);- if (size > EXPORT_PAYLOAD_LIMIT || this.bytes + size > EXPORT_STAGE_LIMIT) {- throw new Error('Export staging capacity exceeded; nothing was published. Use --source, --type or --slug-prefix to select a smaller snapshot.');- }+ if (size > EXPORT_PAYLOAD_LIMIT || this.bytes + size > EXPORT_STAGE_LIMIT) throw stageCapacityError();+ this.plan(path, kind, payload ?? null, null);+ this.bytes += size;+ }++ /**+ * Stage a file written piece by piece to its own file in the stage directory (published by path), so no payload is+ * held whole. `expectedBytes` must fit the staging filesystem with EXPORT_STAGE_FREE_RESERVE to spare; the written+ * bytes must stay within `limit`.+ */+ async addStream(path: string, expectedBytes: number, limit: number, pieces: AsyncIterable<Uint8Array | string>): Promise<void> {+ exportPathKey(path);+ const free = statfsSync(this.directory);+ if (expectedBytes > limit || expectedBytes + EXPORT_STAGE_FREE_RESERVE > Number(free.bavail) * Number(free.bsize)) throw stageCapacityError();+ const name = String(this.files++);+ this.plan(path, 'file', null, name);+ mkdirSync(join(this.directory, 'files'), { recursive: true });+ const fd = openSync(join(this.directory, 'files', name), 'wx', 0o600);+ let size = 0;+ try {+ for await (const piece of pieces) {+ const bytes = typeof piece === 'string' ? Buffer.from(piece, 'utf8') : piece;+ size += bytes.length;+ if (size > limit) throw stageCapacityError();+ for (let at = 0; at < bytes.length;) at += writeSync(fd, bytes, at, bytes.length - at);+ }+ } finally { closeSync(fd); }+ this.fileBytes += size;+ }++ /** The stage file of a path staged by addStream. */+ filePath(name: string): string {+ return join(this.directory, 'files', name);+ }++ private plan(path: string, kind: 'file' | 'directory' | 'marker', payload: string | null, file: string | null): void {+ const parts = path.split('/');for (let i = 1; i <= parts.length; i++) {const current = parts.slice(0, i).join('/');const currentKind = i === parts.length ? kind : 'directory';@@ -45,9 +91,8 @@ export class ExportStage {if (prior.kind === 'directory' && currentKind === 'directory' && prior.path === current) continue;throw new Error('Export path collision (including case, Unicode, page/sidecar or file-prefix aliases). Nothing was published. Export one source at a time with --source <id> into separate fresh directories.');}- this.db.query('INSERT INTO paths VALUES (?, ?, ?, ?)').run(key, current, currentKind, i === parts.length ? payload ?? null : null);+ this.db.query('INSERT INTO paths VALUES (?, ?, ?, ?, ?)').run(key, current, currentKind, i === parts.length ? payload : null, i === parts.length ? file : null);}- this.bytes += size;}close(): void {@@ -55,3 +100,7 @@ export class ExportStage {rmSync(this.directory, { recursive: true, force: true });}}++function stageCapacityError(): Error {+ return new Error('Export staging capacity exceeded; nothing was published. Use --source, --type or --slug-prefix to select a smaller snapshot.');+}diff --git a/src/core/persistence/native-lock.ts b/src/core/persistence/native-lock.tsindex 90831323c4..a7188c859c 100644--- a/src/core/persistence/native-lock.ts+++ b/src/core/persistence/native-lock.ts@@ -9,6 +9,8 @@ import { familySync, GLIBC, MUSL } from 'detect-libc';export interface NativeExportPublisher {beginExport(absoluteDestination: string): object;publishExportFile(handle: object, relativePath: string, data: Buffer): void;+ /** Publishes a staged regular file (absolute path, leaf links refused) copied in bounded reads, never held whole. */+ publishExportFileFrom(handle: object, relativePath: string, absoluteSource: string): void;completeExport(handle: object): void;closeExport(handle: object): void;}@@ -141,7 +143,7 @@ export async function nativeLockCapability(): Promise<{ target: string; napi: 3export async function nativeExportPublisher(): Promise<NativeExportPublisher> {const binding = await (bindingPromise ??= loadBinding());- if (typeof binding.beginExport !== 'function' || typeof binding.publishExportFile !== 'function' ||+ if (typeof binding.beginExport !== 'function' || typeof binding.publishExportFile !== 'function' || typeof binding.publishExportFileFrom !== 'function' ||typeof binding.completeExport !== 'function' || typeof binding.closeExport !== 'function') {throw new NativeLockUnavailableError('Installed native addon lacks safe export publication support');}diff --git a/test/e2e/large-pages-export.test.ts b/test/e2e/large-pages-export.test.tsnew file mode 100644index 0000000000..2190325d14--- /dev/null+++ b/test/e2e/large-pages-export.test.ts@@ -0,0 +1,276 @@+/**+ * Wave B PR 2 (spec 7.4): Markdown export of segmented pages.+ *+ * Protects:+ * - Round trip at 2 and 20 MiB, both engines: a page stored inline (switch off)+ * and the same page stored segmented (switch on) export the same bytes; that+ * file F is canonical (sha256(F) == sha256(serializePageToMarkdown) of the+ * inline page) and export(import(F)) == F for both storage classes. With a+ * withdrawn fact both classes export the same struck file.+ * - Streamed ingest (a file over PAGE_MAX_BYTES) reproduces the importer's trim:+ * leading and trailing body whitespace is dropped, so export(import(F')) has+ * F's body (above 24 MiB the import stamps content-sanity keys into the+ * frontmatter, so only the body round-trips byte for byte).+ * - Abort semantics: a segmented page over the payload limit refuses the whole+ * export (its estimate is `body_bytes`, not NULL); a streamed page extends the+ * snapshot deadline by its bytes.+ * - Backup: a PGLite backup restores a segmented page that exports the same bytes.+ * - 128 MiB (GBRAIN_TEST_LARGE_EXPORT=1, PGLite): the export of a 128 MiB page+ * has F's body and its peak memory (VmHWM) stays under 80 MiB above exporting a+ * 2 MiB page. Run it under a cgroup limit as well (the 20 MiB arms import a+ * fence-heavy page on the string path, which peaks far above 1G on its own):+ * GBRAIN_TEST_LARGE_EXPORT=1 sudo -E systemd-run --scope -p MemoryMax=1G -p MemorySwapMax=0 \+ * "$(command -v bun)" test --timeout=1800000 -t '128 MiB' test/e2e/large-pages-export.test.ts+ * Fails when: export reads a segmented body through the throwing getters+ * (page_body_segmented), joins its segments into one string or Buffer, publishes+ * it as one Buffer, keeps the 32 MiB per-page limit, or the stream and the inline+ * serializer disagree on the frontmatter head, timeline separator or overlay.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import { closeSync, mkdirSync, mkdtempSync, openSync, readFileSync, realpathSync, rmSync, writeFileSync, writeSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { importFromFile } from '../../src/core/import-file.ts';+import { runExport } from '../../src/commands/export.ts';+import { serializeMarkdown, serializePageToMarkdown } from '../../src/core/markdown.ts';+import { EXPORT_SNAPSHOT_MS } from '../../src/core/export-stage.ts';+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';+import { createPgliteBackup, restorePgliteBackup } from '../../src/core/backup/snapshot.ts';+import { bigPage } from '../helpers/segment-bodies.ts';+import { conversationBody } from '../helpers/conversation-page.ts';+import { requirePostgresTestDatabase, testBackends } from '../helpers/test-backends.ts';++const REPO = resolve(import.meta.dir, '../..');+const MiB = 1024 * 1024;+const SLUG = 'notes/large-export';+const TIMELINE = '- **2024-01-02** | src — first entry\n detail line\n- **2024-02-03** | src — second entry';+const sha = (bytes: Buffer | string) => createHash('sha256').update(bytes).digest('hex');+/**+ * The file after its frontmatter block. Import stamps `embed_skip` / `content_flag` (with an `assessed_at` time) into+ * the frontmatter of a page over content_sanity.bytes_block (24 MiB), so above it only the body round-trips exactly.+ */+const bodyOf = (file: Buffer) => file.subarray(file.indexOf('\n---\n\n', 4) + 6);+const dir = realpathSync(mkdtempSync(join(tmpdir(), 'large-pages-export-')));+afterAll(() => rmSync(dir, { recursive: true, force: true }));++function seeded(seed: number): () => number {+ let state = seed;+ return () => { state = (state * 1103515245 + 12345) & 0x7fffffff; return state / 0x7fffffff; };+}++/** A page file with frontmatter, facts, takes, keys, code and a timeline; not yet in canonical form. */+function pageFile(bytes: number, seed: number): string {+ return `---\ntype: note\ntitle: Large export\n---\n\n${bigPage(seeded(seed), bytes)}\n\n<!-- timeline -->\n\n${TIMELINE}\n`;+}++async function quietly<T>(fn: () => Promise<T>): Promise<T> {+ const { log, error } = console;+ const exit = process.exit;+ const messages: string[] = [];+ console.log = console.error = (...args: unknown[]) => { messages.push(args.join(' ')); };+ process.exit = ((code: number) => { throw new Error(`EXIT:${code} ${messages.join('\n')}`); }) as never;+ try { return await fn(); } finally { console.log = log; console.error = error; process.exit = exit; }+}++let exports = 0;+async function exportPage(engine: BrainEngine, args: string[] = []): Promise<Buffer> {+ const out = join(dir, `out-${++exports}`);+ await quietly(() => runExport(engine, ['--dir', out, ...args]));+ expect(readFileSync(join(out, '.gbrain-export-status'), 'utf8')).toEndWith('COMPLETE\n');+ return readFileSync(join(out, `${SLUG}.md`));+}++async function importAs(engine: BrainEngine, storage: 'on' | 'off', file: string): Promise<string> {+ await engine.executeRaw('DELETE FROM pages');+ await engine.setConfig('pages.segmented_storage', storage);+ const bodyPolicy = await readPageBodyPolicy(engine);+ const result = await quietly(() => importFromFile(engine, file, `${SLUG}.md`, { noEmbed: true, bodyPolicy }));+ expect(result.error ?? null).toBeNull();+ expect(result.status).toBe("imported");+ const [row] = await engine.executeRaw<{ body_storage: string }>('SELECT body_storage FROM pages WHERE slug=$1', [SLUG]);+ return row!.body_storage;+}++for (const backend of testBackends()) describe(`large-page export: ${backend}`, () => {+ let engine: BrainEngine;+ beforeAll(async () => {+ engine = backend === 'postgres' ? new PostgresEngine() : new PGLiteEngine();+ await engine.connect(backend === 'postgres' ? { database_url: requirePostgresTestDatabase() } : {});+ await engine.initSchema();+ }, 120_000);+ afterAll(async () => {+ await engine.executeRaw("DELETE FROM fact_withdrawals WHERE source_id='default'");+ await engine.executeRaw('DELETE FROM pages');+ await engine.setConfig('pages.segmented_storage', 'off');+ await engine.disconnect();+ });++ test.each([2, 20])('%i MiB: inline and segmented export the same canonical file, and export(import(F)) == F', async size => {+ const raw = join(dir, `${backend}-${size}-raw.md`);+ writeFileSync(raw, pageFile(size * MiB, size));+ expect(await importAs(engine, 'off', raw)).toBe('inline');+ const canonical = await exportPage(engine);+ const page = (await engine.getPage(SLUG))!;+ expect(sha(canonical)).toBe(sha(serializePageToMarkdown(page, await engine.getTags(SLUG))));+ const file = join(dir, `${backend}-${size}-canonical.md`);+ writeFileSync(file, canonical);++ expect(await importAs(engine, 'on', file)).toBe('segmented');+ const segmented = await exportPage(engine);+ expect(sha(segmented)).toBe(sha(canonical));+ expect(await importAs(engine, 'off', file)).toBe('inline');+ expect(sha(await exportPage(engine))).toBe(sha(canonical));++ await engine.executeRaw("INSERT INTO fact_withdrawals (source_id, visibility, fact_hash) VALUES ('default', 'world', gbrain_fact_fingerprint('likes tea'))");+ try {+ const struck = await exportPage(engine);+ expect(struck.equals(canonical)).toBe(false);+ expect(await importAs(engine, 'on', file)).toBe('segmented');+ expect(sha(await exportPage(engine))).toBe(sha(struck));+ } finally { await engine.executeRaw("DELETE FROM fact_withdrawals WHERE source_id='default'"); }+ }, 600_000);++ test('a segmented page over the payload limit refuses the whole export; a streamed page extends the snapshot deadline', async () => {+ const file = join(dir, `${backend}-limit.md`);+ writeFileSync(file, pageFile(2 * MiB, 3));+ expect(await importAs(engine, 'on', file)).toBe('segmented');+ const [{ body_bytes: stored }] = await engine.executeRaw<{ body_bytes: number }>('SELECT body_bytes FROM pages WHERE slug=$1', [SLUG]);+ await engine.executeRaw('UPDATE pages SET body_bytes=$2 WHERE slug=$1', [SLUG, 300 * MiB]);+ try {+ await expect(exportPage(engine)).rejects.toThrow('Export page payload limit exceeded');+ } finally { await engine.executeRaw('UPDATE pages SET body_bytes=$2 WHERE slug=$1', [SLUG, stored]); }++ const query = engine.executeRaw, now = Date.now;+ engine.executeRaw = async function (sql, params, options) {+ if (sql.includes('AS export_tags')) {+ const late = now() + EXPORT_SNAPSHOT_MS + 1000;+ Date.now = () => late;+ }+ return query.call(this, sql, params, options) as never;+ };+ try {+ expect((await exportPage(engine)).length).toBeGreaterThan(2 * MiB);+ } finally { engine.executeRaw = query; Date.now = now; }+ }, 300_000);++ test.skipIf(backend !== 'pglite')('streamed ingest drops leading and trailing body whitespace like parseMarkdown, so export(import(F + whitespace)) has the body of F', async () => {+ const head = serializeMarkdown({}, '', '', { type: 'note', title: 'Large export', tags: [] }).slice(0, -1);+ const body = conversationBody(PAGE_MAX_BYTES + MiB, { seed: 5 });+ const canonical = `${head}${body}\n\n<!-- timeline -->\n\n${TIMELINE}\n`;+ const padded = join(dir, 'padded.md');+ writeFileSync(padded, `${head}\n \n\t\n${body} \t\n\n \n\n<!-- timeline -->\n\n${TIMELINE}\n\n \n`);+ expect(await importAs(engine, 'on', padded)).toBe('segmented');+ const exported = await exportPage(engine);+ expect(sha(bodyOf(exported))).toBe(sha(bodyOf(Buffer.from(canonical))));+ }, 600_000);+});++describe.skipIf(testBackends().includes('postgres') && !testBackends().includes('pglite'))('PGLite backup of a segmented page', () => {+ test('restores the page so it exports the same bytes', async () => {+ const root = join(dir, 'backup-root');+ mkdirSync(join(root, '.gbrain'), { recursive: true });+ const database = join(root, '.gbrain', 'brain.pglite');+ writeFileSync(join(root, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: database }));+ const file = join(dir, 'backup-page.md');+ writeFileSync(file, pageFile(2 * MiB, 11));+ const withBrain = async <T>(path: string, fn: (engine: PGLiteEngine) => Promise<T>): Promise<T> => {+ const engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite', database_path: path });+ try { return await fn(engine); } finally { await engine.disconnect(); }+ };+ const before = await withBrain(database, async engine => {+ await engine.initSchema();+ expect(await importAs(engine, 'on', file)).toBe('segmented');+ return exportPage(engine);+ });+ const archive = join(dir, 'segmented.gbrain-backup');+ await createPgliteBackup({ root, output: archive });+ const restored = join(dir, 'restored-root');+ await restorePgliteBackup({ archive, into: restored });+ const after = await withBrain(join(restored, '.gbrain', 'brain.pglite'), async engine => {+ const [row] = await engine.executeRaw<{ body_storage: string }>('SELECT body_storage FROM pages WHERE slug=$1', [SLUG]);+ expect(row?.body_storage).toBe('segmented');+ return exportPage(engine);+ });+ expect(sha(after)).toBe(sha(before));+ }, 600_000);+});++const CHILD = `+import { readFileSync, writeFileSync } from 'node:fs';+import { PGLiteEngine } from ${JSON.stringify(join(REPO, 'src/core/pglite-engine.ts'))};+import { importFromFile } from ${JSON.stringify(join(REPO, 'src/core/import-file.ts'))};+import { readPageBodyPolicy } from ${JSON.stringify(join(REPO, 'src/core/page-body/limits.ts'))};+import { runExport } from ${JSON.stringify(join(REPO, 'src/commands/export.ts'))};+const [mode, brain, file, out] = process.argv.slice(-4);+const engine = new PGLiteEngine();+await engine.connect({ engine: 'pglite', database_path: brain });+await engine.initSchema();+let result = null;+if (mode === 'import') {+ await engine.setConfig('pages.segmented_storage', 'on');+ result = await importFromFile(engine, file, ${JSON.stringify(`${SLUG}.md`)}, { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) });+ result = { status: result.status, error: result.error ?? null };+} else {+ console.log = () => {};+ writeFileSync('/proc/self/clear_refs', '5');+ await runExport(engine, ['--dir', out]);+}+const peak = Number(/^VmHWM:\\s+(\\d+) kB$/m.exec(readFileSync('/proc/self/status', 'utf8'))[1]) / 1024;+await engine.disconnect();+process.stdout.write(JSON.stringify({ result, peak }) + '\\n');+`;++/** A canonical page file whose body is at most `bytes`, written in pieces; returns the sha256 of its body (bodyOf). */+function writeCanonical(path: string, bytes: number): string {+ const hash = createHash('sha256');+ const fd = openSync(path, 'w');+ const write = (text: string) => { hash.update(text); writeSync(fd, text); };+ try {+ writeSync(fd, serializeMarkdown({}, '', '', { type: 'note', title: 'Large export', tags: [] }).slice(0, -1));+ for (let at = 0, part = 0; ; part++) {+ const piece = (part ? '\n\n' : '') + conversationBody(Math.min(4 * MiB, bytes - at - 16), { seed: part + 1 });+ if (at + Buffer.byteLength(piece) > bytes) break;+ write(piece);+ at += Buffer.byteLength(piece);+ }+ write(`\n\n<!-- timeline -->\n\n${TIMELINE}\n`);+ } finally { closeSync(fd); }+ return hash.digest('hex');+}++function child(mode: 'import' | 'export', brain: string, file: string, out: string): { result: { status: string; error: string | null } | null; peak: number } {+ const script = join(dir, 'child.ts');+ writeFileSync(script, CHILD);+ const run = spawnSync(process.execPath, [script, mode, brain, file, out], { cwd: REPO, encoding: 'utf8', timeout: 1_500_000, maxBuffer: 16 * MiB });+ if (run.status !== 0) throw new Error(`${mode} child failed (${run.status} ${run.signal}): ${run.stderr.slice(-4000)}`);+ return JSON.parse(run.stdout.trim().split('\n').pop()!);+}++describe.skipIf(process.env.GBRAIN_TEST_LARGE_EXPORT !== '1' || process.platform !== 'linux')('128 MiB export memory (PGLite)', () => {+ test('exports a 128 MiB page with the body of F and peak memory independent of the page size', () => {+ const measure = (name: string, bytes: number) => {+ const file = join(dir, `${name}.md`);+ const expected = writeCanonical(file, bytes);+ const brain = join(dir, `${name}.pglite`);+ expect(child('import', brain, file, '').result).toEqual({ status: 'imported', error: null });+ rmSync(file);+ const out = join(dir, `${name}-out`);+ const { peak } = child('export', brain, file, out);+ expect(sha(bodyOf(readFileSync(join(out, `${SLUG}.md`))))).toBe(expected);+ rmSync(out, { recursive: true, force: true });+ rmSync(brain, { recursive: true, force: true });+ return peak;+ };+ const small = measure('small', 2 * MiB);+ const large = measure('large', 128 * MiB - 64 * 1024);+ console.log(JSON.stringify({ smallPeakMiB: Math.round(small), largePeakMiB: Math.round(large) }));+ expect(large - small).toBeLessThan(80);+ }, 1_800_000);+});diff --git a/test/export-stage.test.ts b/test/export-stage.test.tsindex 77d64ce166..441e1de01f 100644--- a/test/export-stage.test.ts+++ b/test/export-stage.test.ts@@ -1,5 +1,7 @@import { expect, test } from 'bun:test';-import { ExportStage, EXPORT_PAYLOAD_LIMIT, EXPORT_STAGE_LIMIT, exportPathKey } from '../src/core/export-stage.ts';+import { readFileSync } from 'node:fs';+import { ExportStage, EXPORT_PAYLOAD_LIMIT, EXPORT_STAGE_LIMIT, exportPathKey, exportPayloadLimit } from '../src/core/export-stage.ts';+import { PAGE_MAX_BYTES } from '../src/core/page-size-policy.ts';test('manifest rejects unsafe paths and conservatively folds Unicode aliases', () => {for (const path of ['../escape.md', '/absolute.md', 'a//b.md', 'a/../b.md', 'a\\b.md', 'nul.md', 'a\0b.md', 'a/./b.md', '\ud800.md', 'a'.repeat(241) + '.md']) {@@ -37,3 +39,24 @@ test('deep paths use a bounded iterative manifest walk and reserved markers cannexpect(() => stage.add('notes/.raw/item.json/leaf.md', 'file', 'payload')).toThrow('collision');} finally { stage.close(); }});+test('the payload limit is the page ceiling plus the 32 MiB limit\'s metadata headroom, never below 32 MiB', () => {+ expect(exportPayloadLimit(PAGE_MAX_BYTES)).toBe(EXPORT_PAYLOAD_LIMIT);+ expect(exportPayloadLimit(1024 * 1024)).toBe(EXPORT_PAYLOAD_LIMIT);+ expect(exportPayloadLimit(256 * 1024 * 1024)).toBe(256 * 1024 * 1024 + EXPORT_PAYLOAD_LIMIT - PAGE_MAX_BYTES);+});+test('streamed stage files are written piece by piece to the stage directory and refuse capacity without truncating', async () => {+ const stage = new ExportStage();+ const pieces = async function* (...parts: Array<string | Uint8Array>) { yield* parts; };+ const files = () => stage.db.query<{ path: string; file: string | null }, []>("SELECT path, file FROM paths WHERE kind='file'").all();+ try {+ await stage.addStream('notes/big.md', 10, 64, pieces('head\n', Buffer.from('ü body'), '\n'));+ expect(files()).toEqual([{ path: 'notes/big.md', file: '0' }]);+ expect(readFileSync(stage.filePath('0'), 'utf8')).toBe('head\nü body\n');+ expect(stage.fileBytes).toBe(Buffer.byteLength('head\nü body\n'));+ await expect(stage.addStream('notes/over.md', 65, 64, pieces('x'))).rejects.toThrow('capacity');+ await expect(stage.addStream('notes/disk.md', Number.MAX_SAFE_INTEGER, Infinity, pieces('x'))).rejects.toThrow('capacity');+ expect(files()).toHaveLength(1);+ await expect(stage.addStream('notes/grew.md', 4, 8, pieces('12345', '6789'))).rejects.toThrow('capacity');+ await expect(stage.addStream('Notes/Big.md', 1, 64, pieces('x'))).rejects.toThrow('collision');+ } finally { stage.close(); }+});diff --git a/test/native-export-publication.test.ts b/test/native-export-publication.test.tsindex 5c70050744..d20acd86a0 100644--- a/test/native-export-publication.test.ts+++ b/test/native-export-publication.test.ts@@ -138,6 +138,37 @@ describe('native export publication', () => {expect(readFileSync(join(root, marker), 'utf8')).toBe(incomplete);});+ test('publishes a staged file by path in bounded reads, byte for byte, across several read buffers', async () => {+ const stage = temporary();+ const root = join(temporary(), 'out');+ const bytes = Buffer.alloc(3 * 1024 * 1024 + 7);+ for (let i = 0; i < bytes.length; i++) bytes[i] = (i * 31 + (i >> 11)) & 255;+ writeFileSync(join(stage, 'page.md'), bytes);+ writeFileSync(join(stage, 'empty.md'), '');+ const { publisher, handle } = await begin(root);+ publisher.publishExportFileFrom(handle, 'notes/ü.md', join(stage, 'page.md'));+ publisher.publishExportFileFrom(handle, 'empty.md', join(stage, 'empty.md'));+ publisher.completeExport(handle);+ expect(readFileSync(join(root, 'notes/ü.md')).equals(bytes)).toBe(true);+ expect(readFileSync(join(root, 'empty.md')).length).toBe(0);+ expect(readdirSync(join(root, 'notes'))).toEqual(['ü.md']);+ expect(readFileSync(join(stage, 'page.md')).equals(bytes)).toBe(true);+ });++ test.skipIf(process.platform === 'win32').each(['relative', 'missing', 'directory', 'symlink'])('a %s staged source refuses without a leaf and poisons completion', async kind => {+ const stage = temporary();+ const root = temporary();+ writeFileSync(join(stage, 'real.md'), 'staged bytes');+ mkdirSync(join(stage, 'dir'));+ symlinkSync(join(stage, 'real.md'), join(stage, 'link.md'));+ const source = { relative: 'real.md', missing: join(stage, 'absent.md'), directory: join(stage, 'dir'), symlink: join(stage, 'link.md') }[kind]!;+ const { publisher, handle } = await begin(root);+ expect(() => publisher.publishExportFileFrom(handle, 'page.md', source)).toThrow();+ expect(() => publisher.completeExport(handle)).toThrow();+ expect(readdirSync(root)).toEqual([marker]);+ expect(readFileSync(join(root, marker), 'utf8')).toBe(incomplete);+ });+test('rejects a nonbuffer without permitting completion', async () => {const { publisher, handle } = await begin(temporary());expect(() => publisher.publishExportFile(handle, 'file', 'text' as unknown as Buffer)).toThrow();