@polycode-projects/the-mechanical-code-talker 5.0.46 → 6.0.0

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.
@@ -0,0 +1,361 @@
1
+ // subgraph-retrieval.mjs — runs a retrieval plan against corpus band
2
+ // partitions and hands back the rows a turn can reason over, plus the metrics
3
+ // that say how complete the answer is.
4
+ //
5
+ // The whole point is that a smaller budget returns a prefix of a bigger one's
6
+ // answer rather than a different answer. That holds because the traversal order
7
+ // is fixed before the first read: terms sorted, bands sorted, each page sorted
8
+ // by row key, and every response folded in the order it was issued rather than
9
+ // the order it came back. Concurrency changes the wall time and nothing else.
10
+ //
11
+ // Running out of budget degrades. It never throws: the caller gets the rows
12
+ // that arrived, `bounded: true`, and the name of the budget that stopped it. A
13
+ // timeout is a smaller subgraph, never a guess.
14
+
15
+ import {
16
+ buildRetrievalPlan, expandedTerms, ancestryTerms,
17
+ } from "../domain/retrieval-plan.mjs";
18
+ import { loadLexicon } from "../domain/grammar/lexicon.mjs";
19
+ import { BACKEND_UNAVAILABLE_CODE } from "../adapters/memory/row-backend.mjs";
20
+
21
+ /** The retrieval budgets, set from what scripts/corpus-bands/calibrate-retrieval.mjs
22
+ * measured over the committed WordNet and ConceptNet corpora. Changing one is
23
+ * a code change, deliberately: a request cannot widen its own read.
24
+ *
25
+ * Each budget degrades rather than failing. `fuzzyVariantsPerTerm` and
26
+ * `hopDepth` cut the plan before any read; `rowsPerQueryPage` paginates;
27
+ * `totalRows`, `totalQueries` and `wallTimeMs` stop the traversal and mark the
28
+ * subgraph bounded; `inFlightQueries` only queues.
29
+ *
30
+ * What each number came from:
31
+ *
32
+ * fuzzyVariantsPerTerm the widest measured tie was five candidates at the
33
+ * same distance; below that the cap cuts alphabetically
34
+ * and drops real candidates, so six clears every case
35
+ * hopDepth the engine's own alias chase is two hops
36
+ * rowsPerQueryPage the heaviest single term returned 92 rows, so 200
37
+ * reads every measured term in one round trip
38
+ * totalRows folding 1,000 rows into a payload costs about 12 ms
39
+ * and about 1 MB; 5,000 costs 44 ms and 5.3 MB, which
40
+ * is a third of the whole bundled seed for one question
41
+ * totalQueries eight rounds of eight in flight, about 80 ms against
42
+ * a store answering in the 10 ms class. A wide turn
43
+ * spends 20-30 of these on its own terms across three
44
+ * bands, and the rest goes to the subClassOf chain
45
+ * wallTimeMs the latency the turn surface can spend on reads
46
+ * inFlightQueries eight, so a turn cannot monopolize table throughput
47
+ * queryRetries two retries at 25 ms doubling spends at most 75 ms of
48
+ * backoffBaseMs the 300 ms on waiting, leaving 225 ms of reading
49
+ *
50
+ * The measurement's headline is worth knowing when reading a turn's metrics: a
51
+ * grounded question over a corpus this dense wants thousands of Queries if
52
+ * nothing stops it, because the subClassOf closure branches rather than
53
+ * chaining. Every grounded turn comes back bounded, and the marker says so.
54
+ * Reads are ordered so what a budget takes is always the least targeted part. */
55
+ export const RETRIEVAL_BUDGETS = Object.freeze({
56
+ fuzzyVariantsPerTerm: 6,
57
+ hopDepth: 2,
58
+ rowsPerQueryPage: 200,
59
+ totalRows: 1000,
60
+ totalQueries: 64,
61
+ wallTimeMs: 300,
62
+ inFlightQueries: 8,
63
+ queryRetries: 2,
64
+ backoffBaseMs: 25,
65
+ });
66
+
67
+ /** Retrieval ran and the answer stands on the corpus supplement as well as the
68
+ * seed and the session. */
69
+ export const SUPPLEMENTED_MODE = "supplemented";
70
+
71
+ /** No corpus read happened, because no bands are configured or the breaker is
72
+ * open. The
73
+ * answer stands on the bundled seed and the session alone. */
74
+ export const SEED_SESSION_MODE = "seed-session";
75
+
76
+ const THROTTLE_ERROR_NAMES = new Set([
77
+ "ProvisionedThroughputExceededException",
78
+ "RequestLimitExceeded",
79
+ "ThrottlingException",
80
+ "TooManyRequestsException",
81
+ "InternalServerError",
82
+ "ServiceUnavailable",
83
+ "TimeoutError",
84
+ "AbortError",
85
+ ]);
86
+
87
+ /** Does this failure mean the store itself is in trouble? Only these count
88
+ * toward a breaker: throttles, 5xx and timeouts. An empty result is an answer,
89
+ * and a rejected input is a bug in the caller, so neither is systemic. */
90
+ export function isSystemicFailure(error) {
91
+ if (!error) return false;
92
+ if (error.code === BACKEND_UNAVAILABLE_CODE) return true;
93
+ if (error.retryable === true || error.$retryable?.throttling === true) return true;
94
+ if (THROTTLE_ERROR_NAMES.has(error.name)) return true;
95
+ const status = error.status ?? error.$metadata?.httpStatusCode;
96
+ return status === 429 || (typeof status === "number" && status >= 500);
97
+ }
98
+
99
+ /** Is fuzzy variant expansion on for this turn? Most specific setting wins:
100
+ * the request, then the environment, then the config file, then the default,
101
+ * which is on. */
102
+ export function resolveFuzzyMode({ request, env = process.env, config } = {}) {
103
+ if (typeof request === "boolean") return request;
104
+ const fromEnv = env?.TMCT_RETRIEVAL_FUZZY;
105
+ if (fromEnv === "0" || fromEnv === "false") return false;
106
+ if (fromEnv === "1" || fromEnv === "true") return true;
107
+ if (typeof config === "boolean") return config;
108
+ return true;
109
+ }
110
+
111
+ const sleepFor = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });
112
+
113
+ /** A term query over a DynamoDB document client, in the band partition layout:
114
+ * partition `corpus:<band>`, sort key `fact#<term>#<rowKey>`, so one term is
115
+ * one `begins_with` Query. Pass the result as `queryTerm`. */
116
+ export function termQueryOverDocumentClient({ client, tableName, pageSize }) {
117
+ return async function queryTerm({ band, term, exclusiveStartKey, limit }) {
118
+ const response = await client.query({
119
+ TableName: tableName,
120
+ KeyConditionExpression: "pk = :pk AND begins_with(sk, :sk)",
121
+ ExpressionAttributeValues: { ":pk": `corpus:${band}`, ":sk": `fact#${term}#` },
122
+ Limit: limit ?? pageSize,
123
+ ...(exclusiveStartKey ? { ExclusiveStartKey: exclusiveStartKey } : {}),
124
+ });
125
+ return { rows: response?.Items || [], lastEvaluatedKey: response?.LastEvaluatedKey ?? null };
126
+ };
127
+ }
128
+
129
+ const byRowKey = (a, b) => (a.rowKey < b.rowKey ? -1 : a.rowKey > b.rowKey ? 1 : 0);
130
+
131
+ /** One Query, with exponential backoff on a systemic failure and no retry on
132
+ * anything else. Backoff happens inside the wall budget: when the next sleep
133
+ * would spend more time than retrieval has left, the read is given up instead
134
+ * of waited on. */
135
+ async function queryWithBackoff(request, run) {
136
+ let delay = run.budgets.backoffBaseMs;
137
+ for (let attempt = 0; ; attempt += 1) {
138
+ run.queries += 1;
139
+ try {
140
+ const response = await run.queryTerm(request);
141
+ return { rows: [...(response?.rows || [])].sort(byRowKey), lastEvaluatedKey: response?.lastEvaluatedKey ?? null };
142
+ } catch (error) {
143
+ run.failedQueries += 1;
144
+ if (!isSystemicFailure(error)) return { rows: [], lastEvaluatedKey: null, failed: true };
145
+ run.systemicFailures += 1;
146
+ const spent = run.now() - run.startedAt;
147
+ if (attempt >= run.budgets.queryRetries || spent + delay >= run.budgets.wallTimeMs) {
148
+ return { rows: [], lastEvaluatedKey: null, failed: true };
149
+ }
150
+ run.throttles += 1;
151
+ await run.sleep(delay);
152
+ delay *= 2;
153
+ }
154
+ }
155
+ }
156
+
157
+ /** The budget that has already stopped this run, or null while it can carry
158
+ * on. Checked between chunks, so a chunk already in flight finishes and its
159
+ * rows are folded in issue order. */
160
+ function trippedBudget(run) {
161
+ if (run.rows.length >= run.budgets.totalRows) return "totalRows";
162
+ if (run.queries >= run.budgets.totalQueries) return "totalQueries";
163
+ if (run.now() - run.startedAt >= run.budgets.wallTimeMs) return "wallTimeMs";
164
+ return null;
165
+ }
166
+
167
+ /** Fold one response into the run. Rows land in issue order, deduped by key,
168
+ * and the row budget cuts inside the page rather than after it, so the same
169
+ * inputs under a smaller budget stop at exactly the same row. */
170
+ function foldResponse(response, run) {
171
+ const fresh = [];
172
+ for (const row of response.rows) {
173
+ if (!row?.rowKey || run.seenRowKeys.has(row.rowKey)) continue;
174
+ if (run.rows.length >= run.budgets.totalRows) {
175
+ run.tripped = run.tripped ?? "totalRows";
176
+ break;
177
+ }
178
+ run.seenRowKeys.add(row.rowKey);
179
+ run.rows.push(row);
180
+ fresh.push(row);
181
+ }
182
+ if (response.failed) run.degraded = true;
183
+ return fresh;
184
+ }
185
+
186
+ /** Run one wave of term reads to exhaustion or to a budget, and return the rows
187
+ * it brought back. Pagination re-queues the same term behind the rest of the
188
+ * wave, which keeps the issue order a pure function of the plan. */
189
+ async function runWave(requests, run) {
190
+ const fresh = [];
191
+ let pending = requests;
192
+ while (pending.length) {
193
+ const stoppedBy = trippedBudget(run);
194
+ if (stoppedBy) { run.tripped = run.tripped ?? stoppedBy; break; }
195
+ const chunk = pending.slice(0, run.budgets.inFlightQueries);
196
+ const rest = pending.slice(run.budgets.inFlightQueries);
197
+ for (const request of chunk) run.readTerms.add(request.term);
198
+ const responses = await Promise.all(chunk.map((request) => queryWithBackoff(request, run)));
199
+ const continuations = [];
200
+ for (let i = 0; i < chunk.length; i += 1) {
201
+ fresh.push(...foldResponse(responses[i], run));
202
+ if (responses[i].lastEvaluatedKey) {
203
+ continuations.push({ ...chunk[i], exclusiveStartKey: responses[i].lastEvaluatedKey });
204
+ }
205
+ }
206
+ pending = [...rest, ...continuations];
207
+ }
208
+ return fresh;
209
+ }
210
+
211
+ /** Every (band, term) read one wave issues, in a fixed order: term first so a
212
+ * cut lands on whole terms wherever possible, band second. */
213
+ function requestsFor(terms, run) {
214
+ const requests = [];
215
+ for (const term of terms) {
216
+ if (run.plannedTerms.has(term)) continue;
217
+ run.plannedTerms.add(term);
218
+ for (const band of run.bands) requests.push({ band, term, limit: run.budgets.rowsPerQueryPage });
219
+ }
220
+ return requests;
221
+ }
222
+
223
+ /** Read a wave and record what phase paid for it, so a run can say where its
224
+ * Queries went. */
225
+ async function runPhase(terms, run, phase) {
226
+ const queriesBefore = run.queries;
227
+ const rowsBefore = run.rows.length;
228
+ const fresh = await runWave(requestsFor(terms, run), run);
229
+ run.queriesByPhase[phase] += run.queries - queriesBefore;
230
+ run.rowsByPhase[phase] += run.rows.length - rowsBefore;
231
+ return fresh;
232
+ }
233
+
234
+ /** Walk the subClassOf chain above `rows` until it closes. This runs before
235
+ * each wider hop because the inheritance lanes read exactly these rows, so a
236
+ * budget that stops the traversal takes the widest reads and not the ones an
237
+ * answer is most likely to stand on. A term is asked for once per turn, so a
238
+ * cycle in the taxonomy cannot loop here. */
239
+ async function chaseAncestry(rows, run) {
240
+ const found = [];
241
+ let terms = ancestryTerms(rows, { seen: run.plannedTerms });
242
+ while (terms.length && !run.tripped) {
243
+ const fresh = await runPhase(terms, run, "ancestry");
244
+ found.push(...fresh);
245
+ terms = ancestryTerms(fresh, { seen: run.plannedTerms });
246
+ }
247
+ return found;
248
+ }
249
+
250
+ /** Retrieve the corpus subgraph one turn can reach.
251
+ *
252
+ * `queryTerm({band, term, exclusiveStartKey, limit})` resolves to
253
+ * `{rows, lastEvaluatedKey}`. The read is injected, so the caller decides
254
+ * whether it comes from a document client, an HTTP route or a fixture.
255
+ *
256
+ * Returns `{rows, metrics, plan}`. `metrics.mode` and `metrics.bounded` are
257
+ * what an answer's honesty marker reads: `bounded` is true when a budget
258
+ * stopped the traversal or a read failed, which are the two ways the subgraph
259
+ * can hold less than the corpus does. */
260
+ export async function retrieveSubgraph({
261
+ text,
262
+ bands = [],
263
+ queryTerm = null,
264
+ fuzzy = true,
265
+ skip = false,
266
+ lexicon = loadLexicon(),
267
+ vocabulary = null,
268
+ budgets: budgetOverrides = null,
269
+ now = () => Date.now(),
270
+ sleep = sleepFor,
271
+ }) {
272
+ // A partial override keeps every budget it did not name. A missing cap would
273
+ // otherwise read as no cap, which is the one thing this module must never do.
274
+ const budgets = budgetOverrides ? { ...RETRIEVAL_BUDGETS, ...budgetOverrides } : RETRIEVAL_BUDGETS;
275
+ const startedAt = now();
276
+ const plan = buildRetrievalPlan({
277
+ text, fuzzy, lexicon, vocabulary,
278
+ hopDepth: budgets.hopDepth,
279
+ fuzzyVariantsPerTerm: budgets.fuzzyVariantsPerTerm,
280
+ });
281
+ const sortedBands = [...bands].sort();
282
+
283
+ if (skip || !queryTerm || sortedBands.length === 0) {
284
+ return {
285
+ rows: [],
286
+ plan,
287
+ metrics: metricsOf({
288
+ plan, bands: sortedBands, mode: SEED_SESSION_MODE, elapsedMs: now() - startedAt,
289
+ }),
290
+ };
291
+ }
292
+
293
+ const run = {
294
+ budgets, queryTerm, now, sleep, startedAt,
295
+ bands: sortedBands,
296
+ rows: [],
297
+ seenRowKeys: new Set(),
298
+ plannedTerms: new Set(), readTerms: new Set(),
299
+ queries: 0,
300
+ failedQueries: 0,
301
+ systemicFailures: 0,
302
+ throttles: 0,
303
+ tripped: null,
304
+ degraded: false,
305
+ hops: 0,
306
+ queriesByPhase: { seed: 0, ancestry: 0, expansion: 0 },
307
+ rowsByPhase: { seed: 0, ancestry: 0, expansion: 0 },
308
+ };
309
+
310
+ // The words the turn actually contained are read before any variant of them.
311
+ // Under a tight query budget that ordering is the difference between a guess
312
+ // spending the read the real term needed and the real term getting it.
313
+ let wave = [
314
+ ...plan.terms.filter((entry) => entry.origin === "exact").map((entry) => entry.term),
315
+ ...plan.terms.filter((entry) => entry.origin === "fuzzy").map((entry) => entry.term),
316
+ ];
317
+ for (let hop = 0; hop <= budgets.hopDepth && wave.length; hop += 1) {
318
+ const fresh = await runPhase(wave, run, hop === 0 ? "seed" : "expansion");
319
+ run.hops = hop;
320
+ const inherited = await chaseAncestry(fresh, run);
321
+ if (run.tripped) break;
322
+ wave = expandedTerms([...fresh, ...inherited], { seen: run.plannedTerms });
323
+ }
324
+
325
+ return {
326
+ rows: run.rows,
327
+ plan,
328
+ metrics: metricsOf({
329
+ plan,
330
+ bands: sortedBands,
331
+ mode: SUPPLEMENTED_MODE,
332
+ elapsedMs: now() - startedAt,
333
+ run,
334
+ }),
335
+ };
336
+ }
337
+
338
+ function metricsOf({ plan, bands, mode, elapsedMs, run = null }) {
339
+ const exactTerms = plan.terms.filter((entry) => entry.origin === "exact").length;
340
+ return {
341
+ mode,
342
+ bounded: Boolean(run && (run.tripped || run.degraded)),
343
+ tripped: run?.tripped ?? null,
344
+ fuzzy: plan.fuzzy,
345
+ bands,
346
+ planTerms: plan.terms.length,
347
+ exactTerms,
348
+ fuzzyTerms: plan.terms.length - exactTerms,
349
+ termsPlanned: run ? run.plannedTerms.size : 0,
350
+ termsRead: run ? run.readTerms.size : 0,
351
+ queries: run?.queries ?? 0,
352
+ rows: run?.rows.length ?? 0,
353
+ hops: run?.hops ?? 0,
354
+ failedQueries: run?.failedQueries ?? 0,
355
+ systemicFailures: run?.systemicFailures ?? 0,
356
+ throttles: run?.throttles ?? 0,
357
+ queriesByPhase: run ? { ...run.queriesByPhase } : { seed: 0, ancestry: 0, expansion: 0 },
358
+ rowsByPhase: run ? { ...run.rowsByPhase } : { seed: 0, ancestry: 0, expansion: 0 },
359
+ elapsedMs,
360
+ };
361
+ }