Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Lane 2a: read-cost on work counters and a bytes-read spy; incremental outline line lookups
garrytana7bd667cdd15
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.mdindex 7d9b7bbbc4..a2a165a611 100644--- a/docs/architecture/key-files/core-services-2-continued.md+++ b/docs/architecture/key-files/core-services-2-continued.md@@ -22,4 +22,4 @@ The page-state concurrency foundation under `src/core/page-state/` and the share- `src/core/page-window/bounded-lead.ts` — leads, snippets and synopses read a bounded prefix, never the whole body: fan-out SQL selects `boundedBodyPrefixSql(alias)` (`left(coalesce(alias.compiled_truth, alias.truth_lead), 65536)`: a segmented page's NULL body falls back to its stored lead; the one COALESCE of body and lead the page body reader ratchet allows by name), `boundedRawPrefix` cuts a body at 64 KiB on a code point, and `overlaidBoundedRows` / `overlaidBoundedPrefix` replace a prefix holding a `gbrain:facts:begin` marker with the prefix of the withdrawal-overlaid body (one batched `readPageSnapshotsBatch` read; a page it no longer returns, or a failed read, gets an empty lead). A segmented page's row carries its stored `truth_lead`; when that lead holds a facts fence it is overlaid alone with the withdrawal ledger the snapshot read returns (`overlayCanonicalBodies`, then the same 64 KiB cut), never by reading segments. `pageLeadSource` gives getPage callers (exact-slug and alias snippets) a page's compiled truth, or a segmented page's `truth_lead` without touching its throwing body getters. `projectedLead` is that prefix through `boundedProjectedPrefix` (`document.ts`). Consumers: the exact-slug tier (`exact-lookup.ts`) and alias injection (`alias-hop.ts`) snippets, relational hydrate, the reflex pointer synopsis (`retrieval-reflex.ts` `safeSynopsis`: world-only reads take the projected prefix, the trusted entity-card widening the raw prefix through its own fence strip), the entity card's hit row and `entity names` leads, and think's anchor and window-floor rows (`think/gather.ts`: the raw overlaid prefix for the trusted local CLI, the projected prefix otherwise). Small pages render as before. Pinned by `test/bounded-lead.test.ts` and `test/large-pages/segmented-leads.test.ts`.- `src/core/page-window/document.ts` — the one read projection every remote window, outline and lead slices: `projectPageText` (fence overlay split, `sanitizeRemoteBody` + `credentialSafeProjection`, timeline after `TIMELINE_SEPARATOR`), `pageDocument` / `readPageDocument` (UTF-8 bytes + timeline byte offset, with the page's fence overlay), `chunkDocumentSpan` + `spanHoldsChunk` (a chunk's stored `projected_byte_*` span mapped into the document and verified), `boundedProjectedPrefix`, `locateChunksByStoredSpans` (byte spans to string offsets in one pass), `DEFAULT_INLINE_BODY_BYTES` (256 KB).- `src/core/page-window/window.ts` — byte/line window arithmetic on a UTF-8 buffer: windows snap to code points and line starts (`windowFrom`, `windowForLines`, `windowForBytes`, `windowAround`; a lone line longer than the window is cut on a code point as `forced_cut`), `pageOutline` (single pass: ATX headings outside code fences, or 64 KiB blocks for pages with fewer than two headings, with date ranges, paged by `from`/`limit`), and the opaque revision-bound cursor (`gpw1.`). `DocumentSlab` / `slabWindow` run the same arithmetic on a slice of a larger document and shift the result back to document coordinates.-- `src/core/page-window/segmented.ts` — Wave B PR 2 (spec 7.2, 7.4): get_page over a segmented page in projected bytes, the same coordinates as an inline page. `SegmentedDocument` places units (segments from `projectedUnits` plus fixed text) by stored sums and reads only the units a window, line lookup or `around_chunk_id` touches (`slab` adds `EDGE` bytes so code-point and line snapping match the inline arithmetic). `segmentedReadDocument` is the read projection; `segmentedMarkdownDocument` the markdown view (`markdownHead`, then the projection for a remote caller, the overlaid stored body and `TIMELINE_SEPARATOR` for a trusted one). `page_view_digests` (migration v250) caches per page revision, view and audience the read view's line count and the markdown view's size and sha256, checked against the current total. `tailDigest` hashes the last `TAIL_BYTES` raw bytes of the last region, withheld from a remote caller when those rows hold a protected or facts region. `segmentedOutline` pages headings from stored metadata, reading at most `OUTLINE_READ_BYTES` of segments per page. `cli/page-render.ts` uses it for the local `gbrain get` stream (`streamSegmentedGet`); the thin client pages and verifies the markdown view (`printPagedPage`), and `--json` above `PAGE_MAX_BYTES` is refused on both paths. Pinned by `test/large-pages/segmented-get-page-parity.test.ts`, `read-cost.test.ts`, `remote-get-page-privacy.test.ts`, `segmented-get-cli.test.ts` and `segmented-get-over-ceiling.test.ts`.+- `src/core/page-window/segmented.ts` — Wave B PR 2 (spec 7.2, 7.4): get_page over a segmented page in projected bytes, the same coordinates as an inline page. `SegmentedDocument` places units (segments from `projectedUnits` plus fixed text) by stored sums and reads only the units a window, line lookup or `around_chunk_id` touches (`slab` adds `EDGE` bytes so code-point and line snapping match the inline arithmetic). `segmentedReadDocument` is the read projection; `segmentedMarkdownDocument` the markdown view (`markdownHead`, then the projection for a remote caller, the overlaid stored body and `TIMELINE_SEPARATOR` for a trusted one). `page_view_digests` (migration v250) caches per page revision, view and audience the read view's line count and the markdown view's size and sha256, checked against the current total. `tailDigest` hashes the last `TAIL_BYTES` raw bytes of the last region, withheld from a remote caller when those rows hold a protected or facts region. `segmentedOutline` pages headings from stored metadata, reading at most `OUTLINE_READ_BYTES` of segments per page and carrying line counts forward between entries. `segmentedReadWork` (@internal) counts the units and segment bytes a read visits, for the read-cost bounds. `cli/page-render.ts` uses it for the local `gbrain get` stream (`streamSegmentedGet`); the thin client pages and verifies the markdown view (`printPagedPage`), and `--json` above `PAGE_MAX_BYTES` is refused on both paths. Pinned by `test/large-pages/segmented-get-page-parity.test.ts`, `read-cost.test.ts`, `remote-get-page-privacy.test.ts`, `segmented-get-cli.test.ts` and `segmented-get-over-ceiling.test.ts`.diff --git a/src/core/page-body/read-range.ts b/src/core/page-body/read-range.tsindex eb9e40e84b..ad75a8f367 100644--- a/src/core/page-body/read-range.ts+++ b/src/core/page-body/read-range.ts@@ -127,6 +127,7 @@ export interface BodyRangePiece {const utf8 = new TextDecoder('utf-8', { fatal: true });const HEAVY_BATCH = 64;const toJson = (v: unknown) => typeof v === 'string' ? JSON.parse(v) as unknown : v;+const bytesOf = (v: unknown): Uint8Array => { const b = v as Uint8Array; return new Uint8Array(b.buffer, b.byteOffset, b.byteLength); };const newlines = (s: string) => { let n = 0; for (let i = s.indexOf('\n'); i !== -1; i = s.indexOf('\n', i + 1)) n++; return n; };export async function openSegmentedBody(engine: BrainEngine, opts: { pageId: number; generation?: number; ledger?: BodyLedger }): Promise<SegmentedBody> {@@ -134,15 +135,11 @@ export async function openSegmentedBody(engine: BrainEngine, opts: { pageId: numbody_flags, segmenter_version FROM pages WHERE id=$1`, [opts.pageId]);if (!page || page.body_storage !== 'segmented') throw new Error(`Page ${opts.pageId} is not a segmented page.`);const generation = opts.generation ?? Number(page.body_generation);- // One JSON row instead of one result row per segment: PGLite spends about 10 us per result row, and these sums are- // all a body: 'none' read of a large page costs beyond a constant.- const [listed] = await engine.executeRaw<{ rows: unknown }>(`SELECT coalesce(json_agg(json_build_object('seq', m.seq, 'occurrence_id', m.occurrence_id,- 'region', m.region, 'sha256', encode(m.sha256, 'hex'), 'byte_start', m.byte_start, 'byte_len', m.byte_len, 'line_start', m.line_start,- 'line_count', m.line_count, 'static_proj_bytes', m.static_proj_bytes, 'static_proj_lines', m.static_proj_lines, 'outline_count', jsonb_array_length(m.outline),- 'has_facts', jsonb_array_length(m.facts_slots) > 0, 'has_date', m.date_min IS NOT NULL) ORDER BY m.seq), '[]') AS rows+ const rows = await engine.executeRaw<Record<string, unknown>>(`SELECT m.seq, m.occurrence_id, m.region, m.sha256, m.byte_start, m.byte_len,+ m.line_start, m.line_count, m.static_proj_bytes, m.static_proj_lines, jsonb_array_length(m.outline) AS outline_count,+ jsonb_array_length(m.facts_slots) > 0 AS has_facts, m.date_min IS NOT NULL AS has_dateFROM page_body_manifest m- WHERE m.page_id=$1 AND m.staging_id IS NULL AND m.gen_from<=$2 AND (m.gen_to IS NULL OR m.gen_to>$2)`, [opts.pageId, generation]);- const rows = toJson(listed?.rows ?? '[]') as Array<Record<string, unknown>>;+ WHERE m.page_id=$1 AND m.staging_id IS NULL AND m.gen_from<=$2 AND (m.gen_to IS NULL OR m.gen_to>$2) ORDER BY m.seq`, [opts.pageId, generation]);const slug = String(page.slug);const sourceId = String(page.source_id);const ledger = opts.ledger ?? await readBodyLedger(engine, sourceId, slug);@@ -150,7 +147,7 @@ export async function openSegmentedBody(engine: BrainEngine, opts: { pageId: numpageId: opts.pageId, sourceId, slug, generation, bodyBytes: Number(page.body_bytes ?? 0), bodyLines: Number(page.body_lines ?? 0), truthBytes: Number(page.truth_bytes ?? 0),flags: (toJson(page.body_flags) ?? {}) as JsonObject, ledger, stale: Number(page.segmenter_version) !== SEGMENTER_VERSION,rows: rows.map(r => ({- seq: Number(r.seq), occurrenceId: Number(r.occurrence_id), region: r.region as BodyRegion, sha256: new Uint8Array(Buffer.from(String(r.sha256), 'hex')),+ seq: Number(r.seq), occurrenceId: Number(r.occurrence_id), region: r.region as BodyRegion, sha256: bytesOf(r.sha256),byteStart: Number(r.byte_start), byteLen: Number(r.byte_len), lineStart: Number(r.line_start), lineCount: Number(r.line_count), staticProjBytes: Number(r.static_proj_bytes),staticProjLines: Number(r.static_proj_lines), outlineCount: Number(r.outline_count), hasFacts: r.has_facts === true, hasDate: r.has_date === true,})),diff --git a/src/core/page-window/segmented.ts b/src/core/page-window/segmented.tsindex 3a8f07b05c..111f97405e 100644--- a/src/core/page-window/segmented.ts+++ b/src/core/page-window/segmented.ts@@ -47,6 +47,13 @@ const OUTLINE_READ_BYTES = 4 * 1024 * 1024;const TAIL_BYTES = 4096;const NL = 0x0a;+/**+ * @internal Deterministic work counters (test/large-pages/read-cost.test.ts): `units` counts document units and+ * manifest rows a read visits, `bytes` the segment text it reads or scans. A read's bytes stay bounded by what it+ * returns; its units grow with the segment count, never with the bytes.+ */+export const segmentedReadWork = { units: 0, bytes: 0 };+export interface DocumentUnit {start: number;bytes: number;@@ -59,6 +66,7 @@ export interface DocumentUnit {type Reader = (start: number, end: number) => Promise<Buffer>;function newlinesIn(b: Uint8Array): number {+ segmentedReadWork.bytes += b.length;let n = 0;for (let i = b.indexOf(NL); i !== -1; i = b.indexOf(NL, i + 1)) n++;return n;@@ -82,9 +90,12 @@ function unitAt(units: readonly DocumentUnit[], b: number): number {export class SegmentedDocument {readonly newlines: number;private readonly before: number[];+ private readonly reader: Reader;constructor(readonly engine: BrainEngine, readonly body: SegmentedBody, readonly total: number, readonly units: readonly DocumentUnit[],- private readonly reader: Reader, readonly timelineByte = -1) {+ reader: Reader, readonly timelineByte = -1) {+ this.reader = async (start, end) => { const b = await reader(start, end); segmentedReadWork.bytes += b.length; return b; };+ segmentedReadWork.units += units.length;let n = 0;this.before = units.map(u => { const at = n; n += u.newlines; return at; });this.newlines = n;@@ -137,6 +148,7 @@ export class SegmentedDocument {*/async aroundChunk(chunk: { occurrence_id: number; projected_byte_start: number | null; projected_byte_end: number | null; chunk_text: string },contextLines: number, maxBytes: number): Promise<{ window: WindowSlice; span: { start: number; end: number } } | null> {+ segmentedReadWork.units += this.units.length;const unit = this.units.find(u => u.row >= 0 && this.body.rows[u.row]!.occurrenceId === chunk.occurrence_id);const s0 = chunk.projected_byte_start, e0 = chunk.projected_byte_end;if (!unit || s0 == null || e0 == null || !(e0 > s0) || s0 < 0 || e0 > unit.bytes) return null;@@ -152,6 +164,7 @@ export class SegmentedDocument {const want = line - 1;if (want <= 0) return 0;for (let i = 0; i < this.units.length; i++) {+ segmentedReadWork.units++;const u = this.units[i]!;if (this.before[i]! + u.newlines < want) continue;const buf = await this.readUnit(i);@@ -165,12 +178,6 @@ export class SegmentedDocument {return this.total;}- /** 1-based line of byte `b`, from the newline sums and the text of the unit holding it. */- lineAt(b: number, text: Buffer): number {- const i = this.unitAt(b);- return i < 0 ? 1 : 1 + this.before[i]! + newlinesIn(text.subarray(0, b - this.units[i]!.start));- }-linesBefore(i: number): number { return this.before[i] ?? this.newlines; }/** totalLines: the newline sums plus whether the last byte is a newline (reads the last unit). */@@ -234,6 +241,7 @@ export async function segmentedMarkdownDocument(engine: BrainEngine, body: Segme};} else {const measured = new Map<number, { bytes: number; newlines: number }>();+ segmentedReadWork.units += body.rows.length;if (ledgerApplies(body.ledger)) {for (const [i, row] of body.rows.entries()) {if (!row.hasFacts) continue;@@ -320,6 +328,7 @@ export async function readViewLines(doc: SegmentedDocument, revision: string): P* caller gets it only when those rows hold no protected or facts region: a hash of hidden text is a guessing oracle.*/export async function tailDigest(engine: BrainEngine, body: SegmentedBody, remote: boolean): Promise<{ tail_sha256: string; tail_region: string } | Record<string, never>> {+ segmentedReadWork.units += body.rows.length;const region = body.rows.some(r => r.region === 'timeline' && r.byteLen > 0) ? 'timeline' : 'truth';const rows = body.rows.filter(r => r.region === region);const tail: typeof rows = [];@@ -333,6 +342,7 @@ export async function tailDigest(engine: BrainEngine, body: SegmentedBody, remot}const texts = await engine.readSegmentTexts(body.sourceId, tail.map(r => r.sha256));const raw = Buffer.concat(tail.map(r => texts.get(Buffer.from(r.sha256).toString('hex')) ?? new Uint8Array()));+ segmentedReadWork.bytes += raw.length;return { tail_sha256: createHash('sha256').update(raw.subarray(Math.max(0, raw.length - TAIL_BYTES))).digest('hex'), tail_region: region };}@@ -392,6 +402,7 @@ export async function segmentedOutline(doc: SegmentedDocument, from: number, limconst interior: number[] = [];for (let k = 0; k < count; k++) {for (let i = doc.unitAt(bounds[k]!.start); i <= doc.unitAt(end(k) - 1); i++) {+ segmentedReadWork.units++;const row = doc.units[i]!.row;if (row < 0 || reads.has(i)) continue;if (body.rows[row]!.hasFacts) reads.add(i); else interior.push(row);@@ -401,21 +412,32 @@ export async function segmentedOutline(doc: SegmentedDocument, from: number, limfor (const i of reads) texts.set(i, await doc.readUnit(i));const dates = await storedDates(doc, interior);const textOf = async (i: number) => texts.get(i) ?? await doc.readUnit(i);- const lineAt = async (b: number) => doc.lineAt(b, await textOf(doc.unitAt(b)));+ // Entries come in byte order: carry the count from the previous byte in the same unit instead of rescanning it.+ let last = { unit: -1, at: 0, line: 0 };+ const lineAt = async (b: number) => {+ const i = doc.unitAt(b);+ if (i < 0) return 1;+ const text = await textOf(i);+ const from = last.unit === i && b >= last.at ? last : { unit: i, at: doc.units[i]!.start, line: 1 + doc.linesBefore(i) };+ last = { unit: i, at: b, line: from.line + newlinesIn(text.subarray(from.at - doc.units[i]!.start, b - doc.units[i]!.start)) };+ return last.line;+ };const entries: OutlineEntry[] = [];for (let k = 0; k < count; k++) {const { start, heading, level } = bounds[k]!;const stop = end(k);const range = new DateRange();for (let i = doc.unitAt(start); i <= doc.unitAt(stop - 1); i++) {+ segmentedReadWork.units++;const u = doc.units[i]!;if (u.row >= 0 && !texts.has(i)) {const d = dates.get(u.row);if (d) range.add(d.min, d.max);continue;}- const text = await textOf(i);- range.scan(text.subarray(Math.max(start, u.start) - u.start, Math.min(stop, u.start + u.bytes) - u.start).toString('utf8'));+ const slice = (await textOf(i)).subarray(Math.max(start, u.start) - u.start, Math.min(stop, u.start + u.bytes) - u.start);+ segmentedReadWork.bytes += slice.length;+ range.scan(slice.toString('utf8'));}const lineStart = await lineAt(start);entries.push({@@ -431,6 +453,7 @@ async function blankBefore(doc: SegmentedDocument, b: number): Promise<boolean>const last = doc.unitAt(b);let reads = 0;for (let i = 0; i <= last; i++) {+ segmentedReadWork.units++;const u = doc.units[i]!;const upTo = Math.min(u.bytes, b - u.start);if (upTo <= 0) continue;@@ -442,17 +465,21 @@ async function blankBefore(doc: SegmentedDocument, b: number): Promise<boolean>async function blocksOutline(doc: SegmentedDocument, from: number, limit: number, totalLines: number): Promise<PageOutline> {const starts: number[] = [];+ segmentedReadWork.units += doc.units.length;for (const u of doc.units) if (u.row >= 0 && u.bytes > 0) starts.push(starts.length ? u.start : 0);if (!starts.length && doc.total > 0) starts.push(0);const page = starts.slice(from, from + limit);const rows = new Set<number>();const end = (k: number) => starts[from + k + 1] ?? doc.total;- page.forEach((start, k) => { for (let i = doc.unitAt(start); i <= doc.unitAt(end(k) - 1); i++) if (doc.units[i]!.row >= 0) rows.add(doc.units[i]!.row); });+ page.forEach((start, k) => {+ for (let i = doc.unitAt(start); i <= doc.unitAt(end(k) - 1); i++) { segmentedReadWork.units++; if (doc.units[i]!.row >= 0) rows.add(doc.units[i]!.row); }+ });const dates = await storedDates(doc, [...rows]);const entries: OutlineEntry[] = page.map((start, k) => {const stop = end(k);const range = new DateRange();for (let i = doc.unitAt(start); i <= doc.unitAt(stop - 1); i++) {+ segmentedReadWork.units++;const u = doc.units[i]!;if (u.row < 0) range.scan(u.text!);else { const d = dates.get(u.row); if (d) range.add(d.min, d.max); }diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.jsonindex d61bff1845..940c4a6305 100644--- a/test/fixtures/goldens/doctor/content-pglite-human.json+++ b/test/fixtures/goldens/doctor/content-pglite-human.json@@ -72,7 +72,7 @@" [OK] pglite_scale: PGLite at 5 pages — comfortable below the 1000-page threshold"," [OK] rls: Skipped (PGLite — no PostgREST exposure, RLS not applicable)"," [OK] schema_version: Version <latest> (latest: <latest>)",- " [OK] schema_columns: 1191 column(s) verified against live schema",+ " [OK] schema_columns: 1199 column(s) verified against live schema"," [OK] rls_event_trigger: Skipped (PGLite — no event trigger support)"," [INFO] embeddings: Not applicable: embeddings are disabled on this brain (keyword search keeps working)."," [INFO] embedding_provider: Not probed: embeddings are disabled on this brain by choice (keyword search keeps working).",diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex 0cdb9a4448..a480c0d11a 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -914,7 +914,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "1191 column(s) verified against live schema",+ "message": "1199 column(s) verified against live schema","name": "schema_columns","status": "ok"},diff --git a/test/large-pages/read-cost.test.ts b/test/large-pages/read-cost.test.tsindex be7cc48dab..6f808780c9 100644--- a/test/large-pages/read-cost.test.ts+++ b/test/large-pages/read-cost.test.ts@@ -3,14 +3,15 @@* costs the size of what it returns, not the size of the page.** 1. Protects: body: 'none', the first outline page and a 40 KB window in the- * middle of a 10 MB and a 40 MB page take about the same CPU (median ratio- * of best-of-runs below 1.3; Wave A's whole-document path is about 4x), and- * a window reads at most the window plus two segments of segment text.+ * middle of a 10 MB and a 40 MB page load the same bounded segment text+ * (readSegmentTexts spy) and scan the same bounded bytes (segmentedReadWork,+ * deterministic counters), visit a few document units per segment and no+ * more, and a window reads at most the window plus two segments of text.* 2. Fails when: a read materializes or projects the whole body (Wave A's* readPageDocument / pageOutline over the full text), the line count reads* every segment, or a window loads segments it does not cut from.- * 3. PGLite only: PGLite runs its SQL on the calling thread, so thread CPU- * counts the database work too.+ * 3. PGLite only: one 10 MB and one 40 MB import; the counts do not depend on+ * the engine.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';@@ -21,11 +22,12 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { importFromFile } from '../../src/core/import-file.ts';import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';-import { cpuMsAsync } from '../helpers/cpu-time.ts';+import { segmentedReadWork } from '../../src/core/page-window/segmented.ts';const getPage = operations.find(o => o.name === 'get_page')!;const WINDOW = 40_000;-const REPEAT = 20;+/** segmented.ts's per-page cap on outline segment reads. */+const OUTLINE_READ_BYTES = 4 * 1024 * 1024;let engine: PGLiteEngine;let dir: string;@@ -51,22 +53,25 @@ const remote = (): OperationContext => ({ engine, config: {} as GBrainConfig, losourceId: 'default', allowedSources: ['default'] } } as unknown as OperationContext);const get = async (params: Record<string, unknown>) => await getPage.handler(remote(), params) as Record<string, any>;-/** cpuScalingRatio for async spans: median over rounds of best-of-runs large / best-of-runs small, after a warm-up of each. */-async function asyncScalingRatio(small: () => Promise<unknown>, large: () => Promise<unknown>, rounds = 5, runs = 3): Promise<number> {- await small();- await large();- const best = async (fn: () => Promise<unknown>) => {- let ms = Infinity;- for (let k = 0; k < runs; k++) ms = Math.min(ms, await cpuMsAsync(fn));- return ms;+/** Segment text a call loads from storage (readSegmentTexts) and the counted work, after one warm-up call fills the view caches. */+async function measure(call: () => Promise<unknown>): Promise<{ loaded: number; units: number; bytes: number }> {+ await call();+ const original = engine.readSegmentTexts.bind(engine);+ let loaded = 0;+ engine.readSegmentTexts = async (sourceId, hashes) => {+ const texts = await original(sourceId, hashes);+ for (const text of texts.values()) loaded += text.byteLength;+ return texts;};- const ratios: number[] = [];- for (let r = 0; r < rounds; r++) ratios.push(await best(large) / await best(small));- return ratios.sort((a, b) => a - b)[Math.floor(rounds / 2)]!;+ segmentedReadWork.units = 0;+ segmentedReadWork.bytes = 0;+ try { await call(); } finally { engine.readSegmentTexts = original; }+ return { loaded, ...segmentedReadWork };}describe('segmented get_page read cost', () => {- const pages = { small: { slug: 'logs/read-cost-10mb', bytes: 10_000_000, size: 0 }, large: { slug: 'logs/read-cost-40mb', bytes: 40_000_000, size: 0 } };+ const pages = { small: { slug: 'logs/read-cost-10mb', bytes: 10_000_000, size: 0, rows: 0 }, large: { slug: 'logs/read-cost-40mb', bytes: 40_000_000, size: 0, rows: 0 } };+ let segment = 0;beforeAll(async () => {engine = new PGLiteEngine();@@ -82,7 +87,12 @@ describe('segmented get_page read cost', () => {const none = await get({ slug: page.slug, body: 'none' });expect(none.body_storage).toBe('segmented');page.size = none.size.total_bytes;+ const [rows] = await engine.executeRaw<{ n: unknown; max: unknown }>(`SELECT count(*) AS n, max(m.byte_len) AS max FROM page_body_manifest m JOIN pages p ON p.id = m.page_id+ WHERE p.slug = $1 AND m.gen_to IS NULL`, [page.slug]);+ page.rows = Number(rows!.n);+ segment = Math.max(segment, Number(rows!.max));}+ expect(pages.large.rows).toBeGreaterThan(3 * pages.small.rows);}, 600_000);afterAll(async () => {@@ -90,23 +100,25 @@ describe('segmented get_page read cost', () => {rmSync(dir, { recursive: true, force: true });});- const reads: Array<[string, (slug: string, size: number) => Record<string, unknown>]> = [- ['body none', () => ({ body: 'none' })],- ['the first outline page', () => ({ body: 'outline' })],- ['a window in the middle', (_slug, size) => ({ body: 'window', bytes: { offset: Math.floor(size / 2), length: WINDOW } })],+ const reads: Array<[string, (size: number) => Record<string, unknown>, (segment: number) => number]> = [+ ['body none', () => ({ body: 'none' }), segment => 2 * segment],+ ['the first outline page', () => ({ body: 'outline' }), segment => OUTLINE_READ_BYTES + 2 * segment],+ ['a window in the middle', size => ({ body: 'window', bytes: { offset: Math.floor(size / 2), length: WINDOW } }), segment => WINDOW + 2 * segment],];- for (const [name, params] of reads) {- test(`${name}: 40 MB costs about what 10 MB costs`, async () => {- // Thread CPU ticks at a few ms, so one sample is REPEAT reads.- const read = (page: typeof pages.small) => async () => { for (let i = 0; i < REPEAT; i++) await get({ slug: page.slug, ...params(page.slug, page.size) }); };- const ratio = await asyncScalingRatio(read(pages.small), read(pages.large));- expect(ratio).toBeLessThan(1.3);+ for (const [name, params, bound] of reads) {+ test(`${name}: 40 MB loads and scans what 10 MB does`, async () => {+ const small = await measure(() => get({ slug: pages.small.slug, ...params(pages.small.size) }));+ const large = await measure(() => get({ slug: pages.large.slug, ...params(pages.large.size) }));+ for (const [page, m] of [[pages.small, small], [pages.large, large]] as const) {+ expect({ name, size: page.bytes, loaded: m.loaded <= bound(segment), scanned: m.bytes <= 3 * bound(segment), units: m.units <= 8 * page.rows + 64 })+ .toEqual({ name, size: page.bytes, loaded: true, scanned: true, units: true });+ }+ expect(large.loaded).toBeLessThanOrEqual(small.loaded + 2 * segment);+ expect(large.bytes).toBeLessThanOrEqual(small.bytes + 6 * segment);}, 300_000);}test('a window reads at most the window plus two segments of segment text', async () => {- const [largest] = await engine.executeRaw<{ n: unknown }>(`SELECT max(m.byte_len) AS n FROM page_body_manifest m JOIN pages p ON p.id = m.page_id WHERE p.slug = $1`, [pages.large.slug]);- const segment = Number(largest!.n);const original = engine.readSegmentTexts.bind(engine);let bytes = 0;engine.readSegmentTexts = async (sourceId, hashes) => {