@ultimat3/testing 30.7.0 → 30.8.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.
@@ -4,6 +4,8 @@
4
4
  // Pure: JSON in, verdicts out (plan 101, 40-next-query-plans).
5
5
 
6
6
  import { columnsIn } from './plan-conditions';
7
+ import type { ProbeScan } from './plan-probes';
8
+ import { probesOf } from './plan-probes';
7
9
  import type { PlanUnservable, SortKeyRef } from './plan-sort-key';
8
10
  import { sortKeyPart, sortUnservable } from './plan-sort-key';
9
11
 
@@ -28,6 +30,11 @@ export interface PlanVerdict {
28
30
  readonly arms?: readonly (readonly string[])[];
29
31
  /** The alias the plan reads the table by, when it is not the table's own name. */
30
32
  readonly alias?: string;
33
+ /**
34
+ * Columns a join ties this whole read to a scan bound by its own key (`plan-probes.ts`): one
35
+ * that leads an index is a probe the planner had and declined on an empty table's costs.
36
+ */
37
+ readonly probes?: readonly string[];
31
38
  }
32
39
 
33
40
  interface PlanNode {
@@ -36,12 +43,14 @@ interface PlanNode {
36
43
  readonly alias: string | undefined;
37
44
  readonly conditions: readonly string[];
38
45
  readonly sortKey: readonly string[];
39
- readonly indexCond: boolean;
46
+ readonly indexCond: string | undefined;
40
47
  readonly filter: boolean;
41
48
  readonly children: readonly PlanNode[];
42
49
  }
43
50
 
44
51
  const SCANS: ReadonlySet<string> = new Set(['Seq Scan', 'Index Scan', 'Index Only Scan']);
52
+ /** Nodes that hold their child's rows for a join: the join's conditions are the child's still. */
53
+ const HOLDS: ReadonlySet<string> = new Set(['Hash', 'Materialize', 'Memoize']);
45
54
  /** Conditions a join or a recheck carries for the scans beneath it. */
46
55
  const CONDITION_KEYS = ['Index Cond', 'Filter', 'Hash Cond', 'Merge Cond', 'Join Filter'] as const;
47
56
 
@@ -67,7 +76,7 @@ function nodeOf(value: unknown): PlanNode | undefined {
67
76
  alias: text(raw['Alias']),
68
77
  conditions: CONDITION_KEYS.flatMap((key) => text(raw[key]) ?? []),
69
78
  sortKey,
70
- indexCond: text(raw['Index Cond']) !== undefined,
79
+ indexCond: text(raw['Index Cond']),
71
80
  filter: text(raw['Filter']) !== undefined,
72
81
  children: plans.flatMap((child) => nodeOf(child) ?? []),
73
82
  };
@@ -143,18 +152,22 @@ export type PlanTableColumns = ReadonlyMap<string, ReadonlySet<string>>;
143
152
  /**
144
153
  * Every red node of one plan. `Seq Scan` on a judged table; an index scan with no `Index Cond`,
145
154
  * unless a `Limit` above it stops it early and no `Filter` makes it walk on; a `Sort` under a
146
- * `Limit`. A join's conditions are handed down, so the scan of its inner side names its key.
155
+ * `Limit`. A join's conditions are handed down, through the nodes that only hold rows for it, so
156
+ * the scan of its inner side names its key — and a whole read tied to a keyed side, its probe.
147
157
  */
148
158
  export function judgePlan(answer: unknown, tables: PlanTableColumns): readonly PlanVerdict[] {
149
159
  const root = nodeOf(planRoot(answer));
150
160
  if (root === undefined) return [];
151
161
  const verdicts: PlanVerdict[] = [];
162
+ const scans: (ProbeScan & { readonly verdict: number | undefined })[] = [];
152
163
  const walk = (node: PlanNode, limited: boolean, inherited: readonly string[]): void => {
153
164
  const conditions = [...inherited, ...node.conditions];
154
165
  const columns = node.table === undefined ? undefined : tables.get(node.table);
155
- if (node.table !== undefined && columns !== undefined && SCANS.has(node.type)) {
156
- const unbounded = node.type === 'Seq Scan' || (!node.indexCond && (!limited || node.filter));
157
- if (unbounded) {
166
+ if (node.table !== undefined && SCANS.has(node.type)) {
167
+ const judged = columns !== undefined;
168
+ const unbounded =
169
+ node.type === 'Seq Scan' || (node.indexCond === undefined && (!limited || node.filter));
170
+ if (judged && unbounded) {
158
171
  const found = columnsIn(conditions, node, columns);
159
172
  verdicts.push({
160
173
  code: 'X_QUERY_UNINDEXED',
@@ -165,6 +178,9 @@ export function judgePlan(answer: unknown, tables: PlanTableColumns): readonly P
165
178
  ...(node.alias === undefined || node.alias === node.table ? {} : { alias: node.alias }),
166
179
  });
167
180
  }
181
+ const { table, alias, indexCond } = node;
182
+ const verdict = judged && unbounded ? verdicts.length - 1 : undefined;
183
+ scans.push({ table, alias, indexCond, conditions, verdict });
168
184
  }
169
185
  if (node.type === 'Sort' && limited) {
170
186
  const sorted = sortVerdict(node, conditions, tables);
@@ -173,11 +189,15 @@ export function judgePlan(answer: unknown, tables: PlanTableColumns): readonly P
173
189
  const below = limited || node.type === 'Limit';
174
190
  // A join's conditions name both sides: each child keeps only the conjuncts about itself.
175
191
  const handed =
176
- node.type.includes('Join') || node.type === 'Nested Loop' || node.type === 'Hash'
192
+ node.type.includes('Join') || node.type === 'Nested Loop' || HOLDS.has(node.type)
177
193
  ? conditions
178
194
  : [];
179
195
  for (const child of node.children) walk(child, below, handed);
180
196
  };
181
197
  walk(root, false, []);
182
- return verdicts;
198
+ const probes = probesOf(scans);
199
+ return verdicts.map((verdict, at) => {
200
+ const found = probes[scans.findIndex((scan) => scan.verdict === at)] ?? [];
201
+ return found.length === 0 ? verdict : { ...verdict, probes: found };
202
+ });
183
203
  }
@@ -0,0 +1,94 @@
1
+ // Which whole reads in one plan a keyed scan could have probed instead: the join columns that tie
2
+ // a scan to a side bound by its own key. On empty tables the planner may walk a small-looking
3
+ // index beside a join rather than probe it per row; the probe exists when such a column leads an
4
+ // index, which `plan-sweep-fix.ts` reads off the declaration. Pure.
5
+
6
+ import { splitTop, unwrap } from './plan-conditions';
7
+
8
+ /** One scan of the plan, with every condition it was handed and its own `Index Cond`. */
9
+ export interface ProbeScan {
10
+ readonly table: string;
11
+ readonly alias: string | undefined;
12
+ readonly indexCond: string | undefined;
13
+ readonly conditions: readonly string[];
14
+ }
15
+
16
+ const SIDE = String.raw`(?:"?([A-Za-z_][\w$]*)"?\.)?"?([A-Za-z_][\w$]*)"?`;
17
+ /** `a.x = b.y`: one column against another, the only shape a probe answers. */
18
+ const COLUMN_EQUALITY = new RegExp(`^${SIDE}\\s*=\\s*${SIDE}$`);
19
+ const QUALIFIER = /"?([A-Za-z_][\w$]*)"?\.(?="?[A-Za-z_])/g;
20
+
21
+ const nameOf = (scan: ProbeScan): string => scan.alias ?? scan.table;
22
+
23
+ const conjuncts = (conditions: readonly string[]): string[] =>
24
+ conditions.flatMap((condition) => splitTop(unwrap(condition), 'AND'));
25
+
26
+ /**
27
+ * Bound by its own key: an `Index Cond` conjunct that names no other scan. A parameterized inner
28
+ * scan's condition is the join itself, so it keys nothing on its own.
29
+ */
30
+ function selfKeyed(scan: ProbeScan, others: ReadonlySet<string>): boolean {
31
+ if (scan.indexCond === undefined) return false;
32
+ return conjuncts([scan.indexCond]).some((conjunct) =>
33
+ [...conjunct.replace(/'[^']*'/g, '').matchAll(QUALIFIER)].every(
34
+ ([, qualifier]) => qualifier === undefined || !others.has(qualifier),
35
+ ),
36
+ );
37
+ }
38
+
39
+ interface Tie {
40
+ readonly scan: string;
41
+ readonly column: string;
42
+ readonly other: string;
43
+ }
44
+
45
+ /**
46
+ * Every `a.x = b.y` between two scans, both ways round, wherever the plan states it: a join's
47
+ * filter, or a parameterized scan's own `Index Cond`, where its columns go unqualified.
48
+ */
49
+ function tiesOf(scans: readonly ProbeScan[], names: ReadonlySet<string>): readonly Tie[] {
50
+ const ties: Tie[] = [];
51
+ for (const scan of scans) {
52
+ for (const conjunct of conjuncts([...scan.conditions, scan.indexCond ?? ''])) {
53
+ const match = COLUMN_EQUALITY.exec(conjunct);
54
+ if (match === null) continue;
55
+ const [, leftOf = nameOf(scan), left, rightOf = nameOf(scan), right] = match;
56
+ if (left === undefined || right === undefined || leftOf === rightOf) continue;
57
+ if (!names.has(leftOf) || !names.has(rightOf)) continue;
58
+ ties.push({ scan: leftOf, column: left, other: rightOf });
59
+ ties.push({ scan: rightOf, column: right, other: leftOf });
60
+ }
61
+ }
62
+ return ties;
63
+ }
64
+
65
+ /**
66
+ * Each scan's probe columns, in plan order: the columns it is tied to a keyed scan by. A scan
67
+ * that has any is keyed in turn, so the probe carries along a chain of joins; two scans tied only
68
+ * to each other probe nothing — one of them is read whole either way.
69
+ */
70
+ export function probesOf(scans: readonly ProbeScan[]): readonly (readonly string[])[] {
71
+ const names = new Set(scans.map(nameOf));
72
+ const keyed = new Set(
73
+ scans
74
+ .filter((scan) => selfKeyed(scan, new Set([...names].filter((n) => n !== nameOf(scan)))))
75
+ .map(nameOf),
76
+ );
77
+ const ties = tiesOf(scans, names);
78
+ const probes = scans.map((): string[] => []);
79
+ for (let grew = true; grew; ) {
80
+ grew = false;
81
+ scans.forEach((scan, at) => {
82
+ const own = nameOf(scan);
83
+ if (keyed.has(own)) return;
84
+ const found = ties.flatMap((tie) =>
85
+ tie.scan === own && keyed.has(tie.other) ? [tie.column] : [],
86
+ );
87
+ if (found.length === 0) return;
88
+ probes[at] = [...new Set(found)];
89
+ keyed.add(own);
90
+ grew = true;
91
+ });
92
+ }
93
+ return probes;
94
+ }
@@ -1,6 +1,7 @@
1
1
  // From the oracle's red nodes to what an author pastes: the entity, and the `indexes: [{ on }]`
2
2
  // entry by property. Pure. Also where a red node is argued away by the declaration itself: a
3
- // lookup that pins a unique key reads one row whatever the planner walked to find it.
3
+ // lookup that pins a unique key reads one row whatever the planner walked to find it, and a whole
4
+ // read a keyed join side could probe by a declared index is one the planner declined on cost.
4
5
 
5
6
  import type { PlanVerdict, PlanVerdictCode } from './plan-oracle';
6
7
  import type { PlanUnservable } from './plan-sort-key';
@@ -173,6 +174,15 @@ function armFindings(
173
174
  .map((arm) => arm.flatMap((column) => property(column) ?? []));
174
175
  }
175
176
 
177
+ /**
178
+ * A whole read a keyed side could probe: a column it is joined by leads a declared index. On empty
179
+ * tables the planner may walk a small-looking index (a partial one the statement implies) rather
180
+ * than probe it per row; at size it probes. Credited, never re-proven, as a range index is.
181
+ */
182
+ const probed = (keys: readonly (readonly string[])[], verdict: PlanVerdict): boolean =>
183
+ verdict.code === 'X_QUERY_UNINDEXED' &&
184
+ (verdict.probes ?? []).some((column) => keys.some((key) => key[0] === column));
185
+
176
186
  /**
177
187
  * The plan was taken with every declared index in place: one that leads with exactly these
178
188
  * columns is already there, and printing it as the fix would change nothing.
@@ -220,6 +230,7 @@ export function planFindings(
220
230
  // no order after a range column, so the index is the equality columns, then the range.
221
231
  const ranged = walked && verdict.range.length > 0;
222
232
  const declared = declaredIndexes(entity, statement);
233
+ if (probed(declared, verdict)) return [];
223
234
  const bounded = verdict.equality.length > 0 || verdict.range.length > 0;
224
235
  if (!bounded && verdict.arms !== undefined && verdict.code === 'X_QUERY_UNINDEXED') {
225
236
  const arms = armFindings(verdict, declared, (column) => byColumn.get(column));
@@ -28,12 +28,15 @@ export function scaleGraph(
28
28
  readonly seed: number;
29
29
  /** The app's `defineExercise` factories: a table only they satisfy is built by them here too. */
30
30
  readonly factories?: Readonly<Record<string, SeedFactory>> | undefined;
31
+ /** The last graph written to the database before this one; `main` when omitted. */
32
+ readonly beside?: SeedGraph | undefined;
31
33
  },
32
34
  ): ScaleGraph {
33
35
  const sized = seedGraph(Object.fromEntries(entities.map((entity) => [entity.$name, entity])), {
34
36
  tenants: 1,
35
37
  perTable: options.perTable,
36
38
  seed: options.seed,
39
+ beside: options.beside ?? main,
37
40
  ...(options.factories === undefined ? {} : { factories: options.factories }),
38
41
  });
39
42
  const shared = (graph: SeedGraph) => graph.inserts.filter((insert) => insert.tenant === null);
@@ -9,6 +9,7 @@ import type { RunJobs } from './fixture-jobs';
9
9
  import { testJobs } from './fixture-jobs';
10
10
  import type { ScaleProof, StatementTally } from './scale-sweep';
11
11
  import { judgeScale, SCALE_SIZES } from './scale-sweep';
12
+ import type { ScaleGraph } from './scale-sweep-graph';
12
13
  import { scaleGraph } from './scale-sweep-graph';
13
14
  import type { SeedFactory, SeedGraph, SeedWriter } from './seed-graph-plan';
14
15
  import { insertSeedGraph } from './seed-graph-plan';
@@ -85,14 +86,20 @@ export async function scaleSweep(
85
86
  ): Promise<ReadonlyMap<string, ScaleProof>> {
86
87
  const proofs = new Map<string, ScaleProof>();
87
88
  if (options.subjects.length === 0) return proofs;
88
- const sizes = [SCALE_SIZES.small, SCALE_SIZES.large].map((perTable, i) =>
89
+ const sizes: ScaleGraph[] = [];
90
+ for (const [i, perTable] of [SCALE_SIZES.small, SCALE_SIZES.large].entries()) {
89
91
  // Hashed, never `seed + 1`: a later pass on the same database may be seeded with that number.
90
- scaleGraph(options.main, options.entities, {
91
- perTable,
92
- seed: fnv1a(`scale:${options.seed}:${i}`) || 1,
93
- factories: options.factories,
94
- }),
95
- );
92
+ // Each beside the one written before it, so no row position — and no value built from one —
93
+ // repeats across the three graphs in the database.
94
+ sizes.push(
95
+ scaleGraph(options.main, options.entities, {
96
+ perTable,
97
+ seed: fnv1a(`scale:${options.seed}:${i}`) || 1,
98
+ factories: options.factories,
99
+ beside: sizes[i - 1]?.write ?? options.main,
100
+ }),
101
+ );
102
+ }
96
103
  try {
97
104
  for (const size of sizes) await insertSeedGraph(size.write, options.writer);
98
105
  } catch (error) {
@@ -23,6 +23,12 @@ export interface SeedGraphOptions {
23
23
  readonly seed?: number;
24
24
  /** By entity name. A column the factory builds takes its value; keys stay the graph's. */
25
25
  readonly factories?: Readonly<Record<string, SeedFactory>>;
26
+ /**
27
+ * A graph already written to the same database. Each table's row positions — the ordinal a
28
+ * generated value is built from, a factory's `index` — continue past its `next`, so a value built
29
+ * from a position (`code: \`c${index}\``) never repeats one of its rows on a unique column.
30
+ */
31
+ readonly beside?: SeedGraph;
26
32
  }
27
33
 
28
34
  export interface SeedRow {
@@ -67,6 +73,11 @@ export interface SeedGraph {
67
73
  readonly updates: readonly SeedUpdate[];
68
74
  /** One per insert, in the same order: `canaries[i]` is `inserts[i]`'s. */
69
75
  readonly canaries: readonly SeedCanary[];
76
+ /**
77
+ * Per table, the row position a graph written `beside` this one starts at: its own `beside`'s
78
+ * plus every row this graph built. Absent on a hand-written graph: positions then start at 0.
79
+ */
80
+ readonly next?: Readonly<Record<string, number>>;
70
81
  }
71
82
 
72
83
  /** Where `insertSeedGraph` writes. One insert per row, in order, then one update per deferred key. */
package/src/seed-graph.ts CHANGED
@@ -137,6 +137,8 @@ export function seedGraph(
137
137
  const scoped = (name: string): boolean => owned.has(name);
138
138
  const fanned = fannedOut(shapes, scoped);
139
139
  for (const factory of Object.values(options.factories ?? {})) factory.reset();
140
+ const besideNext = options.beside?.next ?? {};
141
+ const next: Record<string, number> = { ...besideNext };
140
142
 
141
143
  const placed = new Map<string, Placed[]>();
142
144
  // The same rows by tenant: a pool read per row was a filter of the whole parent table, so a pass
@@ -196,12 +198,17 @@ export function seedGraph(
196
198
  // Read once per table: each `matches(/…/)` an invariant holds a column to, sampled from.
197
199
  const patterns = declaredPatterns(entity);
198
200
  const buckets: readonly (string | null)[] = scoped(name) ? tenants : [null];
199
- let ordinal = 0;
201
+ // Positions continue past the graph written before this one: a reset factory rebuilt that
202
+ // graph's first values, and a unique column refused the second copy.
203
+ const start = besideNext[name] ?? 0;
204
+ for (let skipped = 0; factory !== undefined && skipped < start; skipped += 1) factory.build();
205
+ let ordinal = start;
200
206
  for (const [bucket, tenant] of buckets.entries()) {
201
207
  const size =
202
208
  rootProperty !== undefined ? 1 : fanned.has(name) ? perTable * tenantCount : perTable;
203
209
  for (let index = 0; index < size; index += 1) {
204
210
  ordinal += 1;
211
+ next[name] = ordinal;
205
212
  const canary = stream().replace(/-/g, '').slice(0, 10);
206
213
  const built: Readonly<Record<string, unknown>> =
207
214
  factory === undefined ? {} : { ...factory.build() };
@@ -320,5 +327,5 @@ export function seedGraph(
320
327
  updates.push({ entity: name, tenant, key: keyOf(shape.entity, row), patch });
321
328
  }
322
329
  }
323
- return { seed, tenants, order, inserts, updates, canaries };
330
+ return { seed, tenants, order, inserts, updates, canaries, next };
324
331
  }
@@ -25,6 +25,11 @@ export interface SubjectProofOptions {
25
25
  readonly seed?: number;
26
26
  /** `defineExercise`'s factories: a table only they satisfy is built by them for the proof too. */
27
27
  readonly factories?: Readonly<Record<string, SeedFactory>> | undefined;
28
+ /**
29
+ * The graph already written to this database — the previous subject's `graph`. Row positions
30
+ * continue past it, so a factory value built from the index never repeats one on a unique column.
31
+ */
32
+ readonly beside?: SeedGraph | undefined;
28
33
  }
29
34
 
30
35
  export interface SubjectProofResult {
@@ -32,6 +37,8 @@ export interface SubjectProofResult {
32
37
  /** The person erased, by key; absent when the plan refused before a row was seeded. */
33
38
  readonly key?: string;
34
39
  readonly problems: readonly UltimateError[];
40
+ /** What it wrote: the next proof on the same database is seeded `beside` it. */
41
+ readonly graph?: SeedGraph;
35
42
  }
36
43
 
37
44
  interface Reached {
@@ -111,6 +118,7 @@ export async function subjectProof<I>(
111
118
  seed: finiteOption('subjectProof', 'seed', options.seed ?? 1),
112
119
  tenants: 2,
113
120
  ...(options.factories === undefined ? {} : { factories: options.factories }),
121
+ ...(options.beside === undefined ? {} : { beside: options.beside }),
114
122
  });
115
123
  // The pass's rule: a nullable cycle key the database refuses to set stays null.
116
124
  await insertSeedGraph(graph, deferredMayStayNull(options.writer));
@@ -119,7 +127,9 @@ export async function subjectProof<I>(
119
127
  (i) => i.entity === subject.entity && (i.tenant === tenant || i.tenant === null),
120
128
  );
121
129
  const root = entities.get(subject.entity);
122
- if (person === undefined || root === undefined) return { subject: subject.entity, problems: [] };
130
+ if (person === undefined || root === undefined) {
131
+ return { subject: subject.entity, problems: [], graph };
132
+ }
123
133
  const key = String(person.row[plan.key]);
124
134
  const reached = reachedRows(graph, plan, entities, person.row);
125
135
 
@@ -181,5 +191,5 @@ export async function subjectProof<I>(
181
191
  }
182
192
  }
183
193
  }
184
- return { subject: subject.entity, key, problems: found };
194
+ return { subject: subject.entity, key, problems: found, graph };
185
195
  }
@@ -1,6 +1,6 @@
1
- // The tenant proof, as `x exercise` reports it: one line per finding — primitive, leg, and the path
2
- // of A's canary in B's answer or the table and id of A's changed row — and one coded finding each
3
- // for the gate to fail on. Only paths, tables and seeded ids are printed: never a bound value.
1
+ // The tenant proof, as `x exercise` reports it: one line per leg and code — primitive, leg, and the
2
+ // paths of A's canaries in B's answer or the tables and ids of A's changed rows — and one coded
3
+ // finding each for the gate to fail on. Only paths, tables and seeded ids: never a bound value.
4
4
 
5
5
  import { renderFixShellArg } from '@ultimat3/core';
6
6
  import type { ExerciseRecord, TenantFinding } from './exercise-report';
@@ -16,21 +16,66 @@ export interface TenantProofFinding {
16
16
 
17
17
  const LEG = { before: 'before A ran', after: 'after A ran' } as const;
18
18
 
19
- /** `B with A's ids, before A ran: output.items[0].url` — where, never what. */
20
- const where = (finding: TenantFinding): string =>
19
+ /** Every finding of one leg and one code: one statement's leak, however many fields it carried. */
20
+ interface Group {
21
+ readonly code: TenantFinding['code'];
22
+ readonly leg: TenantFinding['leg'];
23
+ readonly sweep: boolean;
24
+ readonly where: string;
25
+ }
26
+
27
+ /** `output.items[0].url` — where, never what. */
28
+ const whereOne = (finding: TenantFinding): string =>
21
29
  finding.code === 'X_TENANT_LEAK'
22
30
  ? `${finding.path ?? 'output'}`
23
31
  : `${finding.table ?? '?'} row ${finding.id ?? '?'}`;
24
32
 
25
- /** Every finding of every crossed record, one line each: `action readPost · before · output.url`. */
33
+ /**
34
+ * Each distinct place once. Places differing only in a list index — three enqueues carrying the same
35
+ * three fields — collapse to `[*]` with their count; a lone one keeps its index.
36
+ */
37
+ const whereAll = (findings: readonly TenantFinding[]): string => {
38
+ const counts = new Map<string, { readonly first: string; count: number }>();
39
+ for (const finding of findings) {
40
+ const place = whereOne(finding);
41
+ const shape = place.replace(/\[\d+\]/g, '[*]');
42
+ const seen = counts.get(shape);
43
+ if (seen === undefined) counts.set(shape, { first: place, count: 1 });
44
+ else seen.count += 1;
45
+ }
46
+ const entries = [...counts.entries()];
47
+ const each = entries[0]?.[1].count ?? 1;
48
+ if (each > 1 && entries.every(([, { count }]) => count === each)) {
49
+ return `${entries.map(([shape]) => shape).join(', ')} (${each} each)`;
50
+ }
51
+ return entries
52
+ .map(([shape, { first, count }]) => (count === 1 ? first : `${shape} (×${count})`))
53
+ .join(', ');
54
+ };
55
+
56
+ const groupsOf = (findings: readonly TenantFinding[]): readonly Group[] => {
57
+ const byKey = new Map<string, TenantFinding[]>();
58
+ for (const finding of findings) {
59
+ const key = `${finding.leg}\u0000${finding.code}\u0000${finding.sweep === true}`;
60
+ const list = byKey.get(key);
61
+ if (list === undefined) byKey.set(key, [finding]);
62
+ else list.push(finding);
63
+ }
64
+ return [...byKey.values()].map((list) => {
65
+ const head = list[0] as TenantFinding;
66
+ return { code: head.code, leg: head.leg, sweep: head.sweep === true, where: whereAll(list) };
67
+ });
68
+ };
69
+
70
+ const crossedGroups = (record: ExerciseRecord): readonly Group[] =>
71
+ record.tenant?.verdict === 'crossed' ? groupsOf(record.tenant.findings) : [];
72
+
73
+ /** One line per leg and code of every crossed record: `action readPost · before · …`. */
26
74
  export function tenantFindingLines(records: readonly ExerciseRecord[]): readonly string[] {
27
75
  return records.flatMap((record) =>
28
- record.tenant?.verdict === 'crossed'
29
- ? record.tenant.findings.map(
30
- (finding) =>
31
- `${record.kind} ${record.name} · ${finding.leg} · ${finding.code} ${where(finding)}`,
32
- )
33
- : [],
76
+ crossedGroups(record).map(
77
+ (group) => `${record.kind} ${record.name} · ${group.leg} · ${group.code} ${group.where}`,
78
+ ),
34
79
  );
35
80
  }
36
81
 
@@ -38,32 +83,37 @@ export function tenantFindingLines(records: readonly ExerciseRecord[]): readonly
38
83
  * B sends A's own first input, A's ids bound in only where it takes any: `{ occurrenceMs }` carries
39
84
  * none, and B still crosses when a statement it ran names no tenant. Both readings, always.
40
85
  */
41
- const causeOf = (record: ExerciseRecord, finding: TenantFinding): string =>
42
- finding.code === 'X_TENANT_LEAK'
43
- ? `${record.kind} ${record.name}, called by tenant B with A's own input ${LEG[finding.leg]}, handed back A's seeded data at ${where(finding)}: a read reached A's row past the tenant guard — by an id the caller chose, or by a statement no tenant predicate scopes`
44
- : `${record.kind} ${record.name}, called by tenant B with A's own input ${LEG[finding.leg]}, changed A's ${where(finding)}: a write reached A's row past the tenant guard — by an id the caller chose, or by a statement no tenant predicate scopes`;
86
+ const causeOf = (record: ExerciseRecord, group: Group): string =>
87
+ group.code === 'X_TENANT_LEAK'
88
+ ? `${record.kind} ${record.name}, called by tenant B with A's own input ${LEG[group.leg]}, handed back A's seeded data at ${group.where}: a read reached A's row past the tenant guard — by an id the caller chose, or by a statement no tenant predicate scopes`
89
+ : `${record.kind} ${record.name}, called by tenant B with A's own input ${LEG[group.leg]}, changed A's ${group.where}: a write reached A's row past the tenant guard — by an id the caller chose, or by a statement no tenant predicate scopes`;
45
90
 
46
- const fixOf = (name: string, finding: TenantFinding): string =>
47
- finding.code === 'X_TENANT_LEAK'
48
- ? `x exercise ${name} --json — then read the row behind ${where(finding)} through the repository scoped to ctx.actor, never by the input id alone, nor by an unscoped statement`
49
- : `x exercise ${name} --json — then write ${where(finding)} through the repository scoped to ctx.actor, never by the input id alone, nor by an unscoped statement`;
91
+ /**
92
+ * A `tenant: 'none'` job has no actor's org to scope a read to: reading every org is its job, and
93
+ * the one declaration the proof credits for that is a `crossTenant()` scope (`sweepReason`).
94
+ */
95
+ const fixOf = (name: string, group: Group): string =>
96
+ group.code === 'X_TENANT_WRITE_CROSSED'
97
+ ? `x exercise ${name} --json — then write ${group.where} through the repository scoped to ctx.actor, never by the input id alone, nor by an unscoped statement`
98
+ : group.sweep
99
+ ? `x exercise ${name} --json — then wrap the read behind ${group.where} in ${name}'s run in crossTenant('<why ${name} reads every org>', async () => …) from @ultimat3/entity; the job's actor must hold tenancy:cross`
100
+ : `x exercise ${name} --json — then read the row behind ${group.where} through the repository scoped to ctx.actor, never by the input id alone, nor by an unscoped statement`;
50
101
 
51
102
  /**
52
- * One coded finding per tenant finding. The fix reruns the one primitive: what it reads or writes
53
- * by input id goes through the repository scoped to `ctx.actor` (or `crossTenant()` with a public
54
- * policy, when it truly spans tenants) — which read, only the handler shows.
103
+ * One coded finding per leg and code. The fix reruns the one primitive: what it reads or writes by
104
+ * input id goes through the repository scoped to `ctx.actor` — or, for a `tenant: 'none'` job's
105
+ * read across every org, a `crossTenant()` scope. Which statement, only the handler shows.
55
106
  */
56
107
  export function tenantProofFindings(
57
108
  records: readonly ExerciseRecord[],
58
109
  ): readonly TenantProofFinding[] {
59
110
  return records.flatMap((record) => {
60
- if (record.tenant?.verdict !== 'crossed') return [];
61
111
  const name = renderFixShellArg(record.name, '<primitive>');
62
- return record.tenant.findings.map(
63
- (finding): TenantProofFinding => ({
64
- code: finding.code,
65
- cause: causeOf(record, finding),
66
- fix: fixOf(name, finding),
112
+ return crossedGroups(record).map(
113
+ (group): TenantProofFinding => ({
114
+ code: group.code,
115
+ cause: causeOf(record, group),
116
+ fix: fixOf(name, group),
67
117
  at: `${record.kind} ${record.name}`,
68
118
  }),
69
119
  );
@@ -118,6 +118,8 @@ export function leaksIn(
118
118
  return paths.map((path): TenantFinding => ({ code: 'X_TENANT_LEAK', leg, path }));
119
119
  }
120
120
 
121
+ const asSweep = (finding: TenantFinding): TenantFinding => ({ ...finding, sweep: true });
122
+
121
123
  /**
122
124
  * The reason a leg's read half is skipped as a declared sweep, or `undefined`: a job, a scope the
123
125
  * leg opened, and an input carrying nothing of A's — so no id B chose pointed at A, and what came
@@ -181,6 +183,8 @@ export async function proveTenant(plan: TenantAttack): Promise<ExerciseRecord> {
181
183
  const findings: TenantFinding[] = [];
182
184
  const unwritten = tenantlessReason(plan, marks);
183
185
  let swept: string | undefined;
186
+ // What `sweepReason` would credit, had the leg opened a scope: the leak's fix is that scope.
187
+ const undeclared = plan.sweep && plan.tenantless && marks.length === plan.taint.marks.length;
184
188
  /** B's call, between two snapshots unless the write half is skipped: then none is read. */
185
189
  const watched = async (name: TenantLeg): Promise<LegAnswer> => {
186
190
  if (unwritten !== undefined) return plan.attack(name);
@@ -194,8 +198,9 @@ export async function proveTenant(plan: TenantAttack): Promise<ExerciseRecord> {
194
198
  const answer = await watched(name);
195
199
  if (plan.public !== undefined) return;
196
200
  const sweep = sweepReason(plan, answer, marks);
197
- if (sweep === undefined) findings.push(...leaksIn(name, answer, marks));
198
- else swept = sweep;
201
+ if (sweep !== undefined) swept = sweep;
202
+ else if (undeclared) findings.push(...leaksIn(name, answer, marks).map(asSweep));
203
+ else findings.push(...leaksIn(name, answer, marks));
199
204
  };
200
205
  await leg('before');
201
206
  const control = await plan.control();