@flyingrobots/parley-read 0.0.0-stage → 0.1.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.
- package/CHANGELOG.md +272 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +560 -2
- package/package.json +39 -4
- package/src/digest.ts +438 -0
- package/src/fold.ts +166 -0
- package/src/index.ts +10 -0
- package/src/lines.ts +77 -0
- package/src/load.ts +711 -0
- package/src/locate.ts +70 -0
- package/src/open.ts +435 -0
- package/src/query.ts +760 -0
- package/src/rank.ts +309 -0
- package/src/schemas.ts +2042 -0
- package/src/validate.ts +94 -0
package/src/digest.ts
ADDED
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
// The first response to a read is a digest (spec §9, informative; flyingrobots/parley#50).
|
|
2
|
+
//
|
|
3
|
+
// §9 asks two things of a result that this module is the whole of: it "carries its own lens — the
|
|
4
|
+
// observer, the purpose and the window that produced it — so a later reader knows what it is
|
|
5
|
+
// looking at and **cannot mistake a digest for the whole**", and it "reports what it excluded, at
|
|
6
|
+
// least as a count, so a caller can widen deliberately rather than never learning what it
|
|
7
|
+
// missed". The failure mode §9 names against is over-filtering: a result that reads as complete
|
|
8
|
+
// when it is not.
|
|
9
|
+
//
|
|
10
|
+
// The digest is the `parley.lens` 1.0.0 record decided in flyingrobots/parley#46 — not a new
|
|
11
|
+
// message. That decision already gives a lens the asker, the view, the budget applied, the
|
|
12
|
+
// window, the query it answers by `(run, seq)`, a `loss` bound with the excluded count beside it,
|
|
13
|
+
// and the records it was built from by `(run, seq)`, which is the way back a drill-down takes
|
|
14
|
+
// (`openRecords`, flyingrobots/parley#51). Inventing a second message for the same job would have been this
|
|
15
|
+
// library redeciding a decided one.
|
|
16
|
+
//
|
|
17
|
+
// **The bound, exactly.** `budget.records` is required and bounds the count: the digest names at
|
|
18
|
+
// most that many records. `budget.bytes` is optional and bounds the line: when it is stated, the
|
|
19
|
+
// `parley.lens` line the read writes — serialised JSON plus its newline, measured in UTF-8 bytes
|
|
20
|
+
// — is at most that many bytes, and records are dropped from the end of the ranking until it
|
|
21
|
+
// fits. The envelope and the lens's own fields are not negotiable, because a lens that dropped
|
|
22
|
+
// them would no longer say what it is, so a `bytes` budget too small even for a digest naming no
|
|
23
|
+
// records cannot be met at all: `digestFor` reports that as `fits: false`, and the read declines
|
|
24
|
+
// rather than write a line over the bound, naming the smallest budget that would hold one
|
|
25
|
+
// (`sufficientBytes`, flyingrobots/parley#71). `budget.ms` is a deadline on the read as a whole,
|
|
26
|
+
// not on the digest, and is applied in `query.ts`.
|
|
27
|
+
//
|
|
28
|
+
// **What the bound cuts is the tail of the ranking**, never a record chosen some other way. The
|
|
29
|
+
// order is `rankRecords`'s total order (flyingrobots/parley#49), which reorders and never filters,
|
|
30
|
+
// so "the records the digest does not name" is exactly "the records the fold left out and the
|
|
31
|
+
// records the ranking placed beyond the bound" — two numbers the loss can state honestly, and does.
|
|
32
|
+
// A digest built over a filtered ranking could not.
|
|
33
|
+
//
|
|
34
|
+
// **`loss.bound` is `none` only when `loss.excluded` is 0**, and the schema refuses the other
|
|
35
|
+
// pairing, so a digest that left something out says so structurally rather than in prose. Since
|
|
36
|
+
// ranking reorders and never filters, a digest that reached the end of its ranking lost nothing at
|
|
37
|
+
// all, whichever view produced it.
|
|
38
|
+
//
|
|
39
|
+
// **Each name carries a summary** (flyingrobots/parley#77). A record named by `(run, seq)` alone
|
|
40
|
+
// has to be opened before a reader can tell an `error` from a `receipt.step`, so every entry also
|
|
41
|
+
// carries the record's `event` and `t` and the outcome the ranking established for its run. The
|
|
42
|
+
// summary is read off the loaded record when the digest is built, never from anywhere else, so it
|
|
43
|
+
// cannot drift from the record; a field the record does not carry usably is left out rather than
|
|
44
|
+
// filled in. It is part of the line, so `budget.bytes` bounds it like everything else.
|
|
45
|
+
//
|
|
46
|
+
// **Each run is stated once** (flyingrobots/parley#83). Which invocation a run was is the same for
|
|
47
|
+
// every record of it, so it is said in the lens's `runs` section, once per run the entries name,
|
|
48
|
+
// rather than on each entry: the head's `tool`, `v`, `argv` and `inv`, the run's outcome over the
|
|
49
|
+
// whole window, and, when that outcome is `undetermined`, a `reason` from a closed vocabulary.
|
|
50
|
+
// The outcome moved there from the entries, where a four-record run repeated it four times. An
|
|
51
|
+
// entry keeps its `event` and `t`, and an `error` or `warning` entry also carries its `code`, so
|
|
52
|
+
// three failures of one case read as one case without opening them. A section is read off the
|
|
53
|
+
// window's own records, the same ones the ranking was given, so it cannot drift from the head it
|
|
54
|
+
// summarises; a run whose head the window does not hold still gets a section, saying so.
|
|
55
|
+
//
|
|
56
|
+
// **A section says what the run compared** (flyingrobots/parley#90). `argv` says `HEAD~1..HEAD`;
|
|
57
|
+
// only the head's `resolved`, the interpretation after defaults and environment (§5), says which
|
|
58
|
+
// two commits that was. So a section carries `resolved` too, copied whole off the head and already
|
|
59
|
+
// redacted there (§5.3). It is the tool's own shape, so the reader chooses none of its keys: a
|
|
60
|
+
// subset picked by name would be one tool's field names living in the reader, and a declared
|
|
61
|
+
// subset could drift from the head it summarises.
|
|
62
|
+
//
|
|
63
|
+
// **A section is bounded** by `RUN_SECTION_BYTES`: when its serialised JSON is larger, whole
|
|
64
|
+
// fields are dropped, `resolved` first, then `argv`, `inv`, `v` and `tool`, until it fits, and the
|
|
65
|
+
// section names what it dropped in `dropped`. `resolved` goes first because it is the largest and
|
|
66
|
+
// the tool's own shape, while `argv` is the protocol's. A string is never cut part-way, because a cut
|
|
67
|
+
// argument reads as a different argument. The run's id, outcome, reason and head statement are
|
|
68
|
+
// never dropped: without them the section does not say which run it is or what became of it.
|
|
69
|
+
//
|
|
70
|
+
// **Runs of one invocation with one result are named once** (flyingrobots/parley#79, `fold.ts`).
|
|
71
|
+
// Before the bound is applied, the runs whose `inv` and whole result are equal are folded into
|
|
72
|
+
// their most recent run: the others' records are not named, the representative's section says
|
|
73
|
+
// `folded: {others, records}`, both counting the others only (flyingrobots/parley#100), and
|
|
74
|
+
// `loss.folded` counts every record the fold left out. Those
|
|
75
|
+
// records are in `loss.excluded` too, so the count still accounts for every record not named, and
|
|
76
|
+
// `excluded − folded` is what the budget cut.
|
|
77
|
+
import { foldRuns, type RunFold } from "./fold.ts";
|
|
78
|
+
import type { LoadedRecord } from "./load.ts";
|
|
79
|
+
import type { AcceptedQuery, Asker, Budget, QueryWindow, View } from "./query.ts";
|
|
80
|
+
import type { Outcome } from "./rank.ts";
|
|
81
|
+
|
|
82
|
+
/** The `parley.lens` pair a digest is emitted as; a change to the message moves this version. */
|
|
83
|
+
export const LENS_SCHEMA = { id: "parley.lens", version: "1.0.0" } as const;
|
|
84
|
+
|
|
85
|
+
/** What kind of statement the loss is. `none` is only ever paired with an excluded count of 0. */
|
|
86
|
+
export type LossBound = "none" | "count-only";
|
|
87
|
+
|
|
88
|
+
/** A record named by its identity (§1.3), which is what a lens stores rather than the record itself. */
|
|
89
|
+
export interface RecordRef {
|
|
90
|
+
readonly run: string;
|
|
91
|
+
readonly seq: number;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* One record a digest names: its identity, which is the way back to it, and a fixed summary of it
|
|
96
|
+
* so a reader can choose what to open. Each summary field is present only when it is known:
|
|
97
|
+
*
|
|
98
|
+
* - `event`: the record's event token as the loader reports it, a tool's own included verbatim;
|
|
99
|
+
* absent when the record carries none.
|
|
100
|
+
* - `t`: the record's POSIX milliseconds as the loader reports them; absent when the record has no
|
|
101
|
+
* non-negative integer `t`, rather than a made-up one.
|
|
102
|
+
* - `outcome`: what the ranked window establishes about the record's run (`rank.ts`), which is the
|
|
103
|
+
* window's verdict and not the digest's prefix's; absent when no ranking outcomes were given.
|
|
104
|
+
*/
|
|
105
|
+
export interface LensEntry extends RecordRef {
|
|
106
|
+
readonly event?: string;
|
|
107
|
+
readonly t?: number;
|
|
108
|
+
/** An `error` or `warning` record's code (spec §6); absent on any other record and on a malformed code. */
|
|
109
|
+
readonly code?: string;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Why a run's outcome is `undetermined`, from a closed set that covers every way `runOutcomes`
|
|
114
|
+
* reaches it: the window holds no `end` for the run, or it holds one whose `status` is not a
|
|
115
|
+
* number. A missing `end` is not a successful one (§1.2a); the window cannot say whether the run
|
|
116
|
+
* ended later or never did.
|
|
117
|
+
*/
|
|
118
|
+
export const UNDETERMINED_REASONS = ["no_end_in_window", "end_status_unusable"] as const;
|
|
119
|
+
export type UndeterminedReason = (typeof UNDETERMINED_REASONS)[number];
|
|
120
|
+
|
|
121
|
+
/** The fields a section may drop to fit `RUN_SECTION_BYTES`, in the order they are dropped. */
|
|
122
|
+
export const DROPPABLE = ["resolved", "argv", "inv", "v", "tool"] as const;
|
|
123
|
+
export type Droppable = (typeof DROPPABLE)[number];
|
|
124
|
+
|
|
125
|
+
/** The most UTF-8 bytes one run section's serialised JSON takes, unless its undroppable fields alone exceed it. */
|
|
126
|
+
export const RUN_SECTION_BYTES = 512;
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* What a lens says about one run its entries name, once. Every field but `run` is present only
|
|
130
|
+
* when it is known:
|
|
131
|
+
*
|
|
132
|
+
* - `tool`, `v`, `argv`: the run's `receipt.head` as the loader read it, when the window holds the
|
|
133
|
+
* head; `argv` is already redacted there (§5.3).
|
|
134
|
+
* - `resolved`: the head's `resolved`, whole, when it is a JSON object; redacted there too (§5.3).
|
|
135
|
+
* - `inv`: the head's, or else the window's `receipt.inputs` for the run (§2.2).
|
|
136
|
+
* - `outcome`: the window's verdict on the run (`rank.ts`), absent when no outcomes were given.
|
|
137
|
+
* - `reason`: present exactly when `outcome` is `undetermined`.
|
|
138
|
+
* - `head`: `not_in_window` when the window does not hold the run's head; absent when it does.
|
|
139
|
+
* - `folded`: present on a run that stands for others of one invocation with one result
|
|
140
|
+
* (`fold.ts`): how many other runs it stands for and how many of their records the fold left
|
|
141
|
+
* out, both excluding this run (flyingrobots/parley#100). Never dropped.
|
|
142
|
+
* - `dropped`: the fields left out to fit `RUN_SECTION_BYTES`, in the order they were dropped.
|
|
143
|
+
*/
|
|
144
|
+
export interface RunSection {
|
|
145
|
+
readonly run: string;
|
|
146
|
+
readonly tool?: string;
|
|
147
|
+
readonly v?: string;
|
|
148
|
+
readonly argv?: readonly string[];
|
|
149
|
+
readonly resolved?: Readonly<Record<string, unknown>>;
|
|
150
|
+
readonly inv?: string;
|
|
151
|
+
readonly outcome?: Outcome;
|
|
152
|
+
readonly reason?: UndeterminedReason;
|
|
153
|
+
readonly head?: "not_in_window";
|
|
154
|
+
readonly folded?: RunFold;
|
|
155
|
+
readonly dropped?: readonly Droppable[];
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* What the digest lost against the records it was drawn from. The count is a proxy and a weak one
|
|
160
|
+
* — one withheld record can matter more than fifty — which is why `bound` says what kind of
|
|
161
|
+
* statement it is rather than letting a caller read the number as a distortion bound.
|
|
162
|
+
*/
|
|
163
|
+
export interface Loss {
|
|
164
|
+
readonly bound: LossBound;
|
|
165
|
+
/** Every record of the window the digest does not name, whatever left it out. */
|
|
166
|
+
readonly excluded: number;
|
|
167
|
+
/**
|
|
168
|
+
* How many of `excluded` the fold left out (flyingrobots/parley#79): the records of runs folded
|
|
169
|
+
* into a representative. It depends on the window alone, never on the budget, and
|
|
170
|
+
* `excluded − folded` is what the budget cut. Zero is a count, not an absence.
|
|
171
|
+
*/
|
|
172
|
+
readonly folded: number;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** The `parley.lens` payload. The writer owns the envelope (§1.3), so `t`, `seq` and `run` are not here. */
|
|
176
|
+
export interface Digest {
|
|
177
|
+
readonly event: "lens";
|
|
178
|
+
/** The recorded query this digest answers, by `(run, seq)`. */
|
|
179
|
+
readonly query: RecordRef;
|
|
180
|
+
readonly asker: Asker;
|
|
181
|
+
readonly view: View;
|
|
182
|
+
/** The budget actually applied, the default included: two digests under different budgets are not comparable. */
|
|
183
|
+
readonly budget: Budget;
|
|
184
|
+
readonly window: QueryWindow;
|
|
185
|
+
readonly loss: Loss;
|
|
186
|
+
/** One section per run `records` names, in the order the entries first name them. */
|
|
187
|
+
readonly runs: readonly RunSection[];
|
|
188
|
+
/** The records the digest names, in rank order, never more than `budget.records` of them, each with its summary. */
|
|
189
|
+
readonly records: readonly LensEntry[];
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** The envelope the writer will put on the digest's line, which the byte bound is measured against. */
|
|
193
|
+
export interface LineEnvelope {
|
|
194
|
+
readonly run: string;
|
|
195
|
+
readonly seq: number;
|
|
196
|
+
readonly t: number;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export interface Digested {
|
|
200
|
+
readonly digest: Digest;
|
|
201
|
+
/** The records the digest names, in full and in rank order. */
|
|
202
|
+
readonly records: readonly LoadedRecord[];
|
|
203
|
+
/** How many records of the ranking the digest does not name, the folded ones included. Zero is a count, not an absence. */
|
|
204
|
+
readonly excluded: number;
|
|
205
|
+
/** How many of `excluded` the fold left out rather than the bound (`fold.ts`). */
|
|
206
|
+
readonly folded: number;
|
|
207
|
+
/** The digest's line in UTF-8 bytes, its newline included, as the writer will write it. */
|
|
208
|
+
readonly bytes: number;
|
|
209
|
+
/**
|
|
210
|
+
* Whether the line is within `budget.bytes`. Always true when no byte bound is stated; false only
|
|
211
|
+
* when even a digest naming no records is over it, which the read declines rather than writes.
|
|
212
|
+
*/
|
|
213
|
+
readonly fits: boolean;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Spec §6's code shape, the same pattern `parley.error` and `parley.warning` declare. */
|
|
217
|
+
const CODE = /^[a-z0-9_]+(\.[a-z0-9_]+)+$/;
|
|
218
|
+
|
|
219
|
+
const nonEmpty = (value: unknown): value is string => typeof value === "string" && value.length > 0;
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* The entry a digest names a record by, read off the loaded record. The key order is fixed,
|
|
223
|
+
* `run, seq, event, t, code`, because the byte bound is measured against the serialised line.
|
|
224
|
+
*/
|
|
225
|
+
export function lensEntry(record: LoadedRecord): LensEntry {
|
|
226
|
+
const code = record.record.code;
|
|
227
|
+
const coded = (record.event === "error" || record.event === "warning") && typeof code === "string" && CODE.test(code);
|
|
228
|
+
return {
|
|
229
|
+
run: record.run,
|
|
230
|
+
seq: record.seq,
|
|
231
|
+
...(nonEmpty(record.event) ? { event: record.event } : {}),
|
|
232
|
+
...(typeof record.t === "number" && Number.isInteger(record.t) && record.t >= 0 ? { t: record.t } : {}),
|
|
233
|
+
...(coded ? { code } : {}),
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const sectionBytes = (section: RunSection) => Buffer.byteLength(JSON.stringify(section), "utf8");
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* What a lens says about one run, read off the window's records for it (`window` may hold other
|
|
241
|
+
* runs' records too; `digestFor` passes only the run's own) and the window's outcomes, with the
|
|
242
|
+
* run's fold when it stands for others. The key order is fixed, `run, tool, v, argv, resolved, inv,
|
|
243
|
+
* outcome, reason, head, folded, dropped`, and the section is bounded by `RUN_SECTION_BYTES` by dropping
|
|
244
|
+
* whole fields, never by cutting a string.
|
|
245
|
+
*/
|
|
246
|
+
export function runSection(run: string, window: readonly LoadedRecord[], outcomes?: Readonly<Record<string, Outcome>>, fold?: RunFold): RunSection {
|
|
247
|
+
const own = window.filter((r) => r.run === run);
|
|
248
|
+
const head = own.find((r) => r.event === "receipt.head");
|
|
249
|
+
const inputs = own.find((r) => r.event === "receipt.inputs" && nonEmpty(r.record.inv));
|
|
250
|
+
const argv = head?.record.argv;
|
|
251
|
+
const resolved = head?.record.resolved;
|
|
252
|
+
const inv = nonEmpty(head?.record.inv) ? head.record.inv : inputs?.record.inv as string | undefined;
|
|
253
|
+
const outcome = outcomes?.[run];
|
|
254
|
+
const reason: UndeterminedReason | undefined = outcome !== "undetermined"
|
|
255
|
+
? undefined
|
|
256
|
+
: own.some((r) => r.event === "end") ? "end_status_unusable" : "no_end_in_window";
|
|
257
|
+
const fields: Partial<Record<Droppable, unknown>> = {
|
|
258
|
+
...(nonEmpty(head?.record.tool) ? { tool: head.record.tool } : {}),
|
|
259
|
+
...(nonEmpty(head?.record.v) ? { v: head.record.v } : {}),
|
|
260
|
+
...(Array.isArray(argv) && argv.every((a) => typeof a === "string") ? { argv } : {}),
|
|
261
|
+
...(resolved !== null && typeof resolved === "object" && !Array.isArray(resolved) ? { resolved } : {}),
|
|
262
|
+
...(inv === undefined ? {} : { inv }),
|
|
263
|
+
};
|
|
264
|
+
const build = (dropped: readonly Droppable[]): RunSection => {
|
|
265
|
+
const kept = (k: Droppable) => (k in fields && !dropped.includes(k) ? { [k]: fields[k] } : {});
|
|
266
|
+
return {
|
|
267
|
+
run,
|
|
268
|
+
...kept("tool"),
|
|
269
|
+
...kept("v"),
|
|
270
|
+
...kept("argv"),
|
|
271
|
+
...kept("resolved"),
|
|
272
|
+
...kept("inv"),
|
|
273
|
+
...(outcome === undefined ? {} : { outcome }),
|
|
274
|
+
...(reason === undefined ? {} : { reason }),
|
|
275
|
+
...(head === undefined ? { head: "not_in_window" as const } : {}),
|
|
276
|
+
...(fold === undefined ? {} : { folded: { others: fold.others, records: fold.records } }),
|
|
277
|
+
...(dropped.length === 0 ? {} : { dropped: [...dropped] }),
|
|
278
|
+
} as RunSection;
|
|
279
|
+
};
|
|
280
|
+
const dropped: Droppable[] = [];
|
|
281
|
+
let section = build(dropped);
|
|
282
|
+
for (const field of DROPPABLE) {
|
|
283
|
+
if (sectionBytes(section) <= RUN_SECTION_BYTES) break;
|
|
284
|
+
if (!(field in fields)) continue;
|
|
285
|
+
dropped.push(field);
|
|
286
|
+
section = build(dropped);
|
|
287
|
+
}
|
|
288
|
+
return section;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* The line the writer will write for this digest, byte for byte.
|
|
293
|
+
*
|
|
294
|
+
* The writer builds a record as `{event, t, seq, run, ...payload, _schema}` and writes
|
|
295
|
+
* `JSON.stringify(record) + "\n"` (spec §1.1, §1.3), and a read declares no secrets, so nothing
|
|
296
|
+
* is scrubbed and the payload's own key order survives. Reconstructing it here is what lets a
|
|
297
|
+
* byte budget be applied **before** the line is written rather than discovered after it.
|
|
298
|
+
*/
|
|
299
|
+
export function digestLine(digest: Digest, envelope: LineEnvelope): string {
|
|
300
|
+
const { event, ...rest } = digest;
|
|
301
|
+
return JSON.stringify({
|
|
302
|
+
event,
|
|
303
|
+
t: envelope.t,
|
|
304
|
+
seq: envelope.seq,
|
|
305
|
+
run: envelope.run,
|
|
306
|
+
...rest,
|
|
307
|
+
_schema: { id: LENS_SCHEMA.id, version: LENS_SCHEMA.version },
|
|
308
|
+
}) + "\n";
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** The digest's line in UTF-8 bytes, its newline included. */
|
|
312
|
+
export function digestBytes(digest: Digest, envelope: LineEnvelope): number {
|
|
313
|
+
return Buffer.byteLength(digestLine(digest, envelope), "utf8");
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* The digest naming `kept`, the head of a ranking `total` records long of which the fold left
|
|
318
|
+
* `folded` out, with `runs`, one section per run `kept` names. The one place the lens payload's
|
|
319
|
+
* shape and key order are written, so the smallest digest `sufficientBytes` measures is the digest
|
|
320
|
+
* `digestFor` would write.
|
|
321
|
+
*/
|
|
322
|
+
function buildDigest(query: AcceptedQuery, answers: RecordRef, kept: readonly LensEntry[], total: number, runs: readonly RunSection[], folded: number): Digest {
|
|
323
|
+
const excluded = total - kept.length;
|
|
324
|
+
return {
|
|
325
|
+
event: "lens",
|
|
326
|
+
query: answers,
|
|
327
|
+
asker: query.asker,
|
|
328
|
+
view: query.view,
|
|
329
|
+
budget: query.budget,
|
|
330
|
+
window: query.window,
|
|
331
|
+
// `none` is a claim that nothing was left out, so it is only ever paired with 0; the schema
|
|
332
|
+
// refuses `none` beside a non-zero count (flyingrobots/parley#46).
|
|
333
|
+
// A fold leaves records out, so a digest that folded anything is never `none`.
|
|
334
|
+
loss: { bound: excluded === 0 ? "none" : "count-only", excluded, folded },
|
|
335
|
+
runs,
|
|
336
|
+
records: kept,
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* The smallest `budget.bytes` under which this query's digest, over a ranking `total` records
|
|
342
|
+
* long of which the fold leaves `folded` out (`Digested.folded`; 0 when nothing folds), can be
|
|
343
|
+
* written at all: the line of a digest naming no records, with that very number as its stated
|
|
344
|
+
* `bytes`. Pure.
|
|
345
|
+
*
|
|
346
|
+
* The digest carries the budget it was bounded by, so the size depends on the digits of the bound
|
|
347
|
+
* itself. The search starts from 1 and takes the size the line would have under the current
|
|
348
|
+
* candidate, until a candidate holds its own line. Each step is a size some smaller candidate
|
|
349
|
+
* already needed, so no smaller bound can fit and the first fixed point is the least one; the size
|
|
350
|
+
* only grows with the digits of the bound, so it stops within a few steps.
|
|
351
|
+
*
|
|
352
|
+
* The answer is exact for a read of the same question over the same ranking, measured against the
|
|
353
|
+
* same envelope: `digestFor` under it names no records and fits, and one byte less does not.
|
|
354
|
+
*/
|
|
355
|
+
export function sufficientBytes(query: AcceptedQuery, answers: RecordRef, total: number, envelope: LineEnvelope, folded = 0): number {
|
|
356
|
+
const size = (bytes: number) =>
|
|
357
|
+
// A digest naming no records names no runs either: its `runs` is empty, as `digestFor` writes it.
|
|
358
|
+
digestBytes(buildDigest({ ...query, budget: { ...query.budget, bytes } }, answers, [], total, [], folded), envelope);
|
|
359
|
+
let bytes = 1;
|
|
360
|
+
for (let next = size(bytes); next > bytes; next = size(bytes)) bytes = next;
|
|
361
|
+
return bytes;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* Bound a ranking to a query's budget and state what that cost.
|
|
366
|
+
*
|
|
367
|
+
* Pure: it reads nothing, writes nothing, records nothing, and mutates neither its arguments nor
|
|
368
|
+
* the records in them. `ranked` is the whole of the window in rank order
|
|
369
|
+
* (flyingrobots/parley#49). The runs of one invocation with one result are folded first
|
|
370
|
+
* (`fold.ts`), which needs `outcomes`; the digest is the prefix of what the fold leaves, in the
|
|
371
|
+
* same order, and `excluded` is the rest of the window counted, the folded records included.
|
|
372
|
+
* `outcomes` is the ranking's verdict per run over that whole window, and each run section carries
|
|
373
|
+
* its run's; without it, no section carries an outcome or a reason. Each section is read off the
|
|
374
|
+
* whole window too, so a head the bound cut from the entries still identifies its run.
|
|
375
|
+
*
|
|
376
|
+
* The byte search is a binary search over the prefix length, which is sound because the line only
|
|
377
|
+
* grows as the prefix does: one more record adds its entry, at least its `(run, seq)` pair, and
|
|
378
|
+
* perhaps its run's section, while the excluded count beside it can shrink by at most one digit
|
|
379
|
+
* and `loss.bound` by the six bytes between `count-only` and `none`.
|
|
380
|
+
*/
|
|
381
|
+
export function digestFor(
|
|
382
|
+
query: AcceptedQuery,
|
|
383
|
+
answers: RecordRef,
|
|
384
|
+
ranked: readonly LoadedRecord[],
|
|
385
|
+
envelope: LineEnvelope,
|
|
386
|
+
outcomes?: Readonly<Record<string, Outcome>>,
|
|
387
|
+
): Digested {
|
|
388
|
+
// The fold depends on the window and its outcomes, never on the budget.
|
|
389
|
+
const folding = foldRuns(ranked, outcomes);
|
|
390
|
+
const named = folding.records;
|
|
391
|
+
// Built once, so every candidate prefix the byte search measures is cut from the same entries.
|
|
392
|
+
const entries = named.map((record) => lensEntry(record));
|
|
393
|
+
// One pass over the window groups each run's records, so a section never scans the whole
|
|
394
|
+
// window for its own (RD-80h).
|
|
395
|
+
const byRun = new Map<string, LoadedRecord[]>();
|
|
396
|
+
for (const record of ranked) {
|
|
397
|
+
const own = byRun.get(record.run);
|
|
398
|
+
if (own === undefined) byRun.set(record.run, [record]);
|
|
399
|
+
else own.push(record);
|
|
400
|
+
}
|
|
401
|
+
const sections = new Map<string, RunSection>();
|
|
402
|
+
const sectionOf = (run: string) => {
|
|
403
|
+
let section = sections.get(run);
|
|
404
|
+
if (section === undefined) sections.set(run, section = runSection(run, byRun.get(run) ?? [], outcomes, folding.folds.get(run)));
|
|
405
|
+
return section;
|
|
406
|
+
};
|
|
407
|
+
const build = (keep: number): Digest => {
|
|
408
|
+
const kept = entries.slice(0, keep);
|
|
409
|
+
return buildDigest(query, answers, kept, ranked.length, [...new Set(kept.map((e) => e.run))].map(sectionOf), folding.folded);
|
|
410
|
+
};
|
|
411
|
+
|
|
412
|
+
let keep = Math.min(named.length, query.budget.records);
|
|
413
|
+
const bytes = query.budget.bytes;
|
|
414
|
+
if (bytes !== undefined && digestBytes(build(keep), envelope) > bytes) {
|
|
415
|
+
// The largest prefix whose line fits. `lo` is a length that is kept rather than one known to
|
|
416
|
+
// fit: a budget too small even for an empty digest leaves 0, and `fits` below says the bound
|
|
417
|
+
// could not be met, so the read declines instead of writing the line.
|
|
418
|
+
let lo = 0;
|
|
419
|
+
let hi = keep;
|
|
420
|
+
while (lo < hi) {
|
|
421
|
+
const mid = Math.ceil((lo + hi) / 2);
|
|
422
|
+
if (digestBytes(build(mid), envelope) <= bytes) lo = mid;
|
|
423
|
+
else hi = mid - 1;
|
|
424
|
+
}
|
|
425
|
+
keep = lo;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
const digest = build(keep);
|
|
429
|
+
const size = digestBytes(digest, envelope);
|
|
430
|
+
return {
|
|
431
|
+
digest,
|
|
432
|
+
records: named.slice(0, keep),
|
|
433
|
+
excluded: ranked.length - keep,
|
|
434
|
+
folded: folding.folded,
|
|
435
|
+
bytes: size,
|
|
436
|
+
fits: bytes === undefined || size <= bytes,
|
|
437
|
+
};
|
|
438
|
+
}
|
package/src/fold.ts
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
// Runs of one invocation with one result are named once (flyingrobots/parley#79).
|
|
2
|
+
//
|
|
3
|
+
// A test suite runs its program many times in a burst with the same few argument vectors, and in
|
|
4
|
+
// the cold resume (`docs/topics/reader/cold-resume.md`) those bursts filled every digest of 20 with
|
|
5
|
+
// the same runs: the same three `git.diff_failed` errors, the same pair of warnings from each of
|
|
6
|
+
// fifteen runs. The distinct things that happened were few, and a digest could not reach past the
|
|
7
|
+
// first burst. A digest therefore **folds** runs that are the same invocation with the same
|
|
8
|
+
// result into one representative, and the representative's run section says how many runs it
|
|
9
|
+
// stands for and how many of their records the fold left out.
|
|
10
|
+
//
|
|
11
|
+
// **What "the same" is.** §2.2's `inv` is the run's identity: the same tool and version, the same
|
|
12
|
+
// normalised arguments, the same input content. It is not the run's result, and §2.3 is explicit
|
|
13
|
+
// that "same `inv`, different result" is a divergence, the thing a reader most needs to see. So
|
|
14
|
+
// two runs fold only when their `inv` is equal **and** every summary a lens would state about the
|
|
15
|
+
// run is equal too: the outcome, the `reason` an undetermined outcome carries, the `end` status,
|
|
16
|
+
// the error, warning and startup-failure codes in the order the run emitted them, and the head's
|
|
17
|
+
// `resolved`, which the section carries (flyingrobots/parley#90). A flaky run
|
|
18
|
+
// that failed once and passed once is two results and two sections, never one.
|
|
19
|
+
//
|
|
20
|
+
// **What never folds.**
|
|
21
|
+
// - A run with no `inv`. §2.2 makes `inv` SHOULD in v0.2 and omits it when the program cannot
|
|
22
|
+
// make it safe, and a discovery run (§4.1) has none: without it there is no claim of identity to
|
|
23
|
+
// fold by, and argument vectors are not identity.
|
|
24
|
+
// - A redacted run: one whose head carries `redacted`, whose `end` says `redacted: true`, or that
|
|
25
|
+
// emitted a `redaction`. §2.3 says a redacted receipt shares its `inv` with every run that
|
|
26
|
+
// differed only in a secret, so equal `inv` does not make it the same invocation as anything.
|
|
27
|
+
// Nor a run the window cannot show is unredacted, because it holds neither its head nor an `end`
|
|
28
|
+
// saying `redacted: false`: a missing statement is not a negative one (§1.2a).
|
|
29
|
+
// - Anything when the caller states no outcomes: "the same result" cannot be established.
|
|
30
|
+
//
|
|
31
|
+
// **The representative is the most recent run of its group**: the one whose latest dated record
|
|
32
|
+
// in the window is latest, ties broken by the greater run id. The most recent run is the one a
|
|
33
|
+
// resuming reader is likeliest to act on, and its head is the current statement of the invocation.
|
|
34
|
+
//
|
|
35
|
+
// **The fold is part of how the digest is built, not a view** and not a ranking. The ranking still
|
|
36
|
+
// orders every record of the window and drops none of them; the fold removes the records of
|
|
37
|
+
// folded-away runs from what the digest may name, keeping the ranking's order, and the digest's
|
|
38
|
+
// bound cuts the tail of what remains. Every record the fold removed is still counted in
|
|
39
|
+
// `loss.excluded`, and `loss.folded` says how many of those the fold, rather than the budget, left
|
|
40
|
+
// out, so the two kinds of loss are told apart structurally. The fold depends on the window and the
|
|
41
|
+
// outcomes alone, never on the budget, so the same window folds the same way under any budget.
|
|
42
|
+
import type { LoadedRecord } from "./load.ts";
|
|
43
|
+
import type { Outcome } from "./rank.ts";
|
|
44
|
+
|
|
45
|
+
/** What a representative's run section says it stands for. */
|
|
46
|
+
export interface RunFold {
|
|
47
|
+
/**
|
|
48
|
+
* How many other runs the representative stands for, itself excluded (flyingrobots/parley#100):
|
|
49
|
+
* the section reads as "this run, plus `others` like it". Always at least 1.
|
|
50
|
+
*/
|
|
51
|
+
readonly others: number;
|
|
52
|
+
/** How many records of those other runs, in the window, the fold left out of the digest. */
|
|
53
|
+
readonly records: number;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface Folding {
|
|
57
|
+
/** The ranked records with every folded-away run's records removed, in the ranking's order. */
|
|
58
|
+
readonly records: readonly LoadedRecord[];
|
|
59
|
+
/** Each representative's fold, by its run id. A run that stands only for itself has none. */
|
|
60
|
+
readonly folds: ReadonlyMap<string, RunFold>;
|
|
61
|
+
/** How many records of the window the fold left out: the sum of every fold's `records`. */
|
|
62
|
+
readonly folded: number;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The events whose codes are part of a run's result. */
|
|
66
|
+
const CODED: ReadonlySet<string> = new Set(["error", "warning", "startup.failed"]);
|
|
67
|
+
|
|
68
|
+
const nonEmpty = (value: unknown): value is string => typeof value === "string" && value.length > 0;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The key two runs must share to fold, or null when the run never folds. It is the run's `inv`
|
|
72
|
+
* (the head's, or else `receipt.inputs`'s, as the run section reads it) and its whole result as a
|
|
73
|
+
* lens would state it.
|
|
74
|
+
*/
|
|
75
|
+
function foldKey(own: readonly LoadedRecord[], outcome: Outcome | undefined): string | null {
|
|
76
|
+
if (outcome === undefined) return null;
|
|
77
|
+
const head = own.find((r) => r.event === "receipt.head");
|
|
78
|
+
const inputs = own.find((r) => r.event === "receipt.inputs" && nonEmpty(r.record.inv));
|
|
79
|
+
const inv = nonEmpty(head?.record.inv) ? head.record.inv : inputs?.record.inv;
|
|
80
|
+
if (!nonEmpty(inv)) return null;
|
|
81
|
+
const ends = own.filter((r) => r.event === "end");
|
|
82
|
+
const redacted = (head !== undefined && head.record.redacted !== undefined)
|
|
83
|
+
|| ends.some((r) => r.record.redacted === true)
|
|
84
|
+
|| own.some((r) => r.event === "redaction");
|
|
85
|
+
if (redacted) return null;
|
|
86
|
+
// Not redacted only on evidence: the head says so by carrying no `redacted`, or an `end` says
|
|
87
|
+
// `redacted: false`. A window holding neither cannot tell (§1.2a), so the run does not fold.
|
|
88
|
+
if (head === undefined && !ends.some((r) => r.record.redacted === false)) return null;
|
|
89
|
+
// The same rule the run section states its reason by: an undetermined run with an `end` has an
|
|
90
|
+
// unusable status, one without has no end in the window.
|
|
91
|
+
const reason = outcome !== "undetermined" ? null : ends.length > 0 ? "end_status_unusable" : "no_end_in_window";
|
|
92
|
+
const codes = own
|
|
93
|
+
.filter((r) => r.event !== null && CODED.has(r.event))
|
|
94
|
+
.sort((a, b) => a.seq - b.seq)
|
|
95
|
+
.map((r) => [r.event, typeof r.record.code === "string" ? r.record.code : null]);
|
|
96
|
+
// The head's `resolved` too, since a section states it (flyingrobots/parley#90): §2.2 keeps the
|
|
97
|
+
// working directory and the like out of `inv`, so one `inv` can carry two interpretations, and
|
|
98
|
+
// a fold must not state one run's for another. Keys are sorted so key order is not a difference.
|
|
99
|
+
return JSON.stringify([inv, outcome, reason, ends.map((r) => r.record.status ?? null), codes, canonical(head?.record.resolved)]);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** A JSON value with every object's keys sorted, so two equal values serialise alike. */
|
|
103
|
+
function canonical(value: unknown): unknown {
|
|
104
|
+
if (Array.isArray(value)) return value.map(canonical);
|
|
105
|
+
if (value === null || typeof value !== "object") return value ?? null;
|
|
106
|
+
return Object.fromEntries(Object.keys(value).sort().map((k) => [k, canonical((value as Record<string, unknown>)[k])]));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The latest dated record's `t`, or -1 when the run has none dated. */
|
|
110
|
+
function latest(own: readonly LoadedRecord[]): number {
|
|
111
|
+
let t = -1;
|
|
112
|
+
for (const r of own) if (typeof r.t === "number" && r.t > t) t = r.t;
|
|
113
|
+
return t;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Fold the runs of a ranked window that are one invocation with one result. Pure: it reads,
|
|
118
|
+
* writes and mutates nothing. `ranked` is the whole window in rank order and `outcomes` the
|
|
119
|
+
* ranking's verdict per run over it; without `outcomes` nothing folds.
|
|
120
|
+
*/
|
|
121
|
+
export function foldRuns(ranked: readonly LoadedRecord[], outcomes?: Readonly<Record<string, Outcome>>): Folding {
|
|
122
|
+
const none: Folding = { records: ranked, folds: new Map(), folded: 0 };
|
|
123
|
+
if (outcomes === undefined) return none;
|
|
124
|
+
|
|
125
|
+
const byRun = new Map<string, LoadedRecord[]>();
|
|
126
|
+
for (const record of ranked) {
|
|
127
|
+
const own = byRun.get(record.run);
|
|
128
|
+
if (own === undefined) byRun.set(record.run, [record]);
|
|
129
|
+
else own.push(record);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const groups = new Map<string, string[]>();
|
|
133
|
+
for (const [run, own] of byRun) {
|
|
134
|
+
const key = foldKey(own, outcomes[run]);
|
|
135
|
+
if (key === null) continue;
|
|
136
|
+
const group = groups.get(key);
|
|
137
|
+
if (group === undefined) groups.set(key, [run]);
|
|
138
|
+
else group.push(run);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const away = new Set<string>();
|
|
142
|
+
const folds = new Map<string, RunFold>();
|
|
143
|
+
let folded = 0;
|
|
144
|
+
for (const group of groups.values()) {
|
|
145
|
+
if (group.length < 2) continue;
|
|
146
|
+
let best = group[0]!;
|
|
147
|
+
let bestT = latest(byRun.get(best)!);
|
|
148
|
+
for (const run of group.slice(1)) {
|
|
149
|
+
const t = latest(byRun.get(run)!);
|
|
150
|
+
if (t > bestT || (t === bestT && run > best)) {
|
|
151
|
+
best = run;
|
|
152
|
+
bestT = t;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
let records = 0;
|
|
156
|
+
for (const run of group) {
|
|
157
|
+
if (run === best) continue;
|
|
158
|
+
away.add(run);
|
|
159
|
+
records += byRun.get(run)!.length;
|
|
160
|
+
}
|
|
161
|
+
folds.set(best, { others: group.length - 1, records });
|
|
162
|
+
folded += records;
|
|
163
|
+
}
|
|
164
|
+
if (away.size === 0) return none;
|
|
165
|
+
return { records: ranked.filter((r) => !away.has(r.run)), folds, folded };
|
|
166
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { CHUNK_BYTES, LineBuffer, readFileLines, splitLines, type Line, type Split } from "./lines.ts";
|
|
2
|
+
export { isDirectory, isFile, receiptLocations, repoReceiptDir, stateReceiptDir, type LocateOptions, type ReceiptLocation, type Where } from "./locate.ts";
|
|
3
|
+
export { ENVELOPE, PROTOCOL_PREFIX, envelopeGaps, schemaRef, validator, type SchemaRef, type Validation, type Validator } from "./validate.ts";
|
|
4
|
+
export { QUARANTINE_CODES, loadReceipts, readHistorySegment, readReceiptFile, type Bundle, type BundleSource, type Defect, type DefectCode, type FileRead, type FileSummary, type Load, type LoadOptions, type LoadedRecord, type Projection, type ReadOptions, type Replay, type SidecarResolution, type SidecarState } from "./load.ts";
|
|
5
|
+
export { DROPPABLE, LENS_SCHEMA, RUN_SECTION_BYTES, UNDETERMINED_REASONS, digestBytes, digestFor, digestLine, lensEntry, runSection, sufficientBytes, type Digest, type Digested, type Droppable, type LensEntry, type LineEnvelope, type Loss, type LossBound, type RecordRef, type RunSection, type UndeterminedReason } from "./digest.ts";
|
|
6
|
+
export { DEFAULT_BUDGET, Deadline, MONOTONIC, NO_RETENTION, OVER_BUDGET, QUERY_SCHEMA, VIEWS, declineOnRun, planQuery, queryReceipts, queryRecord, type AcceptedQuery, type Asker, type Budget, type BudgetDecline, type BudgetPhase, type QueryAnswer, type QueryDeclined, type QueryOptions, type QueryOutcome, type QueryPlan, type QueryRefusal, type QueryRefusalCode, type QueryRefused, type QueryRequest, type QueryWindow, type View } from "./query.ts";
|
|
7
|
+
export { CHANGE_VIEWS, OUTCOMES, TIERS, impliesChange, onFailureSurface, onViewSurface, rankRecords, runOutcomes, type Outcome, type RankQuery, type Ranked, type Ranking, type Tier } from "./rank.ts";
|
|
8
|
+
export { foldRuns, type Folding, type RunFold } from "./fold.ts";
|
|
9
|
+
export { SCHEMAS, SCHEMA_SOURCE } from "./schemas.ts";
|
|
10
|
+
export { applyBudget, openedBytes, openOne, openRecords, planOpen, recordBytes, type BundleRuling, type OpenAnswer, type OpenDeclined, type OpenOptions, type OpenOutcome, type OpenOutcomeKind, type OpenPlan, type OpenRefusal, type OpenRefusalCode, type OpenRefused, type OpenRequest, type Opened } from "./open.ts";
|