@parcha/agentrun-import 0.1.0-beta.59 → 0.1.0-beta.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lines.js CHANGED
@@ -4,7 +4,9 @@
4
4
  // takes only the bytes written since.
5
5
  import { open } from "node:fs/promises";
6
6
  import { addRequest, counts, trimmed } from "./counts.js";
7
+ import { DROPS_CURSOR, NO_READ_AHEAD } from "./internal.js";
7
8
  import { rememberUser } from "./reader.js";
9
+ import { fieldsOf, scan } from "./scan.js";
8
10
  import { isObject, mostEffortOf, timeOf } from "./text.js";
9
11
  import { ACTIVE_GAP_MS } from "./types.js";
10
12
  /** The bytes a read takes from its file at once. */
@@ -39,10 +41,17 @@ async function markOf(handle, offset) {
39
41
  const { bytesRead } = await handle.read(bytes, 0, n, offset - n);
40
42
  return bytes.subarray(0, bytesRead).toString("base64");
41
43
  }
42
- /** Whether a read from `cursor` of the open file goes on from it: the same source and kind of read, the same file (device
43
- * and inode), no shorter, and the bytes before its offset as they were. Else it reads the file from its start. */
44
- async function goesOn(source, keep, totals, cursor, handle, stats) {
45
- return cursor.source === source && cursor.keep === keep && (cursor.totals ?? false) === totals && cursor.dev === stats.dev && cursor.ino === stats.ino && stats.size >= cursor.offset && (await markOf(handle, cursor.offset)) === cursor.mark;
44
+ /** A read started ahead of its turn: a failure the read never gets to (a line too long ends it first) is not unhandled;
45
+ * awaited, it still throws. */
46
+ const ahead = (read) => {
47
+ read.catch(() => { });
48
+ return read;
49
+ };
50
+ /** Whether a read from `cursor` of the open file goes on from it: the same source, kind of read and state shape
51
+ * (LineSource.stateVersion), the same file (device and inode), no shorter, and the bytes before its offset as they
52
+ * were. Else it reads the file from its start. */
53
+ async function goesOn(spec, keep, totals, cursor, handle, stats) {
54
+ return cursor.source === spec.source && cursor.keep === keep && (cursor.totals ?? false) === totals && cursor.stateVersion === spec.stateVersion && cursor.dev === stats.dev && cursor.ino === stats.ino && stats.size >= cursor.offset && (await markOf(handle, cursor.offset)) === cursor.mark;
46
55
  }
47
56
  /** Whether a read with these options is a totals read: asked for, with no turns kept, from a source that has one. */
48
57
  const totalsRead = (spec, keep, asked) => asked && !keep && spec.totals === true;
@@ -55,7 +64,7 @@ export async function resumes(spec, file, cursor, { turns: keep = true, totals:
55
64
  if (!handle)
56
65
  return false;
57
66
  try {
58
- return await goesOn(spec.source, keep, totalsRead(spec, keep, asked), cursor, handle, await handle.stat());
67
+ return await goesOn(spec, keep, totalsRead(spec, keep, asked), cursor, handle, await handle.stat());
59
68
  }
60
69
  finally {
61
70
  await handle.close();
@@ -67,14 +76,15 @@ const overlay = (base) => {
67
76
  return { has: (key) => extra.has(key) || base.has(key), add: (key) => extra.add(key) };
68
77
  };
69
78
  /** One session file of `spec`'s source, read from its start or from `cursor`. */
70
- async function readLines(spec, file, cursor, { turns: keep = true, totals: asked = false, seen, keepsCursor = true, maxLine = Infinity } = {}) {
79
+ async function readLines(spec, shape, file, cursor, { turns: keep = true, totals: asked = false, seen, keepsCursor = true, [DROPS_CURSOR]: dropsCursor = false, [NO_READ_AHEAD]: inTurn = false, maxLine = Infinity } = {}) {
71
80
  const { source } = spec;
72
81
  const totals = totalsRead(spec, keep, asked);
82
+ const fields = totals ? shape : undefined;
73
83
  const handle = await open(file, "r");
74
84
  try {
75
85
  const stats = await handle.stat();
76
86
  // The cursor's presence checked here, so `resumed` narrows it where its state and offset are read.
77
- const resumed = cursor !== undefined && (await goesOn(source, keep, totals, cursor, handle, stats));
87
+ const resumed = cursor !== undefined && (await goesOn(spec, keep, totals, cursor, handle, stats));
78
88
  const state = (resumed
79
89
  ? structuredClone(cursor.state)
80
90
  : { session: { source, id: "", file, state: "completed", child: false, turns: [], users: 0, activeMs: 0, copies: 0 }, turns: [], answers: [], names: new Map(), priced: { sum: 0, unknown: false }, activeMs: 0, own: spec.start(), ...(totals ? { counts: counts() } : {}), ...(seen ? {} : { seen: new Set() }) });
@@ -94,14 +104,7 @@ async function readLines(spec, file, cursor, { turns: keep = true, totals: asked
94
104
  state.answers.push(turn);
95
105
  },
96
106
  };
97
- const line = (text) => {
98
- let value;
99
- try {
100
- value = JSON.parse(text);
101
- }
102
- catch {
103
- return;
104
- }
107
+ const line = (value) => {
105
108
  if (!isObject(value))
106
109
  return;
107
110
  const at = timeOf(value.timestamp);
@@ -119,6 +122,21 @@ async function readLines(spec, file, cursor, { turns: keep = true, totals: asked
119
122
  }
120
123
  }
121
124
  };
125
+ // A line's bytes b[from, to): its fields alone where the source names them and the scan is sure of the line, else
126
+ // the line decoded and parsed whole; a line that is not JSON is passed over.
127
+ const take = (b, from, to) => {
128
+ let value = fields ? scan(b, from, to, fields) : undefined;
129
+ if (value === undefined) {
130
+ const text = b.toString("utf8", from, to);
131
+ try {
132
+ value = JSON.parse(text);
133
+ }
134
+ catch {
135
+ return;
136
+ }
137
+ }
138
+ line(value);
139
+ };
122
140
  const start = resumed ? cursor.offset : 0;
123
141
  let offset = start;
124
142
  let read = 0;
@@ -129,24 +147,40 @@ async function readLines(spec, file, cursor, { turns: keep = true, totals: asked
129
147
  throw new LineTooLong(file, offset, bytes, maxLine);
130
148
  };
131
149
  if (stats.size > start) {
132
- // The open handle, so the bytes read are the file stat described, whatever the path names now. One buffer for the
133
- // whole read: a new one a chunk leaves freed native memory behind on every thread that reads (the read pool's).
134
- const buffer = Buffer.allocUnsafeSlow(CHUNK);
150
+ // The open handle, so the bytes read are the file stat described, whatever the path names now. The buffers last the
151
+ // whole read (a new buffer a chunk leaves freed native memory behind on every thread that reads, the read pool's):
152
+ // two taken in turn, the next chunk read into one while this one's lines are read; read in turn (NO_READ_AHEAD),
153
+ // one, the next chunk read into it once its lines are.
154
+ const buffers = inTurn ? [Buffer.allocUnsafeSlow(CHUNK)] : [Buffer.allocUnsafeSlow(CHUNK), Buffer.allocUnsafeSlow(CHUNK)];
155
+ let which = 0;
156
+ let next = ahead(handle.read(buffers[0], 0, CHUNK, start));
135
157
  for (let at = start;;) {
136
- const { bytesRead } = await handle.read(buffer, 0, CHUNK, at);
158
+ const { bytesRead } = await next;
137
159
  if (!bytesRead)
138
160
  break;
161
+ const buffer = buffers[which];
139
162
  at += bytesRead;
163
+ which = (which + 1) % buffers.length;
164
+ if (!inTurn)
165
+ next = ahead(handle.read(buffers[which], 0, CHUNK, at));
140
166
  const chunk = buffer.subarray(0, bytesRead);
141
167
  read += chunk.length;
142
168
  let from = 0;
143
169
  for (let nl = chunk.indexOf(10); nl !== -1; nl = chunk.indexOf(10, from)) {
144
170
  tooLong(restBytes + nl - from);
145
- const whole = rest.length ? Buffer.concat([...rest, chunk.subarray(from, nl)]) : chunk.subarray(from, nl);
146
- rest = [];
147
- restBytes = 0;
148
- line(whole.toString("utf8", 0, whole.length && whole[whole.length - 1] === 13 ? whole.length - 1 : whole.length));
149
- offset += whole.length + 1;
171
+ // The line in the chunk where it starts there, else its start's copies and the chunk's part as one.
172
+ let b = chunk;
173
+ let s = from;
174
+ let n = nl;
175
+ if (rest.length) {
176
+ b = Buffer.concat([...rest, chunk.subarray(from, nl)]);
177
+ s = 0;
178
+ n = b.length;
179
+ rest = [];
180
+ restBytes = 0;
181
+ }
182
+ take(b, s, n > s && b[n - 1] === 13 ? n - 1 : n);
183
+ offset += n - s + 1;
150
184
  from = nl + 1;
151
185
  }
152
186
  // The buffer is read into again: a line's start is kept as a copy.
@@ -155,26 +189,33 @@ async function readLines(spec, file, cursor, { turns: keep = true, totals: asked
155
189
  tooLong(restBytes);
156
190
  rest.push(Buffer.from(chunk.subarray(from)));
157
191
  }
192
+ if (inTurn)
193
+ next = handle.read(buffer, 0, CHUNK, at);
158
194
  }
159
195
  }
160
196
  // A last line with no newline yet may be a record still being written: read into this result when it is whole JSON,
161
197
  // but the cursor stays before it, its state without it. A caller that keeps the cursor reads the line again from it,
162
198
  // so its `seen` is left untouched by it; one that keeps none (readSession) has it in `seen` like any other line.
199
+ // A caller that drops the cursor (DROPS_CURSOR) gets one on the read's own state, that line in it: no copy of the
200
+ // whole state (the file's request index and counts with it) is made to leave the line out.
163
201
  let kept = state;
164
202
  if (rest.length) {
165
- kept = structuredClone(state);
203
+ if (!dropsCursor)
204
+ kept = structuredClone(state);
166
205
  if (keepsCursor)
167
206
  context.seen = overlay(context.seen);
168
- line(Buffer.concat(rest).toString("utf8"));
207
+ const last = Buffer.concat(rest);
208
+ take(last, 0, last.length);
169
209
  }
170
210
  const mark = await markOf(handle, offset);
171
211
  let session = finish(spec, file, state, context);
172
212
  if (!keep) {
173
- kept = { ...kept, session: withoutText(kept.session), own: spec.forget ? spec.forget(kept.own) : kept.own, ...(kept.counts ? { counts: trimmed(kept.counts) } : {}) };
213
+ if (!dropsCursor)
214
+ kept = { ...kept, session: withoutText(kept.session), own: spec.forget ? spec.forget(kept.own) : kept.own, ...(kept.counts ? { counts: trimmed(kept.counts) } : {}) };
174
215
  if (resumed)
175
216
  session = withoutText(session);
176
217
  }
177
- return { sessions: [{ locator: { file }, session, requests: state.answers, ...(state.counts ? { counts: state.counts } : {}) }], cursor: { source, dev: stats.dev, ino: stats.ino, offset, mark, keep, ...(totals ? { totals } : {}), state: kept }, read, resumed };
218
+ return { sessions: [{ locator: { file }, session, requests: state.answers, ...(state.counts ? { counts: state.counts } : {}) }], cursor: { source, dev: stats.dev, ino: stats.ino, offset, mark, keep, ...(totals ? { totals } : {}), ...(spec.stateVersion !== undefined ? { stateVersion: spec.stateVersion } : {}), state: kept }, read, resumed };
178
219
  }
179
220
  finally {
180
221
  await handle.close();
@@ -197,9 +238,20 @@ function finish(spec, file, state, context) {
197
238
  out.effort = effort;
198
239
  return out;
199
240
  }
241
+ /** Each source's fields as scan takes them, made once per Shape: a reader built again over the same fields (a Codex
242
+ * fork's, whose spec differs only in its start) reads with the node they were compiled to, since the walk's table, which
243
+ * holds every compiled node, only grows. */
244
+ const compiled = new WeakMap();
245
+ function fieldsFor(shape) {
246
+ let fields = compiled.get(shape);
247
+ if (!fields)
248
+ compiled.set(shape, (fields = fieldsOf({ ...shape, timestamp: true })));
249
+ return fields;
250
+ }
200
251
  /** The Reader of a JSONL source: each file one locator, its cursor a FileCursor. */
201
252
  export function lineReader(spec) {
202
253
  const { source, name, harness, order, children } = spec;
254
+ const fields = spec.fields ? fieldsFor(spec.fields) : undefined;
203
255
  return {
204
256
  source,
205
257
  name,
@@ -207,7 +259,7 @@ export function lineReader(spec) {
207
259
  ...(order ? { order } : {}),
208
260
  discover: async (home, env) => (await spec.files(home, env)).map((file) => ({ file })),
209
261
  idOf: ({ file }) => spec.idOf(file),
210
- read: (locator, cursor, options) => readLines(spec, locator.file, cursor, options),
262
+ read: (locator, cursor, options) => readLines(spec, fields, locator.file, cursor, options),
211
263
  ...(children ? { children: async (home, env) => (await children(home, env)).map(({ file, of }) => ({ locator: { file }, of: { file: of } })) } : {}),
212
264
  };
213
265
  }
@@ -1,57 +1,45 @@
1
- // A read pool's worker (pool.ts): reads one locator with the registry's reader as parseHome's totals read does, through a
2
- // `seen` of the locator's own records alone, and hands back its sessions, the records it added (mine) and the records it
3
- // asked for, did not hold and never added (missed). parseHome takes the read as its own when no record of either is one
4
- // an earlier locator holds: its `seen` would then have answered every question alike (a record asked for and then added
5
- // is in mine), so the read is the one it would have made.
1
+ // A read pool's worker (pool.ts): reads one locator of a line source (LINE_READERS) as parseHome's totals read does,
2
+ // through a `seen` of the locator's own records alone, and hands back its sessions, the records it added (mine) and the
3
+ // records it asked for, did not hold and never added (missed). parseHome takes the read as its own when no record of
4
+ // either is one an earlier locator holds: its `seen` would then have answered every question alike (a record asked for
5
+ // and then added is in mine), so the read is the one it would have made.
6
6
  import { parentPort, workerData } from "node:worker_threads";
7
7
  import { packed, packInto } from "./record-key.js";
8
- import { addRecord, ownerOf, recordIndex } from "./record-index.js";
9
- import { READERS } from "./readers/index.js";
8
+ import { addRecord, indexArrays, notIn, ownerOf, recordIndex } from "./record-index.js";
9
+ import { DROPS_CURSOR, NO_READ_AHEAD } from "./internal.js";
10
+ import { LINE_READERS } from "./readers/line-readers.js";
10
11
  /** The longest line this worker decodes (pool.ts sets it from the heap cap): a file with a longer one is handed back. */
11
12
  const { maxLine } = workerData;
12
13
  /** What readers look up once, shared by this worker's reads (ReadOptions.lookups): a pool lives for one parseHome, so
13
14
  * this is one import's, and each worker looks up at most once what the import's own thread looks up once. */
14
15
  const lookups = new Map();
15
- const buffers = (index) => [index.uuids.slots, index.uuids.owners, index.uuids.words, index.others.slots, index.others.owners, index.others.ends, index.others.bytes].map((a) => a.buffer);
16
+ /** The index's arrays, moved with the reply rather than copied (its tags too: a copy is made on this thread and again on
17
+ * parseHome's, which every read passes through). */
18
+ const buffers = (index) => indexArrays(index).map((a) => a.buffer);
16
19
  parentPort.on("message", async ({ id, source, locator }) => {
17
- const reader = READERS[source];
20
+ const reader = LINE_READERS[source];
18
21
  const mine = recordIndex(64);
19
- const missed = recordIndex(64);
20
- let asked;
22
+ // Every record asked for while mine did not hold it; the ones added after are taken out once the read ends.
23
+ const asked = recordIndex(64);
21
24
  const at = packed();
22
- // The last record asked for and not held, kept out of missed until the next question: a reader adds most records just
23
- // after asking for them, and those are in mine.
24
- let open = false;
25
- const settle = () => {
26
- if (open)
27
- addRecord(missed, at, 0);
28
- open = false;
29
- };
30
- const pack = (record) => {
31
- if (record === asked)
32
- return at;
33
- settle();
34
- asked = record;
35
- return packInto(record, at);
36
- };
37
25
  const seen = {
38
26
  has: (record) => {
39
- pack(record);
40
- if (ownerOf(mine, at) !== -1)
27
+ if (ownerOf(mine, packInto(record, at)) !== -1)
41
28
  return true;
42
- open = true;
29
+ addRecord(asked, at, 0);
43
30
  return false;
44
31
  },
45
32
  add(record) {
46
- pack(record);
47
- open = false;
48
- addRecord(mine, at, 0);
33
+ addRecord(mine, packInto(record, at), 0);
49
34
  return this;
50
35
  },
51
36
  };
52
37
  try {
53
- const result = await reader.read(locator, undefined, { turns: false, totals: true, seen, maxLine, lookups });
54
- settle();
38
+ // The cursor is never sent back: the read makes no copy for it. No read ahead (NO_READ_AHEAD): the pool's workers take
39
+ // every core it was given.
40
+ const options = { turns: false, totals: true, seen, maxLine, lookups, [DROPS_CURSOR]: true, [NO_READ_AHEAD]: true };
41
+ const result = await reader.read(locator, undefined, options);
42
+ const missed = notIn(asked, mine);
55
43
  const counts = result.sessions.flatMap(({ counts }) => (counts ? [counts.model.buffer, counts.values.buffer, counts.has.buffer] : []));
56
44
  parentPort.postMessage({ id, ok: true, sessions: result.sessions, mine, missed }, [...new Set([...buffers(mine), ...buffers(missed), ...counts])]);
57
45
  }
package/dist/pool.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Locator, SessionRead } from "./reader.js";
2
- import type { RecordIndex } from "./record-index.js";
2
+ import { type RecordIndex } from "./record-index.js";
3
3
  /** A read the pool made: its sessions, the records it added, those it asked for and did not hold. Not ok: make it again. */
4
4
  export type PoolRead = {
5
5
  ok: true;
@@ -12,6 +12,13 @@ export type PoolRead = {
12
12
  /** Each worker's old generation. Unbounded, each grows to several times what it holds (eight workers: 0.5 GiB of heap
13
13
  * for 0.12 GiB in use, on a 24 GB home). A worker past it ends; its file is read by parseHome. */
14
14
  export declare const OLD_MB = 64;
15
+ /** The smallest old generation a worker may be given (parseHome's workerOldMb). On node 24.22.3, one pool worker started
16
+ * at N MB to read a synthetic home of four files (one of 1.2 MB), each N in a process of its own: at 1 and 2 MB V8 ends
17
+ * the whole process as the worker starts ("Fatal JavaScript out of memory: GC during deserialization"); from 3 to 6 MB
18
+ * no worker read a file (5 processes each, 29 at 6); at 7, 28 of 29 processes lost a worker; at 8 to 10 (29 processes
19
+ * each) and at 11 and 12 (5 each), every worker read every file. A worker under it can only end the process or lose
20
+ * every read, so it is refused. */
21
+ export declare const MIN_OLD_MB = 8;
15
22
  /** A file this large or larger is read ahead of the import's order, the largest first: such files set the time. */
16
23
  export declare const BIG_FILE: number;
17
24
  /** The most bytes of finished reads that may wait to be taken by default; at the read-ahead, the pool reads only the one
@@ -24,8 +31,30 @@ export declare const memoryLimit: (total?: number, constrained?: number) => numb
24
31
  /** The default read-ahead: READ_AHEAD_BYTES, or a sixteenth of the memory this process may use when that is less (512 MiB
25
32
  * at 8 GiB, 128 MiB in a 2 GiB container). */
26
33
  export declare const readAheadBytes: (memory?: number) => number;
27
- /** A session's strings (its first prompt and title can run to megabytes) as V8 holds them. */
28
- export declare const stringBytes: (session: object) => number;
34
+ /** The default threads' ceiling. On a 48-core machine, a 23 GB home (pooled, median of 2) took 27.5 s at 8 threads
35
+ * (peak 1.13 GiB), 20.3 s at 16 (1.77 GiB), 17.2 s at 24 (2.39 GiB) and 23.3 s at 32 (2.87 GiB): 16 takes most of 24's
36
+ * gain for three quarters of its memory, and past 24 the threads slow each other down. */
37
+ export declare const DEFAULT_THREADS_CEILING = 16;
38
+ /** The most a worker's heap holds: its young generation (YOUNG_MB) and its old one (`oldMb`), both capped at its start.
39
+ * The pool's peak grew by about this, 80 MiB a worker at the default, from 8 threads to 24 (the runs DEFAULT_THREADS_CEILING cites). */
40
+ export declare const workerBytes: (oldMb?: number) => number;
41
+ /** The memory still free to this process: the machine's (os.freemem, MemAvailable on Linux: page cache it may reclaim
42
+ * counts as free), at most its container's limit (memoryLimit). Not process.availableMemory: under a cgroup it takes the
43
+ * limit less memory.current, which counts the page cache as used. On a 503 GiB machine with 345 GiB free, in a cgroup
44
+ * of 350 GiB whose 346 GiB in use were 250 GiB of page cache, it read 130 MiB to 3.6 GiB from one second to the next. */
45
+ export declare const freeMemory: (free?: number, limit?: number) => number;
46
+ /** parseHome's default threads: the fewest of
47
+ * - the cores this process may run on, one left for the thread that takes the reads and totals them (two cores keep
48
+ * two threads: one worker would read no faster than the calling thread alone);
49
+ * - DEFAULT_THREADS_CEILING;
50
+ * - the workers whose heaps (workerBytes) fit in the memory still free (freeMemory) once the read-ahead (`aheadBytes`)
51
+ * is set aside, since the reads waiting are held on the calling thread;
52
+ * and at least 1 (every file read on the calling thread). A caller's `threads` is taken as given, up to MOST_THREADS. */
53
+ export declare const defaultThreads: (cores?: number, available?: number, aheadBytes?: number, oldMb?: number) => number;
54
+ /** A read's strings as V8 holds them (a session's first prompt and title can run to megabytes), wherever they are in its
55
+ * objects and arrays (a session's turns, a read's requests and paths): each object once, on a stack of its own, so no
56
+ * depth runs the call stack out and a cycle ends. A typed array holds none: heldBytes counts its bytes apart. */
57
+ export declare function stringBytes(read: object): number;
29
58
  export declare class ReadPool {
30
59
  private readonly threads;
31
60
  private readonly aheadBytes;
@@ -45,13 +74,10 @@ export declare class ReadPool {
45
74
  private waiting;
46
75
  private losses;
47
76
  private broken;
48
- /** The most bytes of reads waiting at once, and the workers lost (for measuring). The read-ahead is checked before a
49
- * read is sent, so the reads in flight then (at most `threads`) may land past it. */
77
+ /** The most bytes of reads waiting at once, read by the lane's measuring script alone. The read-ahead is checked before
78
+ * a read is sent, so the reads in flight then (at most `threads`) may land past it. */
50
79
  peakWaiting: number;
51
- lost: number;
52
80
  constructor(threads: number, aheadBytes?: number, oldMb?: number);
53
- /** The bytes of reads waiting to be taken now. */
54
- get held(): number;
55
81
  /** Queues each locator; a job's id is its place in the import's order, so `items` come in that order. The ids, for take. */
56
82
  readAll(items: readonly {
57
83
  source: string;
package/dist/pool.js CHANGED
@@ -7,14 +7,22 @@
7
7
  // (readAheadBytes()), the pool reads large files first (BIG_FILE and over, the largest first: they set the time), then
8
8
  // the rest in the import's order; at the read-ahead it reads only the one parseHome waits for. A worker's heap is bounded (OLD_MB): one that
9
9
  // runs out gives up its file, which parseHome reads itself, and another worker takes its place.
10
- import { totalmem } from "node:os";
10
+ import { availableParallelism, freemem, totalmem } from "node:os";
11
11
  import { Worker } from "node:worker_threads";
12
+ import { indexArrays } from "./record-index.js";
12
13
  /** Each worker's young generation: the default lets eight workers' garbage add up to more than the reads themselves. The
13
14
  * workers take none of this process's flags (a caller's `--input-type=module -e` would stop them loading). */
14
15
  const YOUNG_MB = 16;
15
16
  /** Each worker's old generation. Unbounded, each grows to several times what it holds (eight workers: 0.5 GiB of heap
16
17
  * for 0.12 GiB in use, on a 24 GB home). A worker past it ends; its file is read by parseHome. */
17
18
  export const OLD_MB = 64;
19
+ /** The smallest old generation a worker may be given (parseHome's workerOldMb). On node 24.22.3, one pool worker started
20
+ * at N MB to read a synthetic home of four files (one of 1.2 MB), each N in a process of its own: at 1 and 2 MB V8 ends
21
+ * the whole process as the worker starts ("Fatal JavaScript out of memory: GC during deserialization"); from 3 to 6 MB
22
+ * no worker read a file (5 processes each, 29 at 6); at 7, 28 of 29 processes lost a worker; at 8 to 10 (29 processes
23
+ * each) and at 11 and 12 (5 each), every worker read every file. A worker under it can only end the process or lose
24
+ * every read, so it is refused. */
25
+ export const MIN_OLD_MB = 8;
18
26
  /** The share of a worker's old generation one line may take: a line past it is read by parseHome. A capped worker
19
27
  * whose one native call (a line's decoding, JSON.parse) outgrows its heap does not end alone: V8 ends the process. At a
20
28
  * 64 MB heap, a 90 MB line of text, or a 15.9 MB line of empty objects (`[{},{},...]`, parsed to some 13 times its
@@ -32,22 +40,65 @@ export const memoryLimit = (total = totalmem(), constrained = process.constraine
32
40
  /** The default read-ahead: READ_AHEAD_BYTES, or a sixteenth of the memory this process may use when that is less (512 MiB
33
41
  * at 8 GiB, 128 MiB in a 2 GiB container). */
34
42
  export const readAheadBytes = (memory = memoryLimit()) => Math.min(READ_AHEAD_BYTES, Math.floor(memory / 16));
43
+ /** The default threads' ceiling. On a 48-core machine, a 23 GB home (pooled, median of 2) took 27.5 s at 8 threads
44
+ * (peak 1.13 GiB), 20.3 s at 16 (1.77 GiB), 17.2 s at 24 (2.39 GiB) and 23.3 s at 32 (2.87 GiB): 16 takes most of 24's
45
+ * gain for three quarters of its memory, and past 24 the threads slow each other down. */
46
+ export const DEFAULT_THREADS_CEILING = 16;
47
+ /** The most a worker's heap holds: its young generation (YOUNG_MB) and its old one (`oldMb`), both capped at its start.
48
+ * The pool's peak grew by about this, 80 MiB a worker at the default, from 8 threads to 24 (the runs DEFAULT_THREADS_CEILING cites). */
49
+ export const workerBytes = (oldMb = OLD_MB) => (YOUNG_MB + oldMb) * 2 ** 20;
50
+ /** The memory still free to this process: the machine's (os.freemem, MemAvailable on Linux: page cache it may reclaim
51
+ * counts as free), at most its container's limit (memoryLimit). Not process.availableMemory: under a cgroup it takes the
52
+ * limit less memory.current, which counts the page cache as used. On a 503 GiB machine with 345 GiB free, in a cgroup
53
+ * of 350 GiB whose 346 GiB in use were 250 GiB of page cache, it read 130 MiB to 3.6 GiB from one second to the next. */
54
+ export const freeMemory = (free = freemem(), limit = memoryLimit()) => Math.min(free, limit);
55
+ /** parseHome's default threads: the fewest of
56
+ * - the cores this process may run on, one left for the thread that takes the reads and totals them (two cores keep
57
+ * two threads: one worker would read no faster than the calling thread alone);
58
+ * - DEFAULT_THREADS_CEILING;
59
+ * - the workers whose heaps (workerBytes) fit in the memory still free (freeMemory) once the read-ahead (`aheadBytes`)
60
+ * is set aside, since the reads waiting are held on the calling thread;
61
+ * and at least 1 (every file read on the calling thread). A caller's `threads` is taken as given, up to MOST_THREADS. */
62
+ export const defaultThreads = (cores = availableParallelism(), available = freeMemory(), aheadBytes = readAheadBytes(), oldMb = OLD_MB) => {
63
+ const byCores = cores <= 2 ? cores : cores - 1;
64
+ const byMemory = Math.floor(Math.max(0, available - aheadBytes) / workerBytes(oldMb));
65
+ return Math.max(1, Math.min(byCores, DEFAULT_THREADS_CEILING, byMemory));
66
+ };
35
67
  /** Workers lost (out of memory, or ended) past this many times the threads: the pool stops, and parseHome reads the rest. */
36
68
  const LOSSES_PER_THREAD = 2;
37
69
  /** A session's objects beyond its typed arrays and its strings, as the budget counts them. */
38
70
  const SESSION_BYTES = 1024;
39
71
  /** A string past U+00FF: V8 holds it at two bytes a UTF-16 code unit, any other at one. */
40
72
  const WIDE = /[^\u0000-\u00ff]/;
41
- /** A session's strings (its first prompt and title can run to megabytes) as V8 holds them. */
42
- export const stringBytes = (session) => Object.values(session).reduce((sum, value) => sum + (typeof value === "string" ? (WIDE.test(value) ? 2 : 1) * value.length : 0), 0);
43
- const indexBytes = (index) => [index.uuids.slots, index.uuids.owners, index.uuids.words, index.others.slots, index.others.owners, index.others.ends, index.others.bytes].reduce((sum, a) => sum + a.byteLength, 0);
73
+ /** A read's strings as V8 holds them (a session's first prompt and title can run to megabytes), wherever they are in its
74
+ * objects and arrays (a session's turns, a read's requests and paths): each object once, on a stack of its own, so no
75
+ * depth runs the call stack out and a cycle ends. A typed array holds none: heldBytes counts its bytes apart. */
76
+ export function stringBytes(read) {
77
+ let bytes = 0;
78
+ const visited = new Set();
79
+ const stack = [read];
80
+ while (stack.length) {
81
+ const value = stack.pop();
82
+ if (typeof value === "string")
83
+ bytes += (WIDE.test(value) ? 2 : 1) * value.length;
84
+ else if (typeof value === "object" && value !== null && !ArrayBuffer.isView(value) && !visited.has(value)) {
85
+ visited.add(value);
86
+ for (const inner of Array.isArray(value) ? value : Object.values(value))
87
+ stack.push(inner);
88
+ }
89
+ }
90
+ return bytes;
91
+ }
92
+ const indexBytes = (index) => indexArrays(index).reduce((sum, a) => sum + a.byteLength, 0);
44
93
  /** What a read holds while it waits: its indexes' and counts' arrays, and its sessions with their strings. */
45
94
  function heldBytes(read) {
46
95
  if (!read.ok)
47
96
  return 0;
48
97
  let bytes = indexBytes(read.mine) + indexBytes(read.missed);
49
- for (const { session, counts } of read.sessions)
50
- bytes += SESSION_BYTES + stringBytes(session) + (counts ? counts.model.byteLength + counts.values.byteLength + counts.has.byteLength : 0);
98
+ for (const sessionRead of read.sessions) {
99
+ const { counts } = sessionRead;
100
+ bytes += SESSION_BYTES + stringBytes(sessionRead) + (counts ? counts.model.byteLength + counts.values.byteLength + counts.has.byteLength : 0);
101
+ }
51
102
  return bytes;
52
103
  }
53
104
  export class ReadPool {
@@ -69,10 +120,9 @@ export class ReadPool {
69
120
  waiting = 0;
70
121
  losses = 0;
71
122
  broken = false;
72
- /** The most bytes of reads waiting at once, and the workers lost (for measuring). The read-ahead is checked before a
73
- * read is sent, so the reads in flight then (at most `threads`) may land past it. */
123
+ /** The most bytes of reads waiting at once, read by the lane's measuring script alone. The read-ahead is checked before
124
+ * a read is sent, so the reads in flight then (at most `threads`) may land past it. */
74
125
  peakWaiting = 0;
75
- lost = 0;
76
126
  constructor(threads, aheadBytes = readAheadBytes(), oldMb = OLD_MB) {
77
127
  this.threads = threads;
78
128
  this.aheadBytes = aheadBytes;
@@ -86,10 +136,6 @@ export class ReadPool {
86
136
  this.fail();
87
137
  }
88
138
  }
89
- /** The bytes of reads waiting to be taken now. */
90
- get held() {
91
- return this.waiting;
92
- }
93
139
  /** Queues each locator; a job's id is its place in the import's order, so `items` come in that order. The ids, for take. */
94
140
  readAll(items) {
95
141
  const ids = items.map(({ source, locator, size }) => {
@@ -207,7 +253,6 @@ export class ReadPool {
207
253
  gone(worker) {
208
254
  if (!this.live.delete(worker) || this.broken)
209
255
  return;
210
- this.lost += 1;
211
256
  const at = this.idle.indexOf(worker);
212
257
  if (at !== -1)
213
258
  this.idle.splice(at, 1);
package/dist/read.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { lstat, stat } from "node:fs/promises";
2
+ import { DROPS_CURSOR } from "./internal.js";
2
3
  import { READERS } from "./readers/index.js";
3
4
  /** The reader of `source` among `readers`; one that is not there throws. */
4
5
  export function readerOf(source, readers = READERS) {
@@ -72,7 +73,9 @@ export async function childrenOf(home, source, { env, readers } = {}) {
72
73
  * listing shows. A locator whose session is not there throws. */
73
74
  export async function readSession(locator, source, { readers, ...options } = {}) {
74
75
  const at = typeof locator === "string" ? { file: locator } : locator;
75
- const { sessions } = await readerOf(source, readers).read(at, undefined, { ...options, keepsCursor: false });
76
+ // The cursor is dropped: the read makes no copy for it.
77
+ const read = { ...options, keepsCursor: false, [DROPS_CURSOR]: true };
78
+ const { sessions } = await readerOf(source, readers).read(at, undefined, read);
76
79
  const found = at.id === undefined ? sessions[0] : sessions.find(({ locator }) => locator.id === at.id);
77
80
  if (!found)
78
81
  throw new Error(`no session ${at.id ?? ""} in ${at.file}`);
@@ -1,4 +1,25 @@
1
+ import { type LineSource } from "../lines.js";
1
2
  import { type Env } from "../reader.js";
3
+ import { type RecordIndex } from "../record-index.js";
4
+ import type { Answer } from "../types.js";
5
+ type Own = {
6
+ /** This file's requests by key (keyOf), each a turn its later lines join. */
7
+ keyed: Map<string, Answer>;
8
+ /** A totals read's instead: each request's index in its counts, by its key packed (packInto). */
9
+ indexes?: RecordIndex;
10
+ /** The calls of requests that were copies, whose results are copies too. */
11
+ copied: Set<string>;
12
+ /** Its titles (titleRecord), and its records' uuids, for the summaries' leaves. */
13
+ titles: {
14
+ custom?: string;
15
+ ai?: string;
16
+ summaries: {
17
+ title: string;
18
+ leaf?: string;
19
+ }[];
20
+ uuids: Set<string>;
21
+ };
22
+ };
2
23
  /** Claude Code's subagents' session files under `home`, in <session id>/subagents/ (a workflow's a folder deeper), each
3
24
  * with the session file it ran under (`of`): the one beside the folder it sits in. A session moved to another project
4
25
  * folder keeps its id there, with copies of its subagents' files: each folder's are its own file's. Never through a
@@ -8,3 +29,6 @@ export declare function childFiles(home: string, env?: Env): Promise<{
8
29
  of: string;
9
30
  }[]>;
10
31
  export declare const claudeCode: import("../reader.js").Reader<"claude-code", import("../lines.js").FileCursor>;
32
+ /** The source as lineReader takes it (a test reads with it, its fields or not). */
33
+ export declare const claudeCodeLines: LineSource<"claude-code", Own>;
34
+ export {};