@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/src/rank.ts ADDED
@@ -0,0 +1,309 @@
1
+ // The purpose orders the answer (spec §9, informative; flyingrobots/parley#49).
2
+ //
3
+ // §9 says the purpose *shapes* the result: "I am about to change this program's audit path"
4
+ // should return records touching that surface, not the last fifty things in chronological order.
5
+ // It is the ranking function, not a filter applied afterwards, and this module is only the
6
+ // ranking function: it reorders the records it is given and returns every one of them. Over-
7
+ // filtering is the failure mode §9 names, so nothing here can drop a record even in principle.
8
+ // The budget, the truncation and the excluded count are the digest's (flyingrobots/parley#50,
9
+ // `digest.ts`), which cuts the tail of the order this module produced and says how long that tail
10
+ // was — a cut above a total order can state its loss, and a cut inside one cannot.
11
+ //
12
+ // What the purpose is as data was decided in flyingrobots/parley#46: a read states a `view`, one
13
+ // token from a closed set of five, and `docs/topics/reader/README.md` says what each one is an
14
+ // answer to. Those five definitions are the whole source of the rules below. Nothing here reads a
15
+ // field `parley.query` does not have, and no schema moves.
16
+ //
17
+ // The order is one total order on a key per record, compared left to right:
18
+ //
19
+ // 1. **the failure surface of the runs that failed, when the view implies a change.** A read
20
+ // made in order to change something is a read made in order not to repeat a failure, so what
21
+ // failed goes first. A `warning` from a run the records do not establish as failed is not a
22
+ // failure (§6.1): it is placed by the view's own surface rule like any other record, so a
23
+ // history of runs that warned and went on cannot crowd the view's own surface out of a digest
24
+ // (flyingrobots/parley#76).
25
+ // 2. **the view's own surface.** The records the view is an answer about, above the records it
26
+ // is not. This is §9's sentence, and for the identity view every record is on the surface, so
27
+ // the tier is empty of consequence.
28
+ // 3. **`(t, run, seq)` ascending.** The order a read already answers in, so a view whose surface
29
+ // no record touches leaves the answer exactly as it was.
30
+ //
31
+ // A record's tier is a property of the record and, for the failure tier only, of its run's outcome.
32
+ // A record's outcome is a property of its run, and it is established from the records being ranked rather than from the whole history: a window that
33
+ // does not hold a run's `end` leaves that run `undetermined`, which §1.2a asks for — a reader must
34
+ // not take one kind of evidence for another, and "no `end` in this window" is not "it succeeded".
35
+ import type { LoadedRecord } from "./load.ts";
36
+ import type { AcceptedQuery, View } from "./query.ts";
37
+ import { PROTOCOL_PREFIX } from "./validate.ts";
38
+
39
+ /**
40
+ * The three tiers, best first. A tier is a property of the record, except that the `failure` tier
41
+ * holds a failure-surface record only when its run failed: an `error`, a `startup.failed` and a
42
+ * non-zero `end` make their run a failed one, so that condition binds only a `warning`.
43
+ */
44
+ export const TIERS = ["failure", "surface", "other"] as const;
45
+ export type Tier = (typeof TIERS)[number];
46
+
47
+ /**
48
+ * What the records being ranked establish about a run's outcome, best-known-worst first: a run
49
+ * that failed is nearer what a change purpose needs than a run whose fate is unknown, which is
50
+ * nearer than a run known to have succeeded.
51
+ */
52
+ export const OUTCOMES = ["failed", "undetermined", "succeeded"] as const;
53
+ export type Outcome = (typeof OUTCOMES)[number];
54
+
55
+ /**
56
+ * The views that imply a change, derived from the vocabulary rather than from a field.
57
+ *
58
+ * `parley.query` 1.0.0 carries no field saying "this purpose implies a change", and inventing one
59
+ * would be this library extending a decided message. It does not need one: of the five tokens,
60
+ * exactly one is an answer about a change — `what-changed`, "subject-matter writes, and the inputs
61
+ * they consumed" — and it is the view §9's own example asks for. `what-ran`, `how-it-decided` and
62
+ * `everything` describe history without proposing to change it. `what-failed` is left out
63
+ * deliberately: failure is already that view's whole surface, so promoting it would restate the
64
+ * surface rather than order the answer.
65
+ *
66
+ * Adding a token to the vocabulary moves `parley.query` and `parley.lens` (flyingrobots/parley#46)
67
+ * and must decide the new token's surface and whether it implies a change.
68
+ */
69
+ export const CHANGE_VIEWS: ReadonlySet<View> = new Set<View>(["what-changed"]);
70
+
71
+ /** True when the view is an answer about a change, so the failed runs' failures rank above everything else. */
72
+ export function impliesChange(view: View): boolean {
73
+ return CHANGE_VIEWS.has(view);
74
+ }
75
+
76
+ /** The event tokens the protocol itself defines (§1.3 through §9). Anything else is a tool's own. */
77
+ const PROTOCOL_EVENTS: ReadonlySet<string> = new Set([
78
+ "run", "receipt.head", "command", "schema", "receipt.inputs", "receipt.step",
79
+ "warning", "error", "cache.hit", "sidecar", "page", "redaction", "end",
80
+ "startup.failed", "query", "lens",
81
+ ]);
82
+
83
+ /** The records §9's `what-failed` is an answer about: the errors, the warnings, and the ends that did not succeed. */
84
+ const FAILURE_EVENTS: ReadonlySet<string> = new Set(["error", "startup.failed", "warning"]);
85
+
86
+ /** The records that identify a run and its outcome: `what-ran`'s "tool, version, status, time". */
87
+ const RAN_EVENTS: ReadonlySet<string> = new Set(["run", "receipt.head", "cache.hit", "end", "startup.failed"]);
88
+
89
+ /** The records that carry a decision and its reason: §5's `receipt.step`, and the decision not to run at all. */
90
+ const DECIDED_EVENTS: ReadonlySet<string> = new Set(["receipt.step", "cache.hit"]);
91
+
92
+ function schemaId(record: LoadedRecord): string | null {
93
+ const stamp = record.record._schema as { id?: unknown } | undefined;
94
+ return stamp !== undefined && typeof stamp.id === "string" ? stamp.id : null;
95
+ }
96
+
97
+ /**
98
+ * A record of the tool's own rather than of the protocol: §7's results, which are the subject
99
+ * matter a command exists to produce. A line that advertises no pair at all and carries no
100
+ * protocol event token is the tool's too — the reader cannot attribute it to the protocol, and
101
+ * §4.6 says a line whose id is not ours is passed through rather than reinterpreted.
102
+ */
103
+ function toolOwned(record: LoadedRecord): boolean {
104
+ const id = schemaId(record);
105
+ if (id !== null) return !id.startsWith(PROTOCOL_PREFIX);
106
+ return record.event === null || !PROTOCOL_EVENTS.has(record.event);
107
+ }
108
+
109
+ /** A `receipt.head` or `command` that declares a subject-matter write (§4.3): what the command exists to change. */
110
+ function declaresWrite(record: LoadedRecord): boolean {
111
+ const effects = record.record.effects;
112
+ if (effects === null || typeof effects !== "object" || Array.isArray(effects)) return false;
113
+ const writes = (effects as { writes?: unknown }).writes;
114
+ return Array.isArray(writes) && writes.length > 0;
115
+ }
116
+
117
+ /** `end` with a status that is a number other than zero: a run that did not succeed (§3.3, §3.4). */
118
+ function endedBadly(record: LoadedRecord): boolean {
119
+ return record.event === "end" && typeof record.record.status === "number" && record.record.status !== 0;
120
+ }
121
+
122
+ /**
123
+ * On the failure surface: an error, a startup failure, a warning, or an `end` that did not succeed.
124
+ * This is `what-failed`'s surface, which a warning is on. It is not, on its own, the change-view
125
+ * promotion: `rankRecords` promotes a failure-surface record only when its run failed.
126
+ */
127
+ export function onFailureSurface(record: LoadedRecord): boolean {
128
+ if (record.event !== null && FAILURE_EVENTS.has(record.event)) return true;
129
+ return endedBadly(record);
130
+ }
131
+
132
+ /**
133
+ * Whether a record is on a view's surface, one view at a time, from the vocabulary's own
134
+ * definition of each token. `everything` is the identity, so every record is on its surface.
135
+ */
136
+ export function onViewSurface(view: View, record: LoadedRecord): boolean {
137
+ switch (view) {
138
+ case "everything":
139
+ return true;
140
+ case "what-ran":
141
+ return record.event !== null && RAN_EVENTS.has(record.event);
142
+ case "what-failed":
143
+ return onFailureSurface(record);
144
+ case "how-it-decided":
145
+ return record.event !== null && DECIDED_EVENTS.has(record.event);
146
+ case "what-changed":
147
+ if (toolOwned(record)) return true;
148
+ if (record.event === "sidecar") return true;
149
+ if (record.event === "receipt.inputs") return true;
150
+ if (record.event === "receipt.head" || record.event === "command") return declaresWrite(record);
151
+ return false;
152
+ }
153
+ }
154
+
155
+ /**
156
+ * What the given records establish about each run's outcome. A run that emitted an `error` or a
157
+ * `startup.failed`, or whose `end` carries a non-zero status, failed. A run with an `end` of zero
158
+ * and nothing against it succeeded. Anything else — including a run whose `end` the window does
159
+ * not hold — is `undetermined`, because a missing `end` is not a successful one (§1.2a, §5.4). A
160
+ * `warning` is not a failed run: §6.1 makes it a warning precisely because the run went on.
161
+ */
162
+ export function runOutcomes(records: readonly LoadedRecord[]): Readonly<Record<string, Outcome>> {
163
+ const failed = new Set<string>();
164
+ const succeeded = new Set<string>();
165
+ const seen = new Set<string>();
166
+ for (const record of records) {
167
+ seen.add(record.run);
168
+ if (record.event === "error" || record.event === "startup.failed" || endedBadly(record)) {
169
+ failed.add(record.run);
170
+ continue;
171
+ }
172
+ if (record.event === "end" && record.record.status === 0) succeeded.add(record.run);
173
+ }
174
+ const outcomes: Record<string, Outcome> = {};
175
+ for (const run of seen) outcomes[run] = failed.has(run) ? "failed" : succeeded.has(run) ? "succeeded" : "undetermined";
176
+ return outcomes;
177
+ }
178
+
179
+ /** One record, with the key it was placed by and the reasons for that key. */
180
+ export interface Ranked {
181
+ readonly record: LoadedRecord;
182
+ /** 1-based position in the order. */
183
+ readonly rank: number;
184
+ readonly tier: Tier;
185
+ /** What the ranked records establish about this record's run. */
186
+ readonly outcome: Outcome;
187
+ /** Why the record is where it is, in the order the key was compared. Stated, not inferred by a caller. */
188
+ readonly why: readonly string[];
189
+ }
190
+
191
+ export interface Ranking {
192
+ readonly view: View;
193
+ /** True when the view is an answer about a change, so the failed runs' failure surface ranks first and failed runs lead each tier. */
194
+ readonly impliesChange: boolean;
195
+ /**
196
+ * Every record given, reordered. Never a subset as `rankRecords` returns it: ranking reorders
197
+ * and never filters. A read's answer carries this ranking cut at the digest's bound, which is
198
+ * stated on `QueryAnswer.ranking` — the cut happens above the full order, never inside it.
199
+ */
200
+ readonly records: readonly LoadedRecord[];
201
+ /** The same records in the same order, each with its key and its reasons. */
202
+ readonly ranked: readonly Ranked[];
203
+ /** The outcome each run's records establish, by run id. */
204
+ readonly outcomes: Readonly<Record<string, Outcome>>;
205
+ readonly counts: {
206
+ readonly failure: number;
207
+ readonly surface: number;
208
+ readonly other: number;
209
+ readonly failedRuns: number;
210
+ readonly undeterminedRuns: number;
211
+ readonly succeededRuns: number;
212
+ };
213
+ }
214
+
215
+ /**
216
+ * The part of an accepted query the ranking reads. An `AcceptedQuery` is one; nothing else about
217
+ * the query shapes the order, and in particular the budget does not — the budget is the digest's
218
+ * bound (`digest.ts`), and a ranking that had already applied it could not say what it cut.
219
+ */
220
+ export type RankQuery = Pick<AcceptedQuery, "view">;
221
+
222
+ /** A record with no usable `t` cannot be placed in time, so it sorts last within its tier rather than anywhere. */
223
+ const UNDATED = Number.MAX_SAFE_INTEGER;
224
+
225
+ /**
226
+ * Order the records of an accepted query by its view.
227
+ *
228
+ * Pure: it reads nothing, writes nothing, records nothing and mutates neither its argument nor the
229
+ * records in it. It returns every record it was given, which is what makes it safe for
230
+ * flyingrobots/parley#50 to truncate and state what it left out.
231
+ */
232
+ export function rankRecords(query: RankQuery, records: readonly LoadedRecord[]): Ranking {
233
+ const view = query.view;
234
+ const promotes = impliesChange(view);
235
+ const outcomes = runOutcomes(records);
236
+
237
+ const keyed = records.map((record, index) => {
238
+ const outcome = outcomes[record.run] ?? "undetermined";
239
+ // Promoted only with its run's failure. Every error, startup failure and non-zero end is in a
240
+ // failed run by `runOutcomes`' own rule, so this excludes exactly the warnings of runs the
241
+ // records do not establish as failed — a recovered condition, not a failure (§6.1).
242
+ const failure = onFailureSurface(record);
243
+ const tier: Tier = promotes && failure && outcome === "failed" ? "failure" : onViewSurface(view, record) ? "surface" : "other";
244
+ return {
245
+ record,
246
+ index,
247
+ tier,
248
+ outcome,
249
+ tierIndex: TIERS.indexOf(tier),
250
+ // The outcome only orders anything when the view implies a change; otherwise every record
251
+ // carries the same outcome key and the tier falls straight through to time.
252
+ outcomeIndex: promotes ? OUTCOMES.indexOf(outcome) : 0,
253
+ t: typeof record.t === "number" ? record.t : UNDATED,
254
+ // On the failure surface under a change view and still not promoted: a warning of a run that went on.
255
+ demoted: promotes && failure && tier !== "failure",
256
+ };
257
+ });
258
+
259
+ keyed.sort((a, b) =>
260
+ (a.tierIndex - b.tierIndex)
261
+ || (a.outcomeIndex - b.outcomeIndex)
262
+ || (a.t - b.t)
263
+ || a.record.run.localeCompare(b.record.run)
264
+ || (a.record.seq - b.record.seq),
265
+ );
266
+
267
+ const ranked: Ranked[] = keyed.map((entry, i) => ({
268
+ record: entry.record,
269
+ rank: i + 1,
270
+ tier: entry.tier,
271
+ outcome: entry.outcome,
272
+ why: why(view, promotes, entry.tier, entry.outcome, entry.t === UNDATED, entry.demoted),
273
+ }));
274
+
275
+ const runs = Object.values(outcomes);
276
+ return {
277
+ view,
278
+ impliesChange: promotes,
279
+ records: ranked.map((r) => r.record),
280
+ ranked,
281
+ outcomes,
282
+ counts: {
283
+ failure: ranked.filter((r) => r.tier === "failure").length,
284
+ surface: ranked.filter((r) => r.tier === "surface").length,
285
+ other: ranked.filter((r) => r.tier === "other").length,
286
+ failedRuns: runs.filter((o) => o === "failed").length,
287
+ undeterminedRuns: runs.filter((o) => o === "undetermined").length,
288
+ succeededRuns: runs.filter((o) => o === "succeeded").length,
289
+ },
290
+ };
291
+ }
292
+
293
+ function why(view: View, promotes: boolean, tier: Tier, outcome: Outcome, undated: boolean, demoted: boolean): string[] {
294
+ const reasons: string[] = [];
295
+ if (tier === "failure") reasons.push(`on the failure surface, and ${view} is an answer about a change`);
296
+ else {
297
+ if (demoted) reasons.push("a warning, and its run is not established as failed, so it is placed by the view's surface (§6.1)");
298
+ reasons.push(tier === "surface" ? `touches the ${view} surface` : `off the ${view} surface`);
299
+ }
300
+ if (promotes) {
301
+ reasons.push(outcome === "failed"
302
+ ? "its run failed"
303
+ : outcome === "succeeded"
304
+ ? "its run succeeded"
305
+ : "its run's outcome is not established by the records ranked");
306
+ }
307
+ reasons.push(undated ? "no usable t, so it sorts last in its tier" : "then t, run and seq ascending");
308
+ return reasons;
309
+ }