@rightkit/release 0.6.57 → 0.6.62
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/README.md +4 -0
- package/acceptance-admission.mjs +104 -0
- package/acceptance-launch.mjs +234 -0
- package/acceptance-lines.mjs +1254 -0
- package/acceptance-result.mjs +77 -0
- package/acceptance-rows.mjs +47 -0
- package/admission-files.mjs +2 -0
- package/affected-units.mjs +17 -0
- package/app-check.mjs +6 -2
- package/app-closure.mjs +3 -1
- package/bin/rightkit-gate.mjs +552 -124
- package/broker-admission.mjs +45 -2
- package/broker-pins.mjs +11 -1
- package/broker-toolchain.mjs +113 -0
- package/cargo-profile-contract.mjs +7 -2
- package/class-a-cache-history.mjs +170 -0
- package/cli/right-release.mjs +0 -0
- package/code-closure.mjs +24 -0
- package/config-inspect.mjs +6 -0
- package/consumer-contracts.mjs +3 -1
- package/contract-nn.json +166 -0
- package/deterministic-scans.mjs +835 -112
- package/feature-coverage.mjs +109 -82
- package/feature-partition.mjs +76 -0
- package/forbidden-literals.mjs +78 -0
- package/gate/calls.mjs +121 -0
- package/gate/compile.mjs +190 -0
- package/gate/crate-results.mjs +127 -0
- package/gate/run-calls.mjs +241 -0
- package/gate/tests.mjs +234 -0
- package/gate-coverage.mjs +12 -3
- package/gate-release-admission.mjs +200 -0
- package/gate-seam.mjs +100 -4
- package/gate-serve.mjs +179 -34
- package/gate-stages.mjs +59 -0
- package/legacy-contract-receipt.mjs +809 -0
- package/local-publish.mjs +2 -4
- package/local-runtime.mjs +2 -2
- package/nsis-payload.mjs +4 -3
- package/ownership-applicability.mjs +5 -0
- package/ownership-class-rules.mjs +19 -8
- package/ownership-mandatory-set.json +15 -21
- package/ownership-mandatory-set.mjs +19 -4
- package/package.json +14 -8
- package/probe-memo.mjs +252 -0
- package/publication-artifacts.mjs +56 -2
- package/publish-local-npm.mjs +3 -0
- package/publish-update.mjs +2 -2
- package/receipt-signature.mjs +40 -0
- package/release.mjs +47 -29
- package/resident-answers.mjs +66 -0
- package/rightkit-ownership.json +20 -11
- package/rightkit-versions.json +349 -183
- package/runtime-bundle-stage.mjs +146 -0
- package/scan-digest.mjs +28 -4
- package/seam-broker.mjs +8 -1
- package/shell-contract.mjs +23 -2
- package/snapshot-changes.mjs +106 -0
- package/snapshot-check.mjs +17 -13
- package/snapshot-dependency-reuse.mjs +186 -14
- package/snapshot-git.mjs +17 -1
- package/snapshot-metadata.mjs +155 -3
- package/snapshot.mjs +89 -12
- package/spawn-ledger.mjs +21 -2
- package/stage-sidecar.mjs +231 -19
- package/suite-trust-roots.mjs +2 -2
- package/test-env.mjs +26 -0
- package/tool-version-memo.mjs +46 -0
- package/win-package-recipe.mjs +11 -0
- package/bin/darwin/rightkit-swap +0 -0
- package/gate-acceptance.mjs +0 -3362
package/deterministic-scans.mjs
CHANGED
|
@@ -26,8 +26,8 @@ import { fileURLToPath, pathToFileURL } from "node:url";
|
|
|
26
26
|
import { spawn as spawnChild, spawnSync } from "./background-process.mjs";
|
|
27
27
|
import { checkAdvisoryExceptions } from "./advisory-exceptions.mjs";
|
|
28
28
|
import { crateRunsOn, crossCompileEnv, oneOutput, scopedCrossTargets } from "./cross-targets.mjs";
|
|
29
|
-
import { declaredFeatureNames, effectiveCrateFeatures, featureCoverageProblems } from "./feature-coverage.mjs";
|
|
30
|
-
import { CLIPPY_UNIVERSAL_FEATURE_FLAGS, canonicalJson, clippyBatchPlan, clippySelectionOf, digestScanSet, requiredScanIds, rustCoverageSets, rustCratePlan, rustScanId } from "./scan-digest.mjs";
|
|
29
|
+
import { allFeatureNamesOf, declaredFeatureNames, effectiveCrateFeatures, featureCoverageProblems } from "./feature-coverage.mjs";
|
|
30
|
+
import { CLIPPY_UNIVERSAL_FEATURE_FLAGS, allFeaturesCheckIsRedundant, canonicalJson, clippyBatchPlan, clippySelectionOf, digestScanSet, requiredScanIds, rustCoverageSets, rustCratePlan, rustScanId } from "./scan-digest.mjs";
|
|
31
31
|
import { unlintedFeatures } from "./feature-sets.mjs";
|
|
32
32
|
import { reach } from "./lock-graph.mjs";
|
|
33
33
|
import { cargoManifestState } from "./cargo-manifest-text.mjs";
|
|
@@ -41,8 +41,9 @@ import { OutdatedUnavailableError, resolveOutdatedBin } from "./outdated-command
|
|
|
41
41
|
import { SCAN_TOKEN_ENV, readLedger, scanTokenOf, unclaimedLedgers } from "./cargo-ledger.mjs";
|
|
42
42
|
import { ADMISSION_POLL_MS, CARRIED_CANCEL_GRACE_MS, QUEUED_CEILING_FACTOR, createRunClock, createStatusPoller, watchBrokerAdmission } from "./broker-admission.mjs";
|
|
43
43
|
import { CANCEL_WAIT_ENV, operationDeadlineEnv } from "./broker-admission.mjs";
|
|
44
|
-
import {
|
|
45
|
-
import {
|
|
44
|
+
import { windowsPnpmIdentity } from "./snapshot-dependency-reuse.mjs";
|
|
45
|
+
import { compatibleTargetClasses, groupTargetDifference, meetPartitions, parseTreeFeatures, partitionByFeatures, partitionCacheKey, splitNote, stripSelectors, targetSplitNote, treeArgs, treeArgsForTargets, workspaceManifestDigest } from "./feature-partition.mjs";
|
|
46
|
+
import { CLASS_A_ENV, NOT_EXECUTED_EXIT, RECEIPT_NONCE_ENV, contractJobTag, judgeSeamOutcome, normalizeWorkspace, recordContractJob, seamEnv, seamSettled, verdictForRun } from "./gate-seam.mjs";
|
|
46
47
|
|
|
47
48
|
export const SCAN_RESULT_SCHEMA = "rightkit.deterministic-scans/1";
|
|
48
49
|
// The seam's run state for the door's lock release (reset plan section 3): a seam row whose client the gate killed, that timed out or was cancelled may have
|
|
@@ -61,7 +62,7 @@ export const CHECKER_IDENTITY = (() => {
|
|
|
61
62
|
try {
|
|
62
63
|
const p = JSON.parse(fs.readFileSync(new URL("./package.json", import.meta.url), "utf8"));
|
|
63
64
|
const h = crypto.createHash("sha256");
|
|
64
|
-
for (const f of ["./deterministic-scans.mjs", "./scan-digest.mjs", "./swift-lock.mjs", "./gradle-lock.mjs", "./python-lock.mjs", "./ghsa-audit.mjs"]) { h.update(f); h.update("\0"); h.update(fs.readFileSync(new URL(f, import.meta.url))); h.update("\0"); }
|
|
65
|
+
for (const f of ["./deterministic-scans.mjs", "./scan-digest.mjs", "./swift-lock.mjs", "./gradle-lock.mjs", "./python-lock.mjs", "./ghsa-audit.mjs", "./advisory-exceptions.mjs", "./feature-coverage.mjs", "./feature-sets.mjs", "./cargo-manifest-text.mjs", "./lock-graph.mjs"]) { h.update(f); h.update("\0"); h.update(fs.readFileSync(new URL(f, import.meta.url))); h.update("\0"); }
|
|
65
66
|
return `${p.name}@${p.version}#${h.digest("hex").slice(0, 16)}`;
|
|
66
67
|
} catch { return null; }
|
|
67
68
|
})();
|
|
@@ -108,6 +109,77 @@ export function deterministicScansEnabled(config) {
|
|
|
108
109
|
return config?.deterministicScans?.enabled === true;
|
|
109
110
|
}
|
|
110
111
|
|
|
112
|
+
// A tool's version, once it has answered, for the life of the process (NN07, NN25). A check looks every row up in the cache first and then runs
|
|
113
|
+
// what missed: two passes, and each asked every tool its version again (13 tools twice in one check, Dell 2026-11-17). Kept per spawn function, so
|
|
114
|
+
// a test that supplies its own sees only its own answers. Only a successful answer is kept; a missing or busy tool is asked again.
|
|
115
|
+
const PROBE_ANSWERS = new WeakMap();
|
|
116
|
+
const probeAnswersOf = (spawnFn) => { if (typeof spawnFn !== "function") return new Map(); let m = PROBE_ANSWERS.get(spawnFn); if (!m) { m = new Map(); PROBE_ANSWERS.set(spawnFn, m); } return m; };
|
|
117
|
+
|
|
118
|
+
// The same answer across runs (NN25: "a warm run starts no ... version probe"; NN01: a row answered from the cache starts no process of its tool,
|
|
119
|
+
// and `rustfmt --version` was the process). Remembered in the result cache under the tool's program file as it is on disk: its absolute path,
|
|
120
|
+
// size and modification time. A program that changed in any of those is asked again. A command that is not an absolute path to a file (a name
|
|
121
|
+
// found on PATH), or a .cmd/.bat shim whose answer depends on what it points at, is never remembered across runs.
|
|
122
|
+
export const PROBE_RECORD = "rightkit.tool-probe/1";
|
|
123
|
+
const defaultStat = (f) => fs.statSync(f);
|
|
124
|
+
/**
|
|
125
|
+
* The one program a Windows launcher shim starts, when the shim's own text says so beyond doubt: exactly one quoted absolute `.exe` path, and no
|
|
126
|
+
* `%~` (a path relative to the shim, as pnpm's shim uses) anywhere in it. The managed `rustright.cmd` is this shape
|
|
127
|
+
* (`"D:\.rustright\runtime\rustright.exe" %*`). Anything else answers null and is never remembered across runs.
|
|
128
|
+
*/
|
|
129
|
+
export function shimTarget(text) {
|
|
130
|
+
const s = String(text ?? "");
|
|
131
|
+
if (/%~/.test(s)) return null;
|
|
132
|
+
const found = [...s.matchAll(/"([A-Za-z]:\\[^"%\r\n]+\.exe)"/gi)].map((m) => m[1]);
|
|
133
|
+
return found.length === 1 ? found[0] : null;
|
|
134
|
+
}
|
|
135
|
+
const defaultReadText = (f) => fs.readFileSync(f, "utf8");
|
|
136
|
+
function probeIdentity(tool, command, key, statFile = defaultStat, readText = defaultReadText) {
|
|
137
|
+
if (typeof command !== "string" || !path.isAbsolute(command)) return null;
|
|
138
|
+
let st; try { st = statFile(command); } catch { return null; }
|
|
139
|
+
if (!st?.isFile?.()) return null;
|
|
140
|
+
if (/\.(cmd|bat)$/i.test(command)) {
|
|
141
|
+
// NN09 (Dell 2026-11-19): `rustright.cmd` was never remembered, so every compile run sent `cargo --version` through the broker again. A shim
|
|
142
|
+
// is remembered by its own bytes and by the program it starts as that program is on disk; a change of either asks again.
|
|
143
|
+
let text; try { text = readText(command); } catch { return null; }
|
|
144
|
+
const target = shimTarget(text); if (!target) return null;
|
|
145
|
+
let ts; try { ts = statFile(target); } catch { return null; }
|
|
146
|
+
if (!ts?.isFile?.()) return null;
|
|
147
|
+
// What the launched client answers also depends on files beside it and beside the launcher: the runtime manifest next to the target (which
|
|
148
|
+
// client and broker this is) and the host configuration two levels above the launcher (`<managed root>/config.json`: the `tools` the broker
|
|
149
|
+
// compiles with). Their bytes are part of the identity, so a new runtime or a changed tool asks again. Residual, stated in the evidence
|
|
150
|
+
// sheet: a broker still running with an older configuration answers with its old tools until it is restarted, and nothing here can see that.
|
|
151
|
+
const bytesOf = (f) => { try { return sha256(readText(f)); } catch { return null; } };
|
|
152
|
+
const runtimeManifest = bytesOf(path.join(path.dirname(target), "runtime-manifest.json"));
|
|
153
|
+
const hostConfig = bytesOf(path.join(path.dirname(path.dirname(command)), "config.json"));
|
|
154
|
+
return sha256(canonicalJson({ schema: PROBE_RECORD, tool, command, shim: sha256(text), target, size: ts.size, mtimeMs: Math.trunc(ts.mtimeMs), runtimeManifest, hostConfig, key }));
|
|
155
|
+
}
|
|
156
|
+
return sha256(canonicalJson({ schema: PROBE_RECORD, tool, command, size: st.size, mtimeMs: Math.trunc(st.mtimeMs), key }));
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* NN42: the parts of a compile row's arguments its group key is made from. `rest` is the arguments without the `-p <crate>` pair, `keyRest`
|
|
160
|
+
* those without the `--target <triple>` pair too, and `atKey` where the -p pair sits once the --target pair is taken out. Rows that differ
|
|
161
|
+
* only in their target, wherever each names it, get the same `keyRest` and `atKey`.
|
|
162
|
+
*/
|
|
163
|
+
export function batchKeyParts(args) {
|
|
164
|
+
const at = args.indexOf("-p");
|
|
165
|
+
const crate = at >= 0 ? args[at + 1] : null;
|
|
166
|
+
const rest = at >= 0 ? [...args.slice(0, at), ...args.slice(at + 2)] : [];
|
|
167
|
+
const ti = rest.indexOf("--target");
|
|
168
|
+
const target = ti >= 0 && typeof rest[ti + 1] === "string" ? rest[ti + 1] : null;
|
|
169
|
+
const keyRest = target ? [...rest.slice(0, ti), ...rest.slice(ti + 2)] : rest;
|
|
170
|
+
const atKey = target && ti < at ? at - 2 : at;
|
|
171
|
+
return { at, crate, rest, target, keyRest, atKey };
|
|
172
|
+
}
|
|
173
|
+
export function storedProbe(cache, tool, command, key, statFile, readText) {
|
|
174
|
+
if (!cache) return null; const id = probeIdentity(tool, command, key, statFile, readText); if (!id) return null;
|
|
175
|
+
const row = cache.read(id)?.row;
|
|
176
|
+
return row?.schema === PROBE_RECORD && row.tool === tool && row.command === command && row.outcome?.ok === true ? row.outcome : null;
|
|
177
|
+
}
|
|
178
|
+
export function storeProbe(cache, tool, command, key, outcome, statFile, readText) {
|
|
179
|
+
if (!cache || !outcome?.ok) return; const id = probeIdentity(tool, command, key, statFile, readText); if (!id) return;
|
|
180
|
+
cache.write(id, { schema: PROBE_RECORD, tool, command, outcome });
|
|
181
|
+
}
|
|
182
|
+
|
|
111
183
|
let neutralDir = null;
|
|
112
184
|
/** An empty directory outside every repository, for tool version probes. */
|
|
113
185
|
function probeDir() {
|
|
@@ -147,7 +219,7 @@ const sha256 = (value) => crypto.createHash("sha256").update(value).digest("hex"
|
|
|
147
219
|
|
|
148
220
|
// canonicalJson and digestScanSet live in the dependency-free scan-digest.mjs, so credentialed CI code that verifies
|
|
149
221
|
// scan receipts never loads this scanner.
|
|
150
|
-
export { canonicalJson, digestScanSet, requiredScanIds };
|
|
222
|
+
export { canonicalJson, digestScanSet, requiredScanIds, allFeaturesCheckIsRedundant };
|
|
151
223
|
|
|
152
224
|
// ---- gate result cache --------------------------------------------------------------------------------
|
|
153
225
|
// A passing class B scan is reused on a later run only when every input is identical: the key is the sha256 of the
|
|
@@ -175,7 +247,7 @@ const BUILD_ENV_PREFIXES = ["CARGO_", "RUST", "SCCACHE_", "RK_", "RIGHTKIT_", "R
|
|
|
175
247
|
// explicitly made 171 rows miss with no input change (rightkit#1552, Mac 2026-11-09, inheritedEnv [RUSTRIGHT_BUILD_BROKER_SOCKET] only).
|
|
176
248
|
// A network proxy (NPM_CONFIG_HTTPS_PROXY, NPM_CONFIG_NOPROXY, ...) changes how a download is routed, never what a scan proves, and a
|
|
177
249
|
// cloud host sets it per session (measured 2026-11-06: the cloud's NPM_CONFIG_HTTPS_PROXY moved between two runs and 1,115 rows missed).
|
|
178
|
-
const BUILD_ENV_EXCLUDED = /^(RK_GATE_|RUSTRIGHT_QUIET_LEASE$|RIGHTKIT_BUILD_OWNERSHIP$|RIGHTKIT_CARRIED_CARGO_MAP$|RUSTRIGHT_ATTEST_NONCE$|RUSTRIGHT_REQUEST_ID_FILE$|RUSTRIGHT_SNAPSHOT_REQUEST$|RK_DIRECT_RECEIPT$|RUSTRIGHT_BUILD_BROKER_SOCKET$|RIGHTKIT_CROSS_CC_DIR$|.*PROXY)/;
|
|
250
|
+
const BUILD_ENV_EXCLUDED = /^(RK_GATE_|RUSTRIGHT_GATE_RUN$|RUSTRIGHT_QUIET_LEASE$|RIGHTKIT_BUILD_OWNERSHIP$|RIGHTKIT_CARRIED_CARGO_MAP$|RUSTRIGHT_ATTEST_NONCE$|RUSTRIGHT_RECEIPT_NONCE$|RUSTRIGHT_REQUEST_ID_FILE$|RUSTRIGHT_SNAPSHOT_REQUEST$|RK_DIRECT_RECEIPT$|RUSTRIGHT_BUILD_BROKER_SOCKET$|RIGHTKIT_CROSS_CC_DIR$|.*PROXY)/;
|
|
179
251
|
// PNPM_HOME (where pnpm keeps its own binaries; the calling app profile picks it) is not an input of any scan and is to leave this key once every row's stored index carries
|
|
180
252
|
// its environment shape (a row that only hits never refreshed its index; excluding it first made 74 rows that had no shape miss; Mac 2026-11-07).
|
|
181
253
|
// RIGHTKIT_CROSS_CC_DIR is where the zig wrappers live, not what they are: a cross clippy row keys on its own CC_/CXX_/AR_ variables
|
|
@@ -237,21 +309,47 @@ export function scanCacheKey({ id, command, toolVersion, env = {}, inheritedEnv,
|
|
|
237
309
|
return sha256(canonicalJson({ id: String(id), command: String(command), toolVersion: String(toolVersion), env: { ...env }, inheritedEnv, digest: String(digest) }));
|
|
238
310
|
}
|
|
239
311
|
|
|
312
|
+
export function classACacheMismatch(expected, observed, fingerprint) {
|
|
313
|
+
if (observed.actual === expected.expected && (!expected.status || observed.status === expected.status)
|
|
314
|
+
&& (expected.expected !== "hit" || !expected.key || expected.key === observed.key)) return null;
|
|
315
|
+
return {
|
|
316
|
+
id: fingerprint.id, expected: expected.expected, actual: observed.actual,
|
|
317
|
+
reason: observed.reason ?? "validated lookup differs from forecast",
|
|
318
|
+
key: fingerprint.key, failureKey: fingerprint.failureKey,
|
|
319
|
+
...(expected.key ? { expectedKey: expected.key } : {}),
|
|
320
|
+
...(observed.key ? { actualKey: observed.key } : {}),
|
|
321
|
+
...(expected.status ? { expectedStatus: expected.status } : {}),
|
|
322
|
+
...(observed.status ? { actualStatus: observed.status } : {}),
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
|
|
240
326
|
const CACHE_KEY_SHAPE = /^[0-9a-f]{64}$/;
|
|
241
327
|
|
|
242
328
|
/** A cache directory (`<git dir>/rightkit-gate-cache`): { read(key) => entry | null, write(key, row) }. Never throws. */
|
|
243
329
|
export function fileScanCache(dir, { now = () => new Date(), fsApi = fs } = {}) {
|
|
244
330
|
const file = (key) => (CACHE_KEY_SHAPE.test(key) ? path.join(dir, `${key}.json`) : null);
|
|
331
|
+
const readOutcome = (key) => {
|
|
332
|
+
const f = file(key);
|
|
333
|
+
if (!f) return { entry: null, issue: "invalid cache key" };
|
|
334
|
+
let source;
|
|
335
|
+
try { source = fsApi.readFileSync(f, "utf8"); }
|
|
336
|
+
catch (error) { return { entry: null, issue: error.code === "ENOENT" ? "expected entry absent; removal cause unknown" : "cache entry unreadable" }; }
|
|
337
|
+
try {
|
|
338
|
+
const { checksum, ...entry } = JSON.parse(source);
|
|
339
|
+
if (checksum !== undefined && checksum !== sha256(JSON.stringify(entry))) return { entry: null, issue: "cache entry checksum failed" };
|
|
340
|
+
return { entry, issue: null };
|
|
341
|
+
} catch { return { entry: null, issue: "cache entry is malformed" }; }
|
|
342
|
+
};
|
|
245
343
|
return {
|
|
246
|
-
read(key) {
|
|
247
|
-
|
|
248
|
-
},
|
|
344
|
+
read(key) { return readOutcome(key).entry; },
|
|
345
|
+
readOutcome,
|
|
249
346
|
write(key, row) {
|
|
250
347
|
try {
|
|
251
348
|
const f = file(key); if (!f) return;
|
|
252
349
|
fsApi.mkdirSync(dir, { recursive: true });
|
|
253
350
|
const tmp = `${f}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
|
|
254
|
-
|
|
351
|
+
const entry = { key, at: now().toISOString(), row };
|
|
352
|
+
fsApi.writeFileSync(tmp, JSON.stringify({ ...entry, checksum: sha256(JSON.stringify(entry)) }));
|
|
255
353
|
fsApi.renameSync(tmp, f);
|
|
256
354
|
} catch { /* a cache that cannot be written is only a miss next time */ }
|
|
257
355
|
},
|
|
@@ -500,7 +598,7 @@ export function storedPassRow(s, row) {
|
|
|
500
598
|
// proof (executableProof: the bound output directories and each executable's path, package, target and sha256): a later serial row whose plain row is a cache hit
|
|
501
599
|
// re-checks every file against it (provenExecutables) and reuses them only when every one is still there with the same digest; otherwise it compiles once, alone.
|
|
502
600
|
const memberRuns = row.memberRuns ? Object.fromEntries(Object.entries(row.memberRuns).map(([id, v]) => { const { acceptedBinaries: _bins, ...rest } = v ?? {}; void _bins; return [id, rest]; })) : null;
|
|
503
|
-
return { id: s.id, class: s.class, command: s.command, tool: s.tool ?? null, toolVersion: row.toolVersion, status: "pass", ...(row.executableProof ? { executableProof: row.executableProof } : {}), ...(s.coverageKey || s.provesPublisher ? { snapshotEvidence: row.snapshotEvidence ?? null } : {}), ...(row.testRun || s.coverageKey ? { testRun: row.testRun ?? null } : {}), ...(row.results ? { results: row.results } : {}), ...(memberRuns ? { memberRuns } : {}) };
|
|
601
|
+
return { id: s.id, class: s.class, command: s.command, tool: s.tool ?? null, toolVersion: row.toolVersion, status: "pass", ...(row.executableProof ? { executableProof: row.executableProof } : {}), ...(row.snapshotEvidence || s.coverageKey || s.provesPublisher ? { snapshotEvidence: row.snapshotEvidence ?? null } : {}), ...(row.testRun || s.coverageKey ? { testRun: row.testRun ?? null } : {}), ...(row.results ? { results: row.results } : {}), ...(memberRuns ? { memberRuns } : {}) };
|
|
504
602
|
}
|
|
505
603
|
/** The digest-bound proof of a run's accepted test executables (plain data, cacheable): `{ boundDirs, binaries: [{ executable, package, target, version, manifestDir, sha256 }] }`. */
|
|
506
604
|
export function executableProofOf(accepted, boundDirs) {
|
|
@@ -733,7 +831,7 @@ export const INTERNAL_RULES_SCHEMA = "rightkit.internal-rules/1";
|
|
|
733
831
|
/** Why a row's cache key moved, from the stored pass's key parts to this run's: the input entries that differ (paths and the like), the tool
|
|
734
832
|
* version, the environment variables that differ. Bounded lists; evidence for Adrian's approval of a miss. */
|
|
735
833
|
/** A key's raw inputs as {path-like entry: value} (the files list entries become `files.N/<path>`), with the key suffix as "(key suffix)". */
|
|
736
|
-
export function flatKeyInputs(text) { const out = new Map(); const walk = (v, at) => { if (v && typeof v === "object") { if (Array.isArray(v) && v.length === 2 && typeof v[0] === "string" && typeof v[1] !== "object") { out.set(`${String(at).replace(/\.\d+$/, "")}/${v[0]}`, String(v[1])); return; } for (const [k, x] of Object.entries(v)) walk(x, at ? `${at}.${k}` : k); } else out.set(at, String(v)); }; const s = String(text); const m = /^([\[{][\s\S]*[\]}]):([
|
|
834
|
+
export function flatKeyInputs(text) { const out = new Map(); const walk = (v, at) => { if (v && typeof v === "object") { if (Array.isArray(v) && v.length === 2 && typeof v[0] === "string" && typeof v[1] !== "object") { out.set(`${String(at).replace(/\.\d+$/, "")}/${v[0]}`, String(v[1])); return; } for (const [k, x] of Object.entries(v)) walk(x, at ? `${at}.${k}` : k); } else out.set(at, String(v)); }; const s = String(text); const m = /^([\[{][\s\S]*[\]}]):([^\]}]+)$/.exec(s); try { walk(JSON.parse(m ? m[1] : s), ""); if (m) out.set("(key suffix)", m[2]); } catch { out.set("inputs", s); } return out; }
|
|
737
835
|
const isBlobId = (v) => typeof v === "string" && /^[0-9a-f]{40}([0-9a-f]{24})?$/.test(v);
|
|
738
836
|
/**
|
|
739
837
|
* Carry-over (Adrian 2026-11-07: a key change must not rerun or ask for approval what did not change). A stored pass keyed under an earlier key FORM is
|
|
@@ -777,7 +875,7 @@ export function carryOverProof(before, after, { entryNow }) {
|
|
|
777
875
|
}
|
|
778
876
|
|
|
779
877
|
export function explainKeyChange(before, after) {
|
|
780
|
-
const flat = (text) => { const out = new Map(); const walk = (v, at) => { if (v && typeof v === "object") { if (Array.isArray(v) && v.length === 2 && typeof v[0] === "string" && typeof v[1] !== "object") { out.set(`${String(at).replace(/\.\d+$/, "")}/${v[0]}`, String(v[1])); return; } for (const [k, x] of Object.entries(v)) walk(x, at ? `${at}.${k}` : k); } else out.set(at, String(v)); }; const s = String(text); const m = /^([\[{][\s\S]*[\]}]):([
|
|
878
|
+
const flat = (text) => { const out = new Map(); const walk = (v, at) => { if (v && typeof v === "object") { if (Array.isArray(v) && v.length === 2 && typeof v[0] === "string" && typeof v[1] !== "object") { out.set(`${String(at).replace(/\.\d+$/, "")}/${v[0]}`, String(v[1])); return; } for (const [k, x] of Object.entries(v)) walk(x, at ? `${at}.${k}` : k); } else out.set(at, String(v)); }; const s = String(text); const m = /^([\[{][\s\S]*[\]}]):([^\]}]+)$/.exec(s); try { walk(JSON.parse(m ? m[1] : s), ""); if (m) out.set("(key suffix)", m[2]); } catch { out.set("inputs", s); } return out; };
|
|
781
879
|
const a = flat(before?.inputs ?? ""); const b = flat(after?.inputs ?? "");
|
|
782
880
|
const inputs = [...new Set([...a.keys(), ...b.keys()])].filter((k) => a.get(k) !== b.get(k)).sort();
|
|
783
881
|
// Only names that can change a result count (buildEnvName); a publisher row's stored environment is the old whole-session one.
|
|
@@ -798,6 +896,14 @@ export function explainKeyChange(before, after) {
|
|
|
798
896
|
};
|
|
799
897
|
}
|
|
800
898
|
/** NN41: the compile scans whose failure can be deterministic: check, clippy and doc rows (single or batched, native or cross). Test runs are never among them. */
|
|
899
|
+
/** A Rust test row (`test:rust:...`, `test:rust-serial:...`) or a batched Rust test group (`test:batch:...`, S17 2026-11-18: the group is the row that runs). */
|
|
900
|
+
export const isRustTestRowId = (id) => /^test:(?:rust(?:-serial)?|batch):/.test(String(id));
|
|
901
|
+
/**
|
|
902
|
+
* NN41 for a test row: its failure is stored only when the test build did not compile (cargo's "could not compile"), which is as deterministic as a
|
|
903
|
+
* failed clippy row; a failing or flaky TEST is never stored, and is run again (witness fixture S17, 2026-11-17: test rows of crates with a real
|
|
904
|
+
* compile error reran with unchanged inputs).
|
|
905
|
+
*/
|
|
906
|
+
export const isTestCompileFailure = (text) => /could not compile `[^`]+`/.test(String(text ?? "")) && !/test result: FAILED|panicked at/.test(String(text ?? ""));
|
|
801
907
|
export const isFailureCacheableCompileId = (id) => /^(?:check|check-features|check-dependent|clippy|doc)(?::|$)/.test(String(id));
|
|
802
908
|
/** NN41: a plain (non-broker) compile exit whose output carries compiler error diagnostics and no sign of the environment failing (network, disk, signal, internal compiler error). */
|
|
803
909
|
export function isDeterministicCompileDiagnostics(text) {
|
|
@@ -1783,7 +1889,8 @@ export function planScans({
|
|
|
1783
1889
|
// all be on together (rightkit-db sqlcipher vs sqlcipher-system; qa-driver wv2 generations).
|
|
1784
1890
|
const own = featuresOf(name);
|
|
1785
1891
|
const crate = crateOf(name);
|
|
1786
|
-
const {
|
|
1892
|
+
const declared = (() => { const t = manifestTextOf(name); return typeof t === "string" ? allFeatureNamesOf(t) : null; })();
|
|
1893
|
+
const { lintSets, baseSets, crossSets, defaultCheck, checkSets, none } = rustCratePlan(own, platform, crate, declared);
|
|
1787
1894
|
// Every feature the crate declares must be enabled by one of the sets of ANY host (the feature-coverage scan below, rightkit#1231): a host-scoped set
|
|
1788
1895
|
// is linted on the host whose plan has it. `unlintedFeatures` names the features the gate never lints, each with its reason.
|
|
1789
1896
|
const unlinted = unlintedFeatures(own, crate);
|
|
@@ -1812,15 +1919,16 @@ export function planScans({
|
|
|
1812
1919
|
}
|
|
1813
1920
|
// NN40 (GC-A27): docs build as one command per workspace and configuration. The row is the doc subcommand with --no-deps, --lib, one `-p <crate>`,
|
|
1814
1921
|
// the lint set and --locked, with a batchUnit, so class B batching groups the doc rows of one workspace and configuration into one invocation
|
|
1815
|
-
// naming every crate. The
|
|
1922
|
+
// naming every crate. The row sets RUSTDOCFLAGS to DOC_RUSTDOCFLAGS: the broker adds nothing itself (it only admits exactly this value on doc), so
|
|
1923
|
+
// without it a rustdoc warning passed here and failed in CI (loop matrix G22, found from real receipts 2026-11-17).
|
|
1816
1924
|
// A crate with no library has no API docs to check.
|
|
1817
1925
|
if (exists(path.join(contentRoot, rustDir(name), "src", "lib.rs"))) {
|
|
1818
|
-
|
|
1926
|
+
{ const scan = cargoIn(ws, "doc", "--no-deps", "--lib", "-p", crate, ...lintSets[0], "--locked"); add({ id: rustScanId.doc(name), class: B, batchUnit: name, ...scan, env: { ...(scan.env ?? {}), RUSTDOCFLAGS: DOC_RUSTDOCFLAGS } }); }
|
|
1819
1927
|
}
|
|
1820
1928
|
}
|
|
1821
1929
|
// Class A, file-only (rightkit#1231): no feature of a crate's Cargo.toml may be left out of every planned feature set, so feature-gated code is never
|
|
1822
1930
|
// unchecked. Crates without Cargo features need no row.
|
|
1823
|
-
const featureful = coverageCrates.filter((c) => { const t = manifestTextOf(c.name); return typeof t === "string" && (
|
|
1931
|
+
const featureful = coverageCrates.filter((c) => { const t = manifestTextOf(c.name); return typeof t === "string" && ((allFeatureNamesOf(t)?.length ?? 1) > 0 || c.unlinted !== undefined); }); // implicit features too; a manifest it cannot read is checked
|
|
1824
1932
|
if (featureful.length) add({ id: "feature-coverage", class: A, internal: "feature-coverage", crates: featureful });
|
|
1825
1933
|
if (clippyBatching && clippyEntries.length) {
|
|
1826
1934
|
// One Clippy scan per batch (row 8.6): the independent batches first, the sidecar-bound ones after them (row 8.8; the compile lane
|
|
@@ -2065,9 +2173,7 @@ export function planScans({
|
|
|
2065
2173
|
if (x.batchUnit === undefined) return x;
|
|
2066
2174
|
const { batchUnit: unit, ...plain } = x;
|
|
2067
2175
|
if (!classBBatching || x.deferred || !Array.isArray(x.args) || (x.tool !== "rustright" && x.tool !== "cargo")) return plain;
|
|
2068
|
-
const at = x.args
|
|
2069
|
-
const crate = at >= 0 ? x.args[at + 1] : null;
|
|
2070
|
-
const rest = at >= 0 ? [...x.args.slice(0, at), ...x.args.slice(at + 2)] : [];
|
|
2176
|
+
const { at, crate, rest, target, keyRest, atKey } = batchKeyParts(x.args);
|
|
2071
2177
|
let why = null;
|
|
2072
2178
|
if (at < 0 || typeof crate !== "string" || x.args.indexOf("-p", at + 1) >= 0) why = "it does not name exactly one `-p <crate>`";
|
|
2073
2179
|
else if (rest.some((w) => /^(?:--features(?:=.*)?|-F.*)$/.test(w))) why = "its feature set names crate-specific features";
|
|
@@ -2077,10 +2183,10 @@ export function planScans({
|
|
|
2077
2183
|
// NN42 (LOCKED 2026-11-06): one check/clippy per stage names every --target. The target is not part of the group key: rows that differ only
|
|
2078
2184
|
// in their `--target <triple>` and that triple's own variables (CC_/CXX_/AR_/PKG_CONFIG_/RC_<triple>) share a key, and runScans runs crates
|
|
2079
2185
|
// with the same set of targets as ONE invocation naming all of them, so Cargo overlaps the triples' graphs under one build lock.
|
|
2080
|
-
|
|
2081
|
-
|
|
2186
|
+
// (2026-11-19) The --target pair is no part of the key at all, and the place of the -p pair is counted without it (batchKeyParts): the
|
|
2187
|
+
// host's own row carries its --target before -p (oneOutput, when the row is planned) and a cross-target row after it, so with the pair's
|
|
2188
|
+
// place in the key the host target never met the others and always ran as a command of its own.
|
|
2082
2189
|
const tripleKey = target ? target.replace(/-/g, "_") : null;
|
|
2083
|
-
const keyRest = target ? [...rest.slice(0, ti), "--target", "*", ...rest.slice(ti + 2)] : rest;
|
|
2084
2190
|
const keyEnv = target ? Object.fromEntries(Object.entries(x.env ?? {}).filter(([k]) => !(k.endsWith(`_${tripleKey}`) || k.toUpperCase().endsWith(`_${tripleKey.toUpperCase()}`)))) : x.env;
|
|
2085
2191
|
if (why) {
|
|
2086
2192
|
batchNotes.set(why, (batchNotes.get(why) ?? 0) + 1);
|
|
@@ -2088,17 +2194,17 @@ export function planScans({
|
|
|
2088
2194
|
// other target rows: the key keeps the crate, so only this crate's rows that differ by --target share an invocation (Mac 2026-11-07:
|
|
2089
2195
|
// rightkit-tauri-shell's feature sets ran one target at a time, 1.8 rows/min).
|
|
2090
2196
|
if (!target || at < 0 || typeof crate !== "string") return plain;
|
|
2091
|
-
const ownKey = sha256(canonicalJson({ tool: x.tool, cwd: x.cwd ?? ".", root: x.root, env: keyEnv, rest: keyRest, at, crate, only: "targets" })).slice(0, 16);
|
|
2197
|
+
const ownKey = sha256(canonicalJson({ tool: x.tool, cwd: x.cwd ?? ".", root: x.root, env: keyEnv, rest: keyRest, at: atKey, crate, only: "targets" })).slice(0, 16);
|
|
2092
2198
|
groupCount.set(ownKey, (groupCount.get(ownKey) ?? 0) + 1);
|
|
2093
2199
|
return { ...plain, batchable: { key: ownKey, at, crate, unit, target } };
|
|
2094
2200
|
}
|
|
2095
|
-
const key = sha256(canonicalJson({ tool: x.tool, cwd: x.cwd ?? ".", root: x.root, env: keyEnv, rest: keyRest, at })).slice(0, 16);
|
|
2201
|
+
const key = sha256(canonicalJson({ tool: x.tool, cwd: x.cwd ?? ".", root: x.root, env: keyEnv, rest: keyRest, at: atKey })).slice(0, 16);
|
|
2096
2202
|
groupCount.set(key, (groupCount.get(key) ?? 0) + 1);
|
|
2097
2203
|
return { ...plain, batchable: { key, at, crate, unit, ...(target ? { target } : {}) } };
|
|
2098
2204
|
});
|
|
2099
2205
|
if (groupCount.size) {
|
|
2100
2206
|
const grouped = [...groupCount.values()].filter((n) => n > 1);
|
|
2101
|
-
notes.push(`class B batching: ${scans.filter((x) => x.batchable).length} compile scan(s) in ${groupCount.size} configuration group(s); each group of one Cargo workspace
|
|
2207
|
+
notes.push(`class B batching: ${scans.filter((x) => x.batchable).length} compile scan(s) in ${groupCount.size} configuration group(s); each group of one Cargo workspace runs as one cargo invocation, naming every target its members resolve alike (${grouped.reduce((a, n) => a + n, 0)} scan(s) in ${grouped.length} shared group(s)), a failed group is attributed per crate from cargo's JSON messages, every row keeps its own id and command; before a group runs, each member's own feature resolution is compared with the group's (cargo tree, feature-partition.mjs; GATE-CONTRACT GC-A18) and a member the group would compile with other features runs apart`);
|
|
2102
2208
|
for (const [why, n] of batchNotes) notes.push(`class B batching: ${n} compile scan(s) stay their own invocation: ${why}`);
|
|
2103
2209
|
}
|
|
2104
2210
|
const ids = scans.map((s) => s.id);
|
|
@@ -2242,14 +2348,14 @@ export function killProcessTree(child, { platform = process.platform, run = spaw
|
|
|
2242
2348
|
* With `options.stdoutFile`, stdout is written to that file whole instead of kept in memory.
|
|
2243
2349
|
*/
|
|
2244
2350
|
export function defaultSpawnAsync(command, args, options = {}) {
|
|
2245
|
-
const { signal, stdoutFile, onSpawn, ...rest } = options;
|
|
2351
|
+
const { signal, stdoutFile, stdoutKeep = OUTPUT_KEEP, onSpawn, ...rest } = options;
|
|
2246
2352
|
const inv = resolveInvocation(command, args, { env: rest.env ?? process.env });
|
|
2247
2353
|
if (inv.error) return Promise.resolve({ status: null, stdout: "", stderr: "", error: inv.error });
|
|
2248
2354
|
if (signal?.aborted) return Promise.resolve({ status: null, stdout: "", stderr: "", error: new Error("cancelled"), cancelled: true });
|
|
2249
2355
|
return new Promise((resolve) => {
|
|
2250
2356
|
let stdout = ""; let stderr = ""; let error = null;
|
|
2251
2357
|
let truncated = false;
|
|
2252
|
-
const keep = (buf, chunk) => { const next = buf + chunk; if (next.length >
|
|
2358
|
+
const keep = (buf, chunk, limit) => { const next = buf + chunk; if (next.length > limit) { truncated = true; return next.slice(-limit); } return next; };
|
|
2253
2359
|
let child;
|
|
2254
2360
|
try {
|
|
2255
2361
|
// stdin is closed: no scan reads it, and an open pipe nobody writes can block a tool that probes it (Windows).
|
|
@@ -2263,8 +2369,8 @@ export function defaultSpawnAsync(command, args, options = {}) {
|
|
|
2263
2369
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
2264
2370
|
child.stdout.setEncoding("utf8"); child.stderr.setEncoding("utf8");
|
|
2265
2371
|
const sink = stdoutFile ? fs.createWriteStream(stdoutFile) : null;
|
|
2266
|
-
if (sink) child.stdout.pipe(sink); else child.stdout.on("data", (c) => { stdout = keep(stdout, c); });
|
|
2267
|
-
child.stderr.on("data", (c) => { stderr = keep(stderr, c); });
|
|
2372
|
+
if (sink) child.stdout.pipe(sink); else child.stdout.on("data", (c) => { stdout = keep(stdout, c, stdoutKeep); });
|
|
2373
|
+
child.stderr.on("data", (c) => { stderr = keep(stderr, c, OUTPUT_KEEP); });
|
|
2268
2374
|
child.on("error", (e) => { error = e; });
|
|
2269
2375
|
child.on("close", async (status) => {
|
|
2270
2376
|
if (sink) await new Promise((done) => (sink.writableFinished ? done() : sink.on("finish", done).on("error", done)));
|
|
@@ -3163,6 +3269,13 @@ export async function runScans(plan, options = {}) {
|
|
|
3163
3269
|
const probeScans = new WeakSet(); // scans looked up for runGroup's per-crate cache (answered like a lookup, never run)
|
|
3164
3270
|
const cache = options.cache && typeof options.cache.read === "function" && typeof options.cache.write === "function" && typeof options.cache.digest === "function" ? options.cache : null;
|
|
3165
3271
|
const cacheHits = [];
|
|
3272
|
+
const classACacheDecision = typeof options.classACacheForecast === "function" ? { fingerprints: [], forecast: [], actual: [], mismatches: [], dispatchedRows: [], retained: [] } : null;
|
|
3273
|
+
const classBCacheDecision = typeof options.classBCacheForecast === "function" ? { fingerprints: [], forecast: [], actual: [], mismatches: [], dispatchedRows: [], retained: [] } : null;
|
|
3274
|
+
const admittedB = new Map();
|
|
3275
|
+
const featureContextInputs = new Map();
|
|
3276
|
+
const admittedA = new Map();
|
|
3277
|
+
const admissionToolFiles = new Map();
|
|
3278
|
+
const admissionTrusts = new Map();
|
|
3166
3279
|
// The GitHub advisory scan's same-UTC-day answers live beside the pinned RustSec checkout; a run with no cache (the door's live-scans refresh) asks again.
|
|
3167
3280
|
if (cache) { try { ctx.ghsaCacheDir = path.join(deps.advisoryCacheRoot ?? advisoryCacheRoot({ env: deps.env, platform: deps.platform }), "ghsa-audit"); } catch { ctx.ghsaCacheDir = null; } }
|
|
3168
3281
|
let classAFailed = false;
|
|
@@ -3187,10 +3300,48 @@ export async function runScans(plan, options = {}) {
|
|
|
3187
3300
|
const classBBlocked = !inCallA && !priorClassAValid && options.classAEarlier !== true;
|
|
3188
3301
|
|
|
3189
3302
|
const toolCommand = (tool) => (tool === "node" ? deps.execPath : tool === "rustfmt" ? deps.findRustfmt({ env: deps.env, exists: deps.exists, readdir: deps.readdir, platform: deps.platform, spawn: deps.lookupSpawn }) : tool);
|
|
3303
|
+
const trustOf = (tool) => {
|
|
3304
|
+
if (!TRUSTED_SCAN_TOOLS.includes(tool)) return null;
|
|
3305
|
+
if (classACacheDecision && admissionTrusts.has(tool)) return admissionTrusts.get(tool);
|
|
3306
|
+
const trust = resolveTrustedScanTool(tool, { policy: options.toolPolicy, platform: deps.platform, ops: options.toolOps });
|
|
3307
|
+
if (classACacheDecision) admissionTrusts.set(tool, trust);
|
|
3308
|
+
return trust;
|
|
3309
|
+
};
|
|
3310
|
+
const observedCommand = (tool, command) => options.classAToolPaths?.[tool] ?? (["node", "rustfmt"].includes(tool) && path.isAbsolute(command ?? "") ? command : null);
|
|
3311
|
+
const commandStat = (file) => {
|
|
3312
|
+
const real = fs.realpathSync.native(file);
|
|
3313
|
+
const st = fs.statSync(real, { bigint: true });
|
|
3314
|
+
if (!st.isFile()) throw new Error(`${file} is not a regular tool file`);
|
|
3315
|
+
return `${real}\0${st.dev}:${st.ino}:${st.size}:${st.mtimeNs}:${st.ctimeNs}`;
|
|
3316
|
+
};
|
|
3317
|
+
const commandIdentity = (file) => {
|
|
3318
|
+
if (!admissionToolFiles.has(file)) {
|
|
3319
|
+
const stat = commandStat(file);
|
|
3320
|
+
const sha256 = sha256OfFile(file);
|
|
3321
|
+
if (commandStat(file) !== stat) throw new Error(`${file} changed while its tool identity was read`);
|
|
3322
|
+
admissionToolFiles.set(file, { stat, sha256 });
|
|
3323
|
+
}
|
|
3324
|
+
return admissionToolFiles.get(file).sha256;
|
|
3325
|
+
};
|
|
3326
|
+
const pnpmToolFiles = new Map();
|
|
3327
|
+
let pnpmIdentity = null;
|
|
3328
|
+
const currentPnpmIdentity = () => {
|
|
3329
|
+
const components = windowsPnpmIdentity(deps.env, { execPath: deps.execPath, readFile: (file) => {
|
|
3330
|
+
const stat = commandStat(file);
|
|
3331
|
+
const prior = pnpmToolFiles.get(file);
|
|
3332
|
+
if (prior?.stat === stat) return prior.bytes;
|
|
3333
|
+
const bytes = fs.readFileSync(file);
|
|
3334
|
+
if (commandStat(file) !== stat) throw new Error(`${file} changed while its tool identity was read`);
|
|
3335
|
+
pnpmToolFiles.set(file, { stat, bytes });
|
|
3336
|
+
return bytes;
|
|
3337
|
+
} });
|
|
3338
|
+
if (!components) throw new Error("actual pnpm executable cannot be bound to Windows launcher bytes");
|
|
3339
|
+
return { digest: sha256(canonicalJson(components)), program: components.find(([file]) => !/\.(cmd|bat)$/i.test(file))?.[0] ?? null };
|
|
3340
|
+
};
|
|
3190
3341
|
const probeFlight = singleFlightProbe(async (tool, scanDir = null) => {
|
|
3191
3342
|
let outcome;
|
|
3192
3343
|
// A trusted analyzer is resolved ONCE, from its enrolment (never PATH), and its bytes verified before this probe runs it.
|
|
3193
|
-
const trust =
|
|
3344
|
+
const trust = trustOf(tool);
|
|
3194
3345
|
const command = trust ? (trust.ok ? trust.identity.path : null) : toolCommand(tool);
|
|
3195
3346
|
if (trust && !trust.ok) outcome = { ok: false, code: trust.code, why: trust.why };
|
|
3196
3347
|
else if (!command) outcome = { ok: false, why: "not found" };
|
|
@@ -3233,13 +3384,51 @@ export async function runScans(plan, options = {}) {
|
|
|
3233
3384
|
// outside a Cargo workspace (rightkit#1215). Once it has answered in one directory that answer serves every directory: each fresh probe is a
|
|
3234
3385
|
// broker CONTROL-lane request, and one sent while this run holds the broker's quiet lease waits the lease out and fails (rightkit#1526).
|
|
3235
3386
|
let rustrightAnswer = null;
|
|
3387
|
+
// NN09 (Dell 2026-11-19): six components asked at once, before the first answer existed, so six `cargo --version` requests reached the broker.
|
|
3388
|
+
// While one rustright probe is in flight every other one waits for it; only if it failed does a waiter ask where its own scan runs.
|
|
3389
|
+
let rustrightFlight = null;
|
|
3236
3390
|
const probe = async (tool, scanDir = null) => {
|
|
3237
|
-
if (tool
|
|
3238
|
-
|
|
3391
|
+
if (tool !== "rustright") return probeBody(tool, scanDir);
|
|
3392
|
+
if (rustrightAnswer) return rustrightAnswer;
|
|
3393
|
+
// NN09: on a broker host the caller hands over the broker's own compiler, read from its host configuration (broker-toolchain.mjs): the
|
|
3394
|
+
// registered cargo, verified by its bytes. That is the answer, and no `rustright cargo --version` starts on any run.
|
|
3395
|
+
if (options.brokerToolchain?.ok === true && typeof options.brokerToolchain.cargo?.version === "string") {
|
|
3396
|
+
const version = options.brokerToolchain.cargo.version;
|
|
3397
|
+
rustrightAnswer = { ok: true, command: toolCommand(tool), version, pinProblem: pinnedVersionProblem(tool, version), source: "broker-host-configuration" };
|
|
3398
|
+
toolVersions[tool] = version;
|
|
3399
|
+
return rustrightAnswer;
|
|
3400
|
+
}
|
|
3401
|
+
if (rustrightFlight) { const first = await rustrightFlight.catch(() => null); if (rustrightAnswer) return rustrightAnswer; if (first?.ok) return first; }
|
|
3402
|
+
if (rustrightAnswer) return rustrightAnswer;
|
|
3403
|
+
const flight = probeBody(tool, scanDir);
|
|
3404
|
+
rustrightFlight = flight;
|
|
3405
|
+
try { return await flight; } finally { if (rustrightFlight === flight) rustrightFlight = null; }
|
|
3406
|
+
};
|
|
3407
|
+
const probeBody = async (tool, scanDir = null) => {
|
|
3408
|
+
const trust = trustOf(tool);
|
|
3239
3409
|
const command = trust ? (trust.ok ? trust.identity.path : null) : toolCommand(tool);
|
|
3410
|
+
const observed = classACacheDecision ? observedCommand(tool, command) : null;
|
|
3411
|
+
const windowsPnpm = classACacheDecision && tool === "pnpm" && deps.platform === "win32";
|
|
3412
|
+
if (windowsPnpm) pnpmIdentity ??= currentPnpmIdentity();
|
|
3413
|
+
const bytes = classACacheDecision ? trust?.identity?.sha256 ?? (observed ? commandIdentity(observed) : windowsPnpm ? pnpmIdentity.digest : null) : undefined;
|
|
3240
3414
|
const cwd = (tool === "rustright" || (tool === "cargo" && cargoLiveRoot)) && scanDir ? scanDir : (deps.probeDir ?? probeDir());
|
|
3241
|
-
const key = sha256(canonicalJson({ tool, command, cwd, args: PROBES[tool] ?? ["--version"], env: deps.env }));
|
|
3415
|
+
const key = sha256(canonicalJson({ tool, command, cwd, args: PROBES[tool] ?? ["--version"], env: deps.env, ...(bytes ? { bytes } : {}) }));
|
|
3416
|
+
// Across runs the probe's directory is a fresh temporary one and the environment carries per-run values, so the stored answer is keyed by what
|
|
3417
|
+
// can change a version answer: the program, its arguments, a scan directory when the probe runs in one, and the toolchain variables.
|
|
3418
|
+
const neutral = cwd === (deps.probeDir ?? neutralDir);
|
|
3419
|
+
const probeFile = observed ?? (windowsPnpm ? pnpmIdentity.program : null) ?? command;
|
|
3420
|
+
// NN25 (Dell 2026-11-19: `cargo.exe --version` on every warm run): the search path was part of this key, and on a broker host it holds a
|
|
3421
|
+
// directory made for this one run (the gate's cargo shim, rk-gate-shim-*), so no stored answer was ever found again. The search path decides
|
|
3422
|
+
// which program a NAME starts. When the program is one file named by its absolute path and bound by its bytes, the path decides nothing and
|
|
3423
|
+
// is left out; a tool started by name keeps it.
|
|
3424
|
+
// Not pnpm on Windows: its bound bytes are its launcher chain's, and what that chain ends up running can still depend on the path (review 2026-11-19).
|
|
3425
|
+
const boundFile = Boolean(bytes) && !windowsPnpm && typeof probeFile === "string" && path.isAbsolute(probeFile);
|
|
3426
|
+
const lastingEnv = boundFile ? /^(RUSTUP_TOOLCHAIN|RUSTUP_HOME|CARGO_HOME|RUSTC|COREPACK_HOME|PNPM_HOME)$/ : /^(PATH|Path|RUSTUP_TOOLCHAIN|RUSTUP_HOME|CARGO_HOME|RUSTC|COREPACK_HOME|PNPM_HOME)$/;
|
|
3427
|
+
const lasting = sha256(canonicalJson({ tool, command, args: PROBES[tool] ?? ["--version"], cwd: neutral ? "(neutral)" : tool === "rustright" ? "(any workspace)" : cwd, env: Object.fromEntries(Object.entries(deps.env ?? {}).filter(([k]) => lastingEnv.test(k)).sort()), ...(bytes ? { bytes } : {}) }));
|
|
3428
|
+
const answers = probeAnswersOf(deps.spawn); const remembered = answers.get(key) ?? storedProbe(cache, tool, probeFile, lasting, deps.statFile);
|
|
3429
|
+
if (remembered) { answers.set(key, remembered); toolVersions[tool] = remembered.version; if (remembered.identity) toolIdentities[tool] = { ...remembered.identity, probed: remembered.version }; return remembered; }
|
|
3242
3430
|
const outcome = await probeFlight(key, tool, scanDir);
|
|
3431
|
+
if (outcome?.ok) { answers.set(key, outcome); storeProbe(cache, tool, probeFile, lasting, outcome, deps.statFile); }
|
|
3243
3432
|
if (tool === "rustright" && outcome?.ok && !outcome.pinProblem) rustrightAnswer = outcome;
|
|
3244
3433
|
return outcome;
|
|
3245
3434
|
};
|
|
@@ -3260,13 +3449,15 @@ export async function runScans(plan, options = {}) {
|
|
|
3260
3449
|
}
|
|
3261
3450
|
async function runOneBody(s, extraEnv = null) {
|
|
3262
3451
|
if (signal?.aborted) return { id: s.id, class: s.class, command: s.command, tool: s.tool ?? null, toolVersion: null, status: "not-run", code: "CANCELLED", detail: "cancelled before it started" };
|
|
3452
|
+
if (s.class === SCAN_CLASS.A && classACacheDecision?.mismatches.length) return { id: s.id, class: s.class, command: s.command, tool: s.tool ?? null, toolVersion: null, status: "not-run", code: "CLASS_A_CACHE_DISAGREEMENT", detail: "Class A cache admission refused before dispatch" };
|
|
3453
|
+
if (s.class === SCAN_CLASS.B && classBCacheDecision?.mismatches.length) return { id: s.id, class: s.class, command: s.command, status: "not-run", code: "CLASS_B_CACHE_DISAGREEMENT", detail: "Class B cache admission refused before dispatch" };
|
|
3263
3454
|
const started = Date.now();
|
|
3264
3455
|
const scanStarted = performance.now();
|
|
3265
3456
|
let row = await scanRow(s, extraEnv);
|
|
3266
3457
|
// rightkit#1459: a class A scan that timed out is run once more before it fails Class A (a hung tool, e.g. actionlint on 2026-11-02, ran
|
|
3267
3458
|
// 27 min and failed a run whose rerun passed in 1 s). Class B and carried scans are not retried: a compile that times out is a real failure.
|
|
3268
3459
|
// Test suites are not retried either: a slow test is a finding, not a hung tool.
|
|
3269
|
-
if (row.status === "fail" && row.code === "TIMEOUT" && s.class === SCAN_CLASS.A && s.kind !== "test" && !signal?.aborted) {
|
|
3460
|
+
if (row.status === "fail" && row.code === "TIMEOUT" && s.class === SCAN_CLASS.A && s.kind !== "test" && !signal?.aborted && !classACacheDecision) {
|
|
3270
3461
|
const first = row;
|
|
3271
3462
|
row = await scanRow(s, extraEnv);
|
|
3272
3463
|
row = { ...row, retried: { code: first.code, detail: first.detail, timing: first.timing ?? null } };
|
|
@@ -3305,23 +3496,39 @@ export async function runScans(plan, options = {}) {
|
|
|
3305
3496
|
// Class A scans are independent content checks (and short broker calls: metadata, package list, deny, audit): they run
|
|
3306
3497
|
// `classAJobs` at a time (default: `jobs`); the rows keep plan order. Class B starts only once every class A row is in.
|
|
3307
3498
|
const aJobs = Math.max(1, Number(options.classAJobs ?? jobs) || jobs);
|
|
3499
|
+
// NN39 ("Serial work when it should be parallel? How does the system detect and fail that?", Adrian 2026-11-05): when each Class A row became
|
|
3500
|
+
// ready (its queue was opened to the lanes), when a lane took it and when it ended, with the number of lanes of its queue. The contract test
|
|
3501
|
+
// judged parallelism from child-process start times and read every later start as queued work, so planning time and a row's own second step
|
|
3502
|
+
// (deny after fetch) counted as idle lanes (Dell 2026-11-19, 6.5 s and 2.4 s on a cold check). This is the record a judge can read instead:
|
|
3503
|
+
// a lane is idle while work waits only if a row is ready, not started, and fewer rows are running than there are lanes.
|
|
3504
|
+
const classALanes = [];
|
|
3505
|
+
if (classACacheDecision) await admitClassACache();
|
|
3308
3506
|
{
|
|
3309
3507
|
// Class A is everything mechanical and deterministic that does not compile (Adrian, 2026-10-27): the content checks first,
|
|
3310
3508
|
// `classAJobs` at a time, then the class A tests (kind "test"), `testJobs` at a time, then the quiet ones alone under the
|
|
3311
3509
|
// broker's quiet lease. A failed content check stops the tests: they run on content class A already judged.
|
|
3312
3510
|
const slots = new Array(aScans.length);
|
|
3511
|
+
if (classACacheDecision?.mismatches.length) classAFailed = true;
|
|
3313
3512
|
const content = []; const tests = []; const quietTests = [];
|
|
3314
3513
|
aScans.forEach((s, i) => (s.kind === "test" ? (s.quiet === true ? quietTests : tests) : content).push(i));
|
|
3315
|
-
const drain = (queue, extraEnv = null
|
|
3316
|
-
|
|
3317
|
-
|
|
3318
|
-
|
|
3319
|
-
|
|
3320
|
-
|
|
3321
|
-
|
|
3514
|
+
const drain = (queue, extraEnv = null, laneCount = 1) => {
|
|
3515
|
+
const readyAt = Date.now(); // the queue is opened to its lanes now: every row in it is ready from this moment
|
|
3516
|
+
return async () => {
|
|
3517
|
+
while (queue.length) {
|
|
3518
|
+
const i = queue.shift();
|
|
3519
|
+
const startedAt = Date.now(); // the lane has taken the row
|
|
3520
|
+
// Every lane takes its first row before any row's own work begins: without this pause the lanes are entered one after another and each
|
|
3521
|
+
// would count the synchronous start of the rows before it (key hashing, the cache lookup) as time its own row sat ready and untaken.
|
|
3522
|
+
await null;
|
|
3523
|
+
slots[i] = aScans[i].kind === "test" && classAFailed
|
|
3524
|
+
? { id: aScans[i].id, class: aScans[i].class, command: aScans[i].command, tool: aScans[i].tool ?? null, toolVersion: null, status: "not-run", detail: "a class A content check failed; the class A tests start only after it passes" }
|
|
3525
|
+
: await runOne(aScans[i], extraEnv);
|
|
3526
|
+
classALanes.push({ id: aScans[i].id, readyAt, startedAt, endedAt: Date.now(), lanes: laneCount });
|
|
3527
|
+
}
|
|
3528
|
+
};
|
|
3322
3529
|
};
|
|
3323
|
-
await Promise.all(Array.from({ length: aJobs }, drain(content)));
|
|
3324
|
-
await Promise.all(Array.from({ length: testJobs }, drain(tests)));
|
|
3530
|
+
await Promise.all(Array.from({ length: aJobs }, drain(content, null, aJobs)));
|
|
3531
|
+
await Promise.all(Array.from({ length: testJobs }, drain(tests, null, testJobs)));
|
|
3325
3532
|
if (quietTests.length) {
|
|
3326
3533
|
// One broker quiet lease per quiet suite (the broker caps a lease at 30 min and has no renewal): each suite runs alone,
|
|
3327
3534
|
// under its own lease, with a timeout shorter than the lease, so a lease never expires while its suite still runs.
|
|
@@ -3330,6 +3537,10 @@ export async function runScans(plan, options = {}) {
|
|
|
3330
3537
|
slots[i] = { id: aScans[i].id, class: aScans[i].class, command: aScans[i].command, tool: aScans[i].tool ?? null, toolVersion: null, status: "not-run", detail: signal?.aborted ? "cancelled" : "a class A check failed; the quiet suites start only on a green class A" };
|
|
3331
3538
|
continue;
|
|
3332
3539
|
}
|
|
3540
|
+
if (admittedA.get(aScans[i].id)?.isHit) {
|
|
3541
|
+
slots[i] = await runOne(aScans[i]);
|
|
3542
|
+
continue;
|
|
3543
|
+
}
|
|
3333
3544
|
let lease = null;
|
|
3334
3545
|
if (quietLane) { try { lease = (await quietLane.acquire({ ttlMs: QUIET_LEASE_MAX_MS })) ?? null; } catch { lease = null; } }
|
|
3335
3546
|
if (!lease && options.requireQuietLease) {
|
|
@@ -3343,6 +3554,7 @@ export async function runScans(plan, options = {}) {
|
|
|
3343
3554
|
}
|
|
3344
3555
|
}
|
|
3345
3556
|
results.push(...slots);
|
|
3557
|
+
if (classACacheDecision) await Promise.all([...admittedA.values()].map((item) => item.scan.return()));
|
|
3346
3558
|
}
|
|
3347
3559
|
{
|
|
3348
3560
|
const slots = new Array(bScans.length);
|
|
@@ -3367,29 +3579,40 @@ export async function runScans(plan, options = {}) {
|
|
|
3367
3579
|
// running it N times would repeat it N times. Feature unification: one invocation unifies features across its crates, so before a group runs the planner
|
|
3368
3580
|
// resolves each member alone and in the group with `cargo tree` (feature-partition.mjs) and keeps in one invocation only the members the group resolves as they resolve alone.
|
|
3369
3581
|
const groupOf = new Map();
|
|
3582
|
+
const targetAt = (i) => bScans[i].batchable.target ?? null;
|
|
3370
3583
|
if (options.classBBatching === true) {
|
|
3371
3584
|
const byKey = new Map();
|
|
3372
3585
|
bScans.forEach((s, i) => { if (s.batchable && !s.deferred && (laneOf(s) === "compile" || laneOf(s) === "doc" || (options.groupTests !== false && laneOf(s) === "tests" && s.runOutside && (/^test:rust/.test(s.id) || s.publisherRustTest === true)))) { if (!byKey.has(s.batchable.key)) byKey.set(s.batchable.key, []); byKey.get(s.batchable.key).push(i); } });
|
|
3373
3586
|
for (const all of byKey.values()) {
|
|
3374
3587
|
// NN42: within one key, crates with the same set of targets form one invocation (crates x targets is exactly its members).
|
|
3588
|
+
const subOf = (s) => s.args[s.args[0] === "cargo" ? 1 : 0];
|
|
3589
|
+
const several = (s) => subOf(s) === "clippy" || subOf(s) === "check";
|
|
3375
3590
|
const targetsOf = new Map();
|
|
3376
|
-
for (const i of all) { const c = bScans[i].batchable.crate; if (!targetsOf.has(c)) targetsOf.set(c, new Set()); targetsOf.get(c).add(
|
|
3591
|
+
for (const i of all) { const c = bScans[i].batchable.crate; if (!targetsOf.has(c)) targetsOf.set(c, new Set()); targetsOf.get(c).add(targetAt(i) ?? ""); }
|
|
3377
3592
|
const parts = new Map();
|
|
3378
3593
|
// One target per invocation (2026-11-10, HeardRight on the Dell): Cargo resolves features for host dependencies and target dependencies, never per triple, so a
|
|
3379
3594
|
// call naming two targets gives each the union of both targets' features (the macOS-only sqlcipher-system reached the Linux target, whose C code then wanted
|
|
3380
3595
|
// OpenSSL headers). Rows are grouped across crates for the SAME target; a crate's rows for different targets are never one invocation.
|
|
3381
|
-
|
|
3382
|
-
|
|
3596
|
+
// NN42 (2026-11-19): that is true where the targets resolve differently, and only there. For check and clippy (the commands the broker
|
|
3597
|
+
// takes several --target for) crates with the same set of targets are one candidate group again; before it runs, featurePartition
|
|
3598
|
+
// keeps in one invocation only the targets that resolve every package they share alike (targetClassesOf, cargo's own answer through
|
|
3599
|
+
// `cargo tree`), and the others stay one target per invocation, each pair named with the package that separates it.
|
|
3600
|
+
for (const i of all) {
|
|
3601
|
+
const s = bScans[i];
|
|
3602
|
+
const part = several(s) ? [...targetsOf.get(s.batchable.crate)].sort().join(",") : (s.batchable.target ?? "");
|
|
3603
|
+
if (!parts.has(part)) parts.set(part, []); parts.get(part).push(i);
|
|
3604
|
+
}
|
|
3383
3605
|
for (const members of parts.values()) if (members.length > 1) { const group = { members, promise: null }; for (const i of members) groupOf.set(i, group); }
|
|
3384
3606
|
}
|
|
3385
3607
|
}
|
|
3386
3608
|
const batchScanOf = (idx) => {
|
|
3387
|
-
|
|
3609
|
+
// The row the command is built from names a --target when any member does (a host row names none): the pair is then replaced by every target.
|
|
3610
|
+
const lead = bScans[idx.find((i) => bScans[i].args.includes("--target")) ?? idx[0]];
|
|
3388
3611
|
const { batchable: _batchable, ...plain } = lead; void _batchable;
|
|
3389
3612
|
// A group that holds a plan row standing for a publisher requirement stores and returns the receipt its members' publisher verdicts need (NN27, planUnitListScans).
|
|
3390
3613
|
if (idx.some((i) => bScans[i].provesPublisher === true)) plain.provesPublisher = true;
|
|
3391
3614
|
const crates = [...new Set(idx.map((i) => bScans[i].batchable.crate))];
|
|
3392
|
-
const targets = [...new Set(idx.map((i) =>
|
|
3615
|
+
const targets = [...new Set(idx.map((i) => targetAt(i)).filter(Boolean))];
|
|
3393
3616
|
let args = [...lead.args.slice(0, lead.batchable.at), ...crates.flatMap((c) => ["-p", c]), ...lead.args.slice(lead.batchable.at + 2)];
|
|
3394
3617
|
// Benchmark-only merged feature rows: drop the lead's own feature flags and name every member's features as <crate>/<feature>.
|
|
3395
3618
|
if (idx.some((i) => Array.isArray(bScans[i].batchable.features))) {
|
|
@@ -3401,7 +3624,7 @@ export async function runScans(plan, options = {}) {
|
|
|
3401
3624
|
if (targets.length > 1) { const t = args.indexOf("--target"); if (t >= 0) args = [...args.slice(0, t), ...targets.flatMap((x) => ["--target", x]), ...args.slice(t + 2)]; }
|
|
3402
3625
|
if (targets.length > 1) plain.env = Object.assign({}, ...idx.map((i) => bScans[i].env ?? {}));
|
|
3403
3626
|
const units = [...new Set(idx.map((i) => bScans[i].batchable.unit))].map((u) => targets.length > 1 ? u : u);
|
|
3404
|
-
const memberKey = idx.map((i) => `${bScans[i].batchable.unit}@${
|
|
3627
|
+
const memberKey = idx.map((i) => `${bScans[i].batchable.unit}@${targetAt(i) ?? ""}`);
|
|
3405
3628
|
// A publisher row (a unit-list run) is named by its cargo subcommand, a plan row by its id.
|
|
3406
3629
|
const sub = lead.publisherPhase ? lead.args[lead.args[0] === "cargo" ? 1 : 0] : null;
|
|
3407
3630
|
const stage = sub ? (sub === "clippy" ? "clippy" : sub === "doc" ? "doc" : sub === "test" ? "test" : "check") : /^clippy/.test(lead.id) ? "clippy" : /^doc:/.test(lead.id) ? "doc" : /^test:rust/.test(lead.id) ? "test" : "check";
|
|
@@ -3428,6 +3651,14 @@ export async function runScans(plan, options = {}) {
|
|
|
3428
3651
|
// (2026-11-07: 296 conflicting pairs across 28 crates; a member's projected pass hid its own error). The group's row is stored under the
|
|
3429
3652
|
// group's own key by its own scanRow; a member hits alone only after it ran alone (store rule, Adrian 2026-11-08). In a cache lookup the members are reported one by one, each with its own cause.
|
|
3430
3653
|
const runGroup = async (idx, extraEnv, budget, probed = false) => {
|
|
3654
|
+
if (classBCacheDecision && !classAFailed && !classBBlocked && !signal?.aborted) {
|
|
3655
|
+
const ready = bPreparedGroups.get(idx[0]);
|
|
3656
|
+
for (const i of ready.hits) slots[i] = await runOne(bScans[i], extraEnv);
|
|
3657
|
+
await Promise.all(ready.parts.map((part) => part.length === 1
|
|
3658
|
+
? runOne(bScans[part[0]], extraEnv).then((row) => { slots[part[0]] = row; })
|
|
3659
|
+
: runGroupBody(part, extraEnv)));
|
|
3660
|
+
return;
|
|
3661
|
+
}
|
|
3431
3662
|
if (probed || !cache || idx.length < 2 || signal?.aborted) return runParts(idx, extraEnv, budget);
|
|
3432
3663
|
const started = Date.now();
|
|
3433
3664
|
const looked = await Promise.all(idx.map(async (i) => { const copy = { ...bScans[i] }; probeScans.add(copy); try { return [i, await scanRow(copy, extraEnv)]; } catch (error) { return [i, { ...failedRow(i, error) }]; } }));
|
|
@@ -3455,22 +3686,62 @@ export async function runScans(plan, options = {}) {
|
|
|
3455
3686
|
// The partition of a configuration group's members (feature-partition.mjs), as index lists in plan order. A group naming several targets
|
|
3456
3687
|
// (NN42) keeps as one invocation only the members equivalent on every target; the others run alone.
|
|
3457
3688
|
const partitionMemo = new Map();
|
|
3689
|
+
const treeMemo = new Map();
|
|
3690
|
+
const featureProofOf = new Map();
|
|
3458
3691
|
const FEATURE_PARTITION_MS = 5 * 60_000;
|
|
3459
3692
|
const featurePartition = async (idx) => {
|
|
3460
3693
|
const lead = bScans[idx[0]];
|
|
3461
3694
|
const prefix = lead.args[0] === "cargo" ? ["cargo"] : [];
|
|
3462
3695
|
const { rest } = stripSelectors(lead.args.slice(prefix.length));
|
|
3463
3696
|
const crates = [...new Set(idx.map((i) => bScans[i].batchable.crate))];
|
|
3464
|
-
|
|
3465
|
-
const
|
|
3466
|
-
|
|
3467
|
-
|
|
3697
|
+
const cwd = lead.cwd ?? "."; const env = lead.env ?? {};
|
|
3698
|
+
const evidence = [];
|
|
3699
|
+
// A command names crates x targets, so its members must be exactly that product. When some rows of a group were answered from the
|
|
3700
|
+
// store and others not, the crates left can differ in which targets they still need: each set of crates with the same targets is a
|
|
3701
|
+
// group of its own, and nothing is compiled for a pair that has no row here (review 2026-11-19).
|
|
3702
|
+
{
|
|
3703
|
+
const targetsOfCrate = new Map();
|
|
3704
|
+
for (const i of idx) { const c = bScans[i].batchable.crate; if (!targetsOfCrate.has(c)) targetsOfCrate.set(c, new Set()); targetsOfCrate.get(c).add(targetAt(i) ?? ""); }
|
|
3705
|
+
const shape = (c) => [...targetsOfCrate.get(c)].sort().join(",");
|
|
3706
|
+
const shapes = new Set([...targetsOfCrate.keys()].map(shape));
|
|
3707
|
+
if (shapes.size > 1) return (await Promise.all([...shapes].map((s) => featurePartition(idx.filter((i) => shape(bScans[i].batchable.crate) === s))))).flat();
|
|
3708
|
+
}
|
|
3709
|
+
// NN42: several targets share one invocation only where that changes no target's own feature resolution (targetClassesOf).
|
|
3710
|
+
const named = [...new Set(idx.map((i) => targetAt(i)))];
|
|
3711
|
+
if (named.length > 1) {
|
|
3712
|
+
const { classes, proof } = await targetClassesOf({ tool: lead.tool, prefix, rest, crates, targets: named, cwd, env });
|
|
3713
|
+
if (classes.length > 1) return (await Promise.all(classes.map((cls) => featurePartition(idx.filter((i) => cls.includes(targetAt(i))))))).flat();
|
|
3714
|
+
if (proof) evidence.push(proof);
|
|
3715
|
+
}
|
|
3716
|
+
if (crates.length < 2) { if (evidence.length) featureProofOf.set(idx.join(","), evidence); return [idx]; }
|
|
3717
|
+
const parts = await partitionCrates({ tool: lead.tool, prefix, rest, crates, targets: named, cwd, env, evidence });
|
|
3718
|
+
const result = parts.map((p) => idx.filter((i) => p.crates.includes(bScans[i].batchable.crate))).filter((part) => part.length);
|
|
3719
|
+
// Review 2026-11-19: the targets were found alike for ALL these crates named together. A smaller set of them can differ (a crate that
|
|
3720
|
+
// turns a feature on for every target hides another crate's use of it on one target only), and the smaller set is what the command
|
|
3721
|
+
// will name. So when the crates split, each part is judged again as a group of its own: its targets, then its crates.
|
|
3722
|
+
if (named.length > 1 && result.length > 1) return (await Promise.all(result.map((part) => featurePartition(part)))).flat();
|
|
3723
|
+
for (const part of result) featureProofOf.set(part.join(","), evidence);
|
|
3724
|
+
return result;
|
|
3468
3725
|
};
|
|
3469
|
-
|
|
3726
|
+
// What `cargo tree` is asked under: of a row's own environment only the variables that can change how Cargo resolves (which toolchain and
|
|
3727
|
+
// home, flags that set a cfg, a default target). A row's other settings (RUSTDOCFLAGS on a doc group, CC_<triple> on a cross row, its
|
|
3728
|
+
// output directory) change nothing here, and with them in the key the same question was put twice (review 2026-11-19; the contract
|
|
3729
|
+
// test fails any program started twice with the same arguments in the same directory).
|
|
3730
|
+
const TREE_ENV = /^(RUSTFLAGS|CARGO_ENCODED_RUSTFLAGS|CARGO_BUILD_RUSTFLAGS|CARGO_BUILD_TARGET|CARGO_HOME|RUSTUP_HOME|RUSTUP_TOOLCHAIN|RUSTC|RUSTC_WRAPPER|RUSTC_WORKSPACE_WRAPPER|RUSTC_BOOTSTRAP|CARGO_BUILD_RUSTC|CARGO_BUILD_RUSTC_WRAPPER|CARGO_NET_OFFLINE|CARGO_TARGET_[A-Z0-9_]+_RUSTFLAGS|CARGO_REGISTRIES_[A-Z0-9_]+|CARGO_RESOLVER_[A-Z0-9_]+|CARGO_UNSTABLE_[A-Z0-9_]+)$/;
|
|
3731
|
+
// NN07 (Dell 2026-11-19, first compile: every `cargo tree` of the rk workspace started twice). A clippy group and a test group of the same
|
|
3732
|
+
// crates resolve with the same tree arguments, and each asked for itself. One run asks each resolution (tool, directory, arguments, the
|
|
3733
|
+
// row's own environment without its per-triple settings) once; the second caller gets the same answer, or the same failure.
|
|
3734
|
+
// `target` is one triple, null, or a list of triples (the call that will name them all, NN42).
|
|
3735
|
+
const treeOf = ({ tool, prefix, rest, cwd, env }) => {
|
|
3470
3736
|
const dir = path.join(contentRoot, cwd);
|
|
3471
|
-
const
|
|
3472
|
-
|
|
3473
|
-
const
|
|
3737
|
+
const tree = (packages, target) => {
|
|
3738
|
+
const args = Array.isArray(target) ? treeArgsForTargets({ rest, packages, targets: target }) : treeArgs({ rest, packages, target });
|
|
3739
|
+
const { CARGO_TARGET_DIR: _targetDirKey, ...keyEnv } = env; void _targetDirKey;
|
|
3740
|
+
const memoKey = canonicalJson([tool, prefix, dir, args, Object.entries(keyEnv).filter(([k]) => TREE_ENV.test(k)).sort(([x], [y]) => (x < y ? -1 : x > y ? 1 : 0))]);
|
|
3741
|
+
if (!treeMemo.has(memoKey)) treeMemo.set(memoKey, treeAsked(args, packages, target));
|
|
3742
|
+
return treeMemo.get(memoKey);
|
|
3743
|
+
};
|
|
3744
|
+
const treeAsked = async (args, packages, target) => {
|
|
3474
3745
|
const token = cargoLedger ? scanTokenOf(`feature-partition:${cwd}`) : null; if (token) claimedTokens.add(token);
|
|
3475
3746
|
const { CARGO_TARGET_DIR: _targetDir, ...rowEnv } = env; void _targetDir;
|
|
3476
3747
|
// Compiles nothing and must leave the tree as it is: its output directory is a scratch one outside every root (the direct read spawn gives it another).
|
|
@@ -3478,18 +3749,73 @@ export async function runScans(plan, options = {}) {
|
|
|
3478
3749
|
let r;
|
|
3479
3750
|
try { r = await deps.spawn(tool, [...prefix, ...args], { cwd: dir, env: { ...deps.env, ...rowEnv, CARGO_TARGET_DIR: scratch, ...(token ? { [SCAN_TOKEN_ENV]: token } : {}) }, timeout: FEATURE_PARTITION_MS, ...sig }); }
|
|
3480
3751
|
finally { try { fs.rmSync(scratch, { recursive: true, force: true }); } catch { /* a scratch directory under the gate's tmp root */ } }
|
|
3481
|
-
|
|
3752
|
+
const named = Array.isArray(target) ? target.join(", ") : target;
|
|
3753
|
+
if (!r || r.error || r.status !== 0) throw new Error(`cargo tree for ${packages.join(", ")}${named ? ` (--target ${named})` : ""} in ${cwd} failed: ${r?.error?.message ?? (tail(r) || `exit ${r?.status}`)}`);
|
|
3482
3754
|
return r.stdout ?? "";
|
|
3483
3755
|
};
|
|
3756
|
+
return tree;
|
|
3757
|
+
};
|
|
3758
|
+
// NN42: which of a group's targets may be named in ONE invocation. Each target is resolved alone (`cargo tree`, every crate of the group);
|
|
3759
|
+
// targets that resolve every package they share alike form a class (compatibleTargetClasses), and cargo's own resolution of the call
|
|
3760
|
+
// naming a whole class must then be each member's resolution alone (groupTargetDifference), else that class runs one target per
|
|
3761
|
+
// invocation too. Every pair kept apart is printed with the package that separates it (targetSplitNote): the contract test accepts one
|
|
3762
|
+
// command per target only with that note for each pair. The broker takes several --target for check and clippy only.
|
|
3763
|
+
const targetClassMemo = new Map();
|
|
3764
|
+
const targetClassesOf = ({ tool, prefix, rest, crates: given, targets, cwd, env }) => {
|
|
3765
|
+
const sub = rest[0];
|
|
3766
|
+
const apart = () => Promise.resolve({ classes: targets.map((t) => [t]), proof: null });
|
|
3767
|
+
if ((sub !== "clippy" && sub !== "check") || targets.some((t) => typeof t !== "string" || !t)) return apart();
|
|
3768
|
+
const crates = [...given].sort(); // the order the crate partition asks in, so the same question is one question
|
|
3769
|
+
const memoKey = canonicalJson([tool, prefix, cwd, rest, crates, [...targets].sort()]);
|
|
3770
|
+
if (!targetClassMemo.has(memoKey)) targetClassMemo.set(memoKey, (async () => {
|
|
3771
|
+
const tree = treeOf({ tool, prefix, rest, cwd, env });
|
|
3772
|
+
const texts = await Promise.all(targets.map((t) => tree(crates, t)));
|
|
3773
|
+
const features = new Map(targets.map((t, i) => [t, parseTreeFeatures(texts[i])]));
|
|
3774
|
+
const { classes, differences } = compatibleTargetClasses(features);
|
|
3775
|
+
for (const d of differences) partitionNotes.add(targetSplitNote({ sub, cwd, crates, ...d }));
|
|
3776
|
+
const out = [];
|
|
3777
|
+
for (const cls of classes) {
|
|
3778
|
+
if (cls.length < 2) { out.push(cls); continue; }
|
|
3779
|
+
const d = groupTargetDifference(parseTreeFeatures(await tree(crates, cls)), features, cls);
|
|
3780
|
+
if (!d) { out.push(cls); continue; }
|
|
3781
|
+
// Cargo resolves the call naming them all differently from one of them alone: none of this class shares a command.
|
|
3782
|
+
for (const t of cls) out.push([t]);
|
|
3783
|
+
for (let i = 0; i < cls.length; i += 1) for (let j = i + 1; j < cls.length; j += 1) partitionNotes.add(targetSplitNote({ sub, cwd, crates, a: cls[i], b: cls[j], package: d.package, aFeatures: d.aloneFeatures, bFeatures: d.groupFeatures ?? [] }));
|
|
3784
|
+
}
|
|
3785
|
+
// Every target in one class: that finding is stored like a crate partition's, so a member's kept result can show it later (a result
|
|
3786
|
+
// of a command naming several targets is kept for a member only with this proof). The classes themselves are asked of cargo on every
|
|
3787
|
+
// run that sends such a command: the run's own ledger then shows the question behind each note.
|
|
3788
|
+
let proof = null;
|
|
3789
|
+
if (out.length === 1 && cache) {
|
|
3790
|
+
let toolVersion = null;
|
|
3791
|
+
try { toolVersion = (await probe(tool, path.join(cargoLiveRoot ?? contentRoot, cwd)))?.version ?? null; } catch { toolVersion = null; }
|
|
3792
|
+
const context = { kind: "targets", rest, crates, targets: [...targets].sort(), cwd, inputs: workspaceManifestDigest(path.join(contentRoot, cwd)), toolVersion };
|
|
3793
|
+
const key = targetsProofKey(context);
|
|
3794
|
+
cache.write(key, { id: "feature-partition-targets", status: "pass", crates, targets: context.targets });
|
|
3795
|
+
const kept = cache.read(key);
|
|
3796
|
+
if (kept?.key === key && kept.row?.id === "feature-partition-targets") proof = { key, context, rowDigest: cacheEntryIdentity(kept.row) };
|
|
3797
|
+
}
|
|
3798
|
+
return { classes: out, proof };
|
|
3799
|
+
})());
|
|
3800
|
+
return targetClassMemo.get(memoKey);
|
|
3801
|
+
};
|
|
3802
|
+
const partitionCrates = async ({ tool, prefix, rest, crates, targets, cwd, env, evidence }) => {
|
|
3803
|
+
const dir = path.join(contentRoot, cwd);
|
|
3804
|
+
const inputs = workspaceManifestDigest(dir);
|
|
3805
|
+
const tree = treeOf({ tool, prefix, rest, cwd, env });
|
|
3484
3806
|
// The cargo that resolves is part of what it resolves (fresh review 2026-11-09, E6): its version joins the key, with the module's own code (partitionCacheKey).
|
|
3485
3807
|
let toolVersion = null;
|
|
3486
3808
|
try { toolVersion = (await probe(tool, path.join(cargoLiveRoot ?? contentRoot, cwd)))?.version ?? null; } catch { toolVersion = null; }
|
|
3487
3809
|
const one = async (target) => {
|
|
3488
|
-
const
|
|
3810
|
+
const context = { rest, crates, target, cwd, inputs, toolVersion };
|
|
3811
|
+
const key = partitionCacheKey(context);
|
|
3489
3812
|
const stored = cache?.read(key);
|
|
3490
|
-
if (stored && stored.key === key && Array.isArray(stored.row?.partition)) return stored.row.partition;
|
|
3813
|
+
if (stored && stored.key === key && Array.isArray(stored.row?.partition)) { evidence.push({ key, context, rowDigest: cacheEntryIdentity(stored.row) }); return stored.row.partition; }
|
|
3491
3814
|
if (!partitionMemo.has(key)) partitionMemo.set(key, partitionByFeatures({ crates, tree: (packages) => tree(packages, target) }).then((parts) => { cache?.write(key, { id: "feature-partition", status: "pass", crates: [...crates].sort(), target, partition: parts }); return parts; }));
|
|
3492
|
-
|
|
3815
|
+
const result = await partitionMemo.get(key);
|
|
3816
|
+
const retained = cache?.read(key);
|
|
3817
|
+
if (retained?.key === key && Array.isArray(retained.row?.partition)) evidence.push({ key, context, rowDigest: cacheEntryIdentity(retained.row) });
|
|
3818
|
+
return result;
|
|
3493
3819
|
};
|
|
3494
3820
|
// Several targets (NN42): the common refinement of the per-target partitions, so no boundary any target drew is crossed (rightkit#1538, second review).
|
|
3495
3821
|
const result = meetPartitions(await Promise.all(targets.map(one)));
|
|
@@ -3530,8 +3856,8 @@ export async function runScans(plan, options = {}) {
|
|
|
3530
3856
|
});
|
|
3531
3857
|
// NN42: cargo's messages name the crate, not the target. A crate that failed in an invocation naming several targets runs each of its
|
|
3532
3858
|
// targets alone, so the verdict names the target that fails and the others pass on their own.
|
|
3533
|
-
const multi = new Set(idx.map((i) =>
|
|
3534
|
-
if (multi && !signal?.aborted) {
|
|
3859
|
+
const multi = new Set(idx.map((i) => targetAt(i)).filter(Boolean)).size > 1;
|
|
3860
|
+
if (multi && !signal?.aborted && !classBCacheDecision) {
|
|
3535
3861
|
const redo = idx.filter((i) => slots[i]?.status === "fail");
|
|
3536
3862
|
await Promise.all(redo.map(async (i) => { const alone = await runOne(bScans[i], extraEnv).catch((error) => failedRow(i, error)); slots[i] = { ...alone, batchFailure: { id: bs.id, units: bs.batch.units, command: row.command, detail: "the multi-target invocation failed for this crate; this target ran alone" } }; }));
|
|
3537
3863
|
}
|
|
@@ -3567,7 +3893,138 @@ export async function runScans(plan, options = {}) {
|
|
|
3567
3893
|
running.add(job);
|
|
3568
3894
|
}
|
|
3569
3895
|
};
|
|
3570
|
-
|
|
3896
|
+
const bPreparedGroups = new Map();
|
|
3897
|
+
if (classBCacheDecision && !classAFailed && !classBBlocked && !signal?.aborted) {
|
|
3898
|
+
await admitClassBCache();
|
|
3899
|
+
}
|
|
3900
|
+
async function admitClassBCache() {
|
|
3901
|
+
const decision = classBCacheDecision;
|
|
3902
|
+
const staged = [];
|
|
3903
|
+
const stage = async (scan, members) => {
|
|
3904
|
+
const item = { decision, members, owned: { cargoReadTarget: null }, timing: { invocationId: crypto.randomUUID(), elapsedMs: null, cacheLookupMs: null, executionMs: null }, started: performance.now(), observed: new Map() };
|
|
3905
|
+
const prepared = scan.quiet === true ? { ...scan, timeoutMs: Math.min(scanTimeoutMs(scan, options), QUIET_SCAN_MAX_MS) } : scan;
|
|
3906
|
+
item.scan = scanRowIn(prepared, null, item.owned, item.timing, item);
|
|
3907
|
+
item.invocationScan = scan;
|
|
3908
|
+
item.featureProof = featureProofOf.get(members.join(","));
|
|
3909
|
+
const first = await item.scan.next();
|
|
3910
|
+
item.fingerprint = first.done ? classAFingerprint(scan, null, null, null, first.value.detail ?? "row not available") : first.value;
|
|
3911
|
+
item.done = first.done;
|
|
3912
|
+
if (first.done) item.actual = { id: scan.id, actual: "blocked", reason: first.value.detail ?? "row not available" };
|
|
3913
|
+
staged.push(item);
|
|
3914
|
+
return item;
|
|
3915
|
+
};
|
|
3916
|
+
const lookup = async (item) => {
|
|
3917
|
+
if (!item.done) {
|
|
3918
|
+
const next = await item.scan.next();
|
|
3919
|
+
item.actual = next.done ? { id: item.fingerprint.id, actual: "blocked", reason: next.value.detail ?? "lookup did not complete" } : next.value;
|
|
3920
|
+
}
|
|
3921
|
+
};
|
|
3922
|
+
const selected = [];
|
|
3923
|
+
let memberPredictions = new Map();
|
|
3924
|
+
try {
|
|
3925
|
+
const singles = await Promise.all(bScans.map((scan, i) => stage(scan, [i])));
|
|
3926
|
+
decision.memberFingerprints = Object.freeze(singles.map((item) => Object.freeze({ ...item.fingerprint, invocationId: item.fingerprint.id })));
|
|
3927
|
+
const supplied = await options.classBCacheForecast(decision.memberFingerprints, { phase: "members" });
|
|
3928
|
+
if (!Array.isArray(supplied)) throw new TypeError("expected an array of member forecasts");
|
|
3929
|
+
const predicted = new Map();
|
|
3930
|
+
for (const row of supplied) {
|
|
3931
|
+
if (typeof row?.id !== "string" || !["hit", "run", "uncacheable"].includes(row.expected) || (row.status !== undefined && !["pass", "fail"].includes(row.status)) || predicted.has(row.id)) throw new Error("invalid or duplicate member forecast: " + row?.id);
|
|
3932
|
+
predicted.set(row.id, Object.freeze({ ...row }));
|
|
3933
|
+
}
|
|
3934
|
+
if (predicted.size !== singles.length || singles.some((item) => !predicted.has(item.fingerprint.id))) throw new Error("member forecast differs from complete selected row set");
|
|
3935
|
+
decision.memberForecast = Object.freeze([...predicted.values()]);
|
|
3936
|
+
for (const item of singles) {
|
|
3937
|
+
const source = predicted.get(item.fingerprint.id).source;
|
|
3938
|
+
if (!source) continue;
|
|
3939
|
+
if (source.memberKey !== item.fingerprint.key || !source.scan?.batch?.members?.includes(item.fingerprint.id) || !/^[0-9a-f]{64}$/.test(source.key ?? "") || !/^[0-9a-f]{64}$/.test(source.rowDigest ?? "")) throw new Error(item.fingerprint.id + ": invalid retained invocation source");
|
|
3940
|
+
item.source = source;
|
|
3941
|
+
item.fingerprint = Object.freeze({ ...item.fingerprint, key: source.key, failureKey: null, invocationId: source.scan.id, coveredBy: source.scan.id, memberFingerprint: item.fingerprint });
|
|
3942
|
+
}
|
|
3943
|
+
// Independent history chooses expected grouping before any scan outcome is looked up.
|
|
3944
|
+
memberPredictions = predicted;
|
|
3945
|
+
const seen = new Set();
|
|
3946
|
+
for (let i = 0; i < bScans.length; i++) {
|
|
3947
|
+
const group = groupOf.get(i);
|
|
3948
|
+
if (!group) { selected.push(singles[i]); continue; }
|
|
3949
|
+
if (seen.has(group)) continue;
|
|
3950
|
+
seen.add(group);
|
|
3951
|
+
const hits = group.members.filter((n) => predicted.get(bScans[n].id).expected === "hit");
|
|
3952
|
+
const missing = group.members.filter((n) => predicted.get(bScans[n].id).expected !== "hit");
|
|
3953
|
+
selected.push(...hits.map((n) => singles[n]));
|
|
3954
|
+
const parts = missing.length > 1 ? await featurePartition(missing) : missing.length ? [missing] : [];
|
|
3955
|
+
for (const part of parts) {
|
|
3956
|
+
const item = part.length === 1 ? singles[part[0]] : await stage(batchScanOf(part), part);
|
|
3957
|
+
selected.push(item);
|
|
3958
|
+
}
|
|
3959
|
+
const prepared = { hits, parts };
|
|
3960
|
+
for (const n of group.members) bPreparedGroups.set(n, prepared);
|
|
3961
|
+
}
|
|
3962
|
+
} catch (error) {
|
|
3963
|
+
decision.mismatches.push({ id: "class-b", expected: null, actual: "blocked", reason: String(error?.message ?? error) });
|
|
3964
|
+
}
|
|
3965
|
+
const memberById = new Map(decision.memberFingerprints?.map((row) => [row.id, row]));
|
|
3966
|
+
const logical = selected.flatMap((item) => item.members.map((i) => ({ item, fingerprint: Object.freeze({ ...item.fingerprint, id: bScans[i].id, invocationId: item.source?.scan.id ?? item.fingerprint.id, memberFingerprint: memberById.get(bScans[i].id), ...(item.members.length > 1 ? { coveredBy: item.fingerprint.id } : {}) }) })));
|
|
3967
|
+
decision.fingerprints = Object.freeze(logical.map(({ fingerprint }) => fingerprint));
|
|
3968
|
+
const forecasts = new Map();
|
|
3969
|
+
const mismatch = (id, expected, actual, reason, more = {}) => decision.mismatches.push({ id, expected, actual, reason, ...more });
|
|
3970
|
+
try {
|
|
3971
|
+
const supplied = await options.classBCacheForecast(decision.fingerprints, { phase: "invocations" });
|
|
3972
|
+
if (!Array.isArray(supplied)) throw new TypeError("expected an array of row forecasts");
|
|
3973
|
+
for (const entry of supplied) {
|
|
3974
|
+
if (typeof entry?.id !== "string" || !["hit", "run", "uncacheable"].includes(entry.expected) || (entry.status !== undefined && !["pass", "fail"].includes(entry.status))) mismatch(entry?.id ?? "class-b", null, null, "invalid forecast row");
|
|
3975
|
+
else if (forecasts.has(entry.id)) mismatch(entry.id, entry.expected, null, "duplicate forecast row");
|
|
3976
|
+
else forecasts.set(entry.id, Object.freeze({ ...entry }));
|
|
3977
|
+
}
|
|
3978
|
+
} catch (error) { mismatch("class-b", null, null, String(error?.message ?? error)); }
|
|
3979
|
+
decision.forecast = Object.freeze([...forecasts.values()]);
|
|
3980
|
+
// Both independent predictions are frozen before any outcome lookup.
|
|
3981
|
+
await Promise.all(staged.map(lookup));
|
|
3982
|
+
const singles = staged.filter((item) => item.members.length === 1 && !item.fingerprint.id.includes(":batch:"));
|
|
3983
|
+
decision.memberActual = singles.map((item) => ({ ...item.actual }));
|
|
3984
|
+
for (const item of singles) {
|
|
3985
|
+
const expected = memberPredictions.get(item.fingerprint.id);
|
|
3986
|
+
if (!expected) continue;
|
|
3987
|
+
const issue = classACacheMismatch(expected, item.actual, item.fingerprint);
|
|
3988
|
+
if (issue) decision.mismatches.push({ ...issue, phase: "members" });
|
|
3989
|
+
}
|
|
3990
|
+
const ids = new Set();
|
|
3991
|
+
for (const { item, fingerprint } of logical) {
|
|
3992
|
+
const { id, problem } = fingerprint;
|
|
3993
|
+
if (ids.has(id)) mismatch(id, forecasts.get(id)?.expected, null, "duplicate planned row");
|
|
3994
|
+
ids.add(id);
|
|
3995
|
+
if (problem) mismatch(id, forecasts.get(id)?.expected, "blocked", problem);
|
|
3996
|
+
const actual = { ...item.actual, id, invocationId: fingerprint.invocationId };
|
|
3997
|
+
decision.actual.push(actual);
|
|
3998
|
+
if (!forecasts.has(id)) mismatch(id, null, actual.actual, "missing forecast row");
|
|
3999
|
+
else {
|
|
4000
|
+
const expected = forecasts.get(id);
|
|
4001
|
+
const issue = classACacheMismatch(expected, actual, fingerprint); if (issue) decision.mismatches.push(issue);
|
|
4002
|
+
for (const field of ["invocationId", "coveredBy"]) if (Object.hasOwn(expected, field) && expected[field] !== fingerprint[field]) mismatch(id, expected[field], fingerprint[field], `${field} differs from forecast`);
|
|
4003
|
+
}
|
|
4004
|
+
}
|
|
4005
|
+
for (const entry of decision.forecast) if (!ids.has(entry.id)) mismatch(entry.id, entry.expected, null, "unexpected forecast row");
|
|
4006
|
+
// Include member lookups that determined grouping: a late hit/miss there changes workload too.
|
|
4007
|
+
if (!decision.mismatches.length) for (const item of staged) for (const [key, observed] of item.observed) {
|
|
4008
|
+
const current = cacheReadOutcome(key);
|
|
4009
|
+
if (cacheEntryIdentity(current.entry) !== observed.identity || current.issue !== observed.issue) mismatch(item.fingerprint.id, null, "blocked", "cache entry changed between lookup and dispatch", { key, storeIssue: current.issue });
|
|
4010
|
+
}
|
|
4011
|
+
if (!decision.mismatches.length) for (const [command, binding] of admissionToolFiles) {
|
|
4012
|
+
try { if (commandStat(command) !== binding.stat) mismatch("class-b", null, "blocked", `${command} changed between fingerprint and dispatch`); }
|
|
4013
|
+
catch (error) { mismatch("class-b", null, "blocked", String(error?.message ?? error)); }
|
|
4014
|
+
}
|
|
4015
|
+
if (!decision.mismatches.length) for (const item of staged) for (const identity of item.toolIdentities ?? []) {
|
|
4016
|
+
const changed = trustedScanToolProblem(identity, { ops: options.toolOps });
|
|
4017
|
+
if (changed) mismatch(item.fingerprint.id, null, "blocked", changed.detail);
|
|
4018
|
+
}
|
|
4019
|
+
if (!decision.mismatches.length) for (const item of staged) if (item.receiptProof && !retainedReceiptValid(item.receiptProof)) mismatch(item.fingerprint.id, "hit", "blocked", "retained invocation receipt changed between lookup and dispatch");
|
|
4020
|
+
for (const item of staged) {
|
|
4021
|
+
if (!decision.mismatches.length && selected.includes(item)) admittedB.set(item.fingerprint.id, item);
|
|
4022
|
+
else await item.scan.return();
|
|
4023
|
+
}
|
|
4024
|
+
}
|
|
4025
|
+
if (classBCacheDecision?.mismatches.length) {
|
|
4026
|
+
bScans.forEach((scan, i) => { slots[i] = { id: scan.id, class: scan.class, command: scan.command, status: "not-run", code: "CLASS_B_CACHE_DISAGREEMENT", detail: "Class B cache admission refused before dispatch" }; });
|
|
4027
|
+
} else if (brokerHost) {
|
|
3571
4028
|
await scheduleBrokerHostClassB({
|
|
3572
4029
|
scans: bScans, lanes, localJobs: bJobs, carried: (scan) => isBrokerScheduledScan(scan, carriedCtx), pipeline: options.classBPipeline ?? 1,
|
|
3573
4030
|
run: async (i) => { try { slots[i] = await runB(i); } catch (error) { slots[i] = failedRow(i, error); } },
|
|
@@ -3580,7 +4037,7 @@ export async function runScans(plan, options = {}) {
|
|
|
3580
4037
|
if (lanes.quiet.length) {
|
|
3581
4038
|
// One lease per quiet suite, as in class A above.
|
|
3582
4039
|
for (const i of lanes.quiet) {
|
|
3583
|
-
if (classAFailed || classBBlocked || signal?.aborted) {
|
|
4040
|
+
if (classAFailed || classBBlocked || classBCacheDecision?.mismatches.length || signal?.aborted) {
|
|
3584
4041
|
slots[i] = { id: bScans[i].id, class: bScans[i].class, command: bScans[i].command, tool: bScans[i].tool ?? null, toolVersion: null, status: "not-run", detail: signal?.aborted ? "cancelled" : classAFailed ? "class A is red; nothing in class B starts" : "class B is blocked" };
|
|
3585
4042
|
continue;
|
|
3586
4043
|
}
|
|
@@ -3596,6 +4053,7 @@ export async function runScans(plan, options = {}) {
|
|
|
3596
4053
|
}
|
|
3597
4054
|
}
|
|
3598
4055
|
results.push(...slots);
|
|
4056
|
+
if (classBCacheDecision) await Promise.all([...admittedB.values()].map((item) => item.scan.return()));
|
|
3599
4057
|
}
|
|
3600
4058
|
|
|
3601
4059
|
// The pinned advisory database, materialised once per run on first use (a failure is remembered and refuses every advisory scan).
|
|
@@ -3622,20 +4080,210 @@ export async function runScans(plan, options = {}) {
|
|
|
3622
4080
|
}
|
|
3623
4081
|
|
|
3624
4082
|
// `extraEnv` (the quiet lease id) reaches the child but never the cache key: a lease changes nothing a scan proves.
|
|
4083
|
+
function classAFingerprint(s, key, failureKey, keyParts, problem, uncacheableReason = null) {
|
|
4084
|
+
let featureContext = null;
|
|
4085
|
+
const retainedSourceEligible = !s.coverageKey && !s.provesPublisher && !Array.isArray(s.batchable?.features);
|
|
4086
|
+
if (s.class === SCAN_CLASS.B && s.batchable && retainedSourceEligible && Array.isArray(s.args)) {
|
|
4087
|
+
const cwd = s.cwd ?? ".";
|
|
4088
|
+
if (!featureContextInputs.has(cwd)) featureContextInputs.set(cwd, workspaceManifestDigest(path.join(contentRoot, cwd)));
|
|
4089
|
+
const prefix = s.args[0] === "cargo" ? 1 : 0;
|
|
4090
|
+
const { rest } = stripSelectors(s.args.slice(prefix));
|
|
4091
|
+
featureContext = { cwd, inputs: featureContextInputs.get(cwd), toolVersion: toolVersions[s.tool] ?? null, selection: treeArgs({ rest, packages: [s.batchable.crate], target: s.batchable.target ?? null }) };
|
|
4092
|
+
}
|
|
4093
|
+
return Object.freeze({ id: s.id, key, failureKey, inputs: keyParts?.raw.inputs ?? null, toolVersion: keyParts?.raw.toolVersion ?? null, environment: keyParts?.env ?? null, retainedSourceEligible, featureContext, ...(problem ? { problem } : {}), ...(uncacheableReason ? { uncacheableReason } : {}) });
|
|
4094
|
+
}
|
|
4095
|
+
function cacheEntryIdentity(entry) { return entry === null || entry === undefined ? null : sha256(canonicalJson(entry)); }
|
|
4096
|
+
function retainedReceiptValid(evidence) {
|
|
4097
|
+
if (typeof evidence?.receiptPath !== "string" || !path.isAbsolute(evidence.receiptPath) || typeof evidence.requestId !== "string" || !/^[0-9a-f]{64}$/.test(evidence.receiptSha256 ?? "")) return false;
|
|
4098
|
+
try {
|
|
4099
|
+
const bytes = fs.readFileSync(evidence.receiptPath);
|
|
4100
|
+
if (sha256(bytes) !== evidence.receiptSha256) return false;
|
|
4101
|
+
const receipt = JSON.parse(bytes.toString("utf8"));
|
|
4102
|
+
return receipt?.id === evidence.requestId && receipt.provenance?.payload?.jobId === evidence.requestId && Boolean(receipt.provenance.signature);
|
|
4103
|
+
} catch { return false; }
|
|
4104
|
+
}
|
|
4105
|
+
/** The key of a stored "these targets resolve alike for these crates" finding (targetClassesOf). */
|
|
4106
|
+
function targetsProofKey(context) { return sha256(canonicalJson({ schema: "rightkit.feature-partition-targets/1", rest: context.rest, crates: context.crates, targets: context.targets, cwd: context.cwd, inputs: context.inputs, toolVersion: context.toolVersion })); }
|
|
4107
|
+
/** Whether a targets proof is about this member: same workspace state and cargo, its crate, its own target, its own selection. */
|
|
4108
|
+
function targetProofCovers(proof, context, crate) {
|
|
4109
|
+
const c = proof?.context;
|
|
4110
|
+
if (!context || c?.kind !== "targets" || c.cwd !== context.cwd || c.inputs !== context.inputs || c.toolVersion !== context.toolVersion || !c.crates?.includes(crate)) return false;
|
|
4111
|
+
const at = Array.isArray(context.selection) ? context.selection.indexOf("--target") : -1;
|
|
4112
|
+
const target = at >= 0 ? context.selection[at + 1] : null;
|
|
4113
|
+
if (typeof target !== "string" || !c.targets?.includes(target)) return false;
|
|
4114
|
+
try { return canonicalJson(treeArgs({ rest: c.rest, packages: [crate], target })) === canonicalJson(context.selection); } catch { return false; }
|
|
4115
|
+
}
|
|
4116
|
+
function featureProofCovers(proof, context, crate) {
|
|
4117
|
+
if (proof?.context?.kind === "targets") return false; // judged by targetProofCovers
|
|
4118
|
+
if (!context || !proof?.context || proof.context.cwd !== context.cwd || proof.context.inputs !== context.inputs || proof.context.toolVersion !== context.toolVersion || !proof.context.crates?.includes(crate)) return false;
|
|
4119
|
+
try { return canonicalJson(treeArgs({ rest: proof.context.rest, packages: [crate], target: proof.context.target })) === canonicalJson(context.selection); } catch { return false; }
|
|
4120
|
+
}
|
|
4121
|
+
function cacheReadOutcome(key) { return cache.readOutcome?.(key) ?? { entry: cache.read(key), issue: null }; }
|
|
4122
|
+
function readRowCache(key, admission) {
|
|
4123
|
+
if (!key) return null;
|
|
4124
|
+
if (!admission) return cache.read(key);
|
|
4125
|
+
const { entry, issue } = cacheReadOutcome(key);
|
|
4126
|
+
admission.observed.set(key, { identity: cacheEntryIdentity(entry), issue });
|
|
4127
|
+
return entry;
|
|
4128
|
+
}
|
|
4129
|
+
function classAObservation(s, key, failureKey, cached, admission, hadEntry = false) {
|
|
4130
|
+
if (cached) return { id: s.id, actual: "hit", status: cached.status, key: cached.failureCached ? failureKey : key };
|
|
4131
|
+
if (!key) return { id: s.id, actual: "uncacheable" };
|
|
4132
|
+
const issues = [...admission.observed.values()].map((seen) => seen.issue).filter((issue) => issue && !issue.startsWith("expected entry absent"));
|
|
4133
|
+
return { id: s.id, actual: "run", key, reason: issues[0] ?? (hadEntry ? "entry failed validation" : "expected entry absent; removal cause unknown") };
|
|
4134
|
+
}
|
|
4135
|
+
function storeScanOutcome(key, row, admission) {
|
|
4136
|
+
cache.write(key, row);
|
|
4137
|
+
if (admission) {
|
|
4138
|
+
const stored = cache.read(key);
|
|
4139
|
+
admission.stored = stored?.key === key && cacheEntryIdentity(stored.row) === cacheEntryIdentity(JSON.parse(JSON.stringify(row)));
|
|
4140
|
+
if (!admission.stored) {
|
|
4141
|
+
if (!admission.decision) classAFailed = true;
|
|
4142
|
+
(admission.decision ?? classACacheDecision).mismatches.push({ id: row.id, key, expected: "retained", actual: "unavailable", reason: "reusable outcome could not be verified after writing the cache entry" });
|
|
4143
|
+
}
|
|
4144
|
+
}
|
|
4145
|
+
}
|
|
4146
|
+
function markScanDispatch(s, row, admission) {
|
|
4147
|
+
if (!admission) return;
|
|
4148
|
+
const decision = admission.decision ?? classACacheDecision;
|
|
4149
|
+
decision.dispatchedRows.push(...(admission.members ? admission.members.map((i) => bScans[i].id) : [s.id]));
|
|
4150
|
+
row.dispatched = true;
|
|
4151
|
+
}
|
|
4152
|
+
async function admitClassACache() {
|
|
4153
|
+
const decision = classACacheDecision;
|
|
4154
|
+
const stage = await Promise.all(aScans.map(async (s) => {
|
|
4155
|
+
const admission = { owned: { cargoReadTarget: null }, timing: { invocationId: crypto.randomUUID(), elapsedMs: null, cacheLookupMs: null, executionMs: null }, started: performance.now(), observed: new Map() };
|
|
4156
|
+
const scan = s.kind === "test" && s.quiet === true ? { ...s, timeoutMs: Math.min(scanTimeoutMs(s, options), QUIET_SCAN_MAX_MS) } : s;
|
|
4157
|
+
admission.scan = scanRowIn(scan, null, admission.owned, admission.timing, admission);
|
|
4158
|
+
const first = await admission.scan.next();
|
|
4159
|
+
admission.fingerprint = first.done ? classAFingerprint(s, null, null, null, first.value.detail ?? "row not available") : first.value;
|
|
4160
|
+
return admission;
|
|
4161
|
+
}));
|
|
4162
|
+
decision.fingerprints = Object.freeze(stage.map((item) => item.fingerprint));
|
|
4163
|
+
const mismatch = (id, expected, actual, reason, details = {}) => decision.mismatches.push({ id, expected, actual, reason, ...details });
|
|
4164
|
+
const forecasts = new Map();
|
|
4165
|
+
try {
|
|
4166
|
+
const supplied = await options.classACacheForecast(decision.fingerprints);
|
|
4167
|
+
if (!Array.isArray(supplied)) throw new TypeError("expected an array of row forecasts");
|
|
4168
|
+
for (const entry of supplied) {
|
|
4169
|
+
if (typeof entry?.id !== "string" || !["hit", "run", "uncacheable"].includes(entry.expected) || (entry.status !== undefined && !["pass", "fail"].includes(entry.status))) {
|
|
4170
|
+
mismatch(entry?.id ?? "class-a", null, null, "invalid forecast row");
|
|
4171
|
+
} else if (forecasts.has(entry.id)) {
|
|
4172
|
+
mismatch(entry.id, entry.expected, null, "duplicate forecast row");
|
|
4173
|
+
} else forecasts.set(entry.id, Object.freeze({ ...entry }));
|
|
4174
|
+
}
|
|
4175
|
+
} catch (error) { mismatch("class-a", null, null, String(error?.message ?? error)); }
|
|
4176
|
+
decision.forecast = Object.freeze([...forecasts.values()]);
|
|
4177
|
+
if (!stage.length) mismatch("class-a", null, null, "Class A stage selected no scan rows");
|
|
4178
|
+
const identities = new Set();
|
|
4179
|
+
for (const item of stage) {
|
|
4180
|
+
const { id, problem } = item.fingerprint;
|
|
4181
|
+
if (identities.has(id)) mismatch(id, forecasts.get(id)?.expected, null, "duplicate planned row");
|
|
4182
|
+
identities.add(id);
|
|
4183
|
+
if (!forecasts.has(id)) mismatch(id, null, null, "missing forecast row");
|
|
4184
|
+
if (problem) mismatch(id, forecasts.get(id)?.expected, "blocked", problem);
|
|
4185
|
+
}
|
|
4186
|
+
for (const entry of decision.forecast) if (!identities.has(entry.id)) mismatch(entry.id, entry.expected, null, "unexpected forecast row");
|
|
4187
|
+
if (!decision.mismatches.length) {
|
|
4188
|
+
for (const item of stage) {
|
|
4189
|
+
const { id } = item.fingerprint;
|
|
4190
|
+
const lookup = await item.scan.next();
|
|
4191
|
+
const actual = lookup.done ? { id, actual: "blocked", reason: lookup.value.detail ?? "lookup did not complete" } : lookup.value;
|
|
4192
|
+
item.isHit = actual.actual === "hit";
|
|
4193
|
+
decision.actual.push(actual);
|
|
4194
|
+
const disagreement = classACacheMismatch(forecasts.get(id), actual, item.fingerprint);
|
|
4195
|
+
if (disagreement) decision.mismatches.push(disagreement);
|
|
4196
|
+
}
|
|
4197
|
+
// Recheck the scan records as a single stage before releasing any row. The admitted
|
|
4198
|
+
// results are held in memory, and execution never turns a disappearing hit into a run.
|
|
4199
|
+
if (!decision.mismatches.length) for (const item of stage) {
|
|
4200
|
+
const { id } = item.fingerprint;
|
|
4201
|
+
for (const [key, observed] of item.observed) {
|
|
4202
|
+
const current = cacheReadOutcome(key);
|
|
4203
|
+
if (cacheEntryIdentity(current.entry) !== observed.identity || current.issue !== observed.issue) mismatch(id, forecasts.get(id).expected, "blocked", "cache entry changed between lookup and dispatch", { key, storeIssue: current.issue });
|
|
4204
|
+
}
|
|
4205
|
+
}
|
|
4206
|
+
if (!decision.mismatches.length) {
|
|
4207
|
+
const changes = new Map();
|
|
4208
|
+
for (const [command, binding] of admissionToolFiles) {
|
|
4209
|
+
try { if (commandStat(command) !== binding.stat) changes.set(command, `${command} changed between fingerprint and dispatch`); }
|
|
4210
|
+
catch (error) { changes.set(command, String(error?.message ?? error)); }
|
|
4211
|
+
}
|
|
4212
|
+
for (const trust of admissionTrusts.values()) {
|
|
4213
|
+
if (!trust.ok) continue;
|
|
4214
|
+
const changed = trustedScanToolProblem(trust.identity, { ops: options.toolOps });
|
|
4215
|
+
if (changed) changes.set(trust.identity.path, changed.detail);
|
|
4216
|
+
}
|
|
4217
|
+
if (pnpmIdentity) {
|
|
4218
|
+
try { if (currentPnpmIdentity().digest !== pnpmIdentity.digest) changes.set("pnpm", "pnpm changed between fingerprint and dispatch"); }
|
|
4219
|
+
catch (error) { changes.set("pnpm", String(error?.message ?? error)); }
|
|
4220
|
+
}
|
|
4221
|
+
for (const item of stage) for (const command of item.toolCommands ?? []) {
|
|
4222
|
+
if (changes.has(command)) mismatch(item.fingerprint.id, forecasts.get(item.fingerprint.id).expected, "blocked", changes.get(command));
|
|
4223
|
+
}
|
|
4224
|
+
}
|
|
4225
|
+
}
|
|
4226
|
+
if (decision.mismatches.length) {
|
|
4227
|
+
await Promise.all(stage.map((item) => item.scan.return()));
|
|
4228
|
+
return;
|
|
4229
|
+
}
|
|
4230
|
+
for (const item of stage) admittedA.set(item.fingerprint.id, item);
|
|
4231
|
+
}
|
|
3625
4232
|
async function scanRow(s, extraEnv = null) {
|
|
4233
|
+
const admitted = s.class === SCAN_CLASS.A ? admittedA.get(s.id) : admittedB.get(s.id);
|
|
4234
|
+
if (s.class === SCAN_CLASS.B && classBCacheDecision && !admitted && !classAFailed && !classBBlocked && !signal?.aborted) {
|
|
4235
|
+
classBCacheDecision.mismatches.push({ id: s.id, expected: "forecast invocation", actual: "unplanned invocation", reason: "Class B invocation was not admitted before dispatch" });
|
|
4236
|
+
return { id: s.id, class: s.class, command: s.command, status: "not-run", code: "CLASS_B_CACHE_DISAGREEMENT", detail: "Class B invocation was not admitted before dispatch" };
|
|
4237
|
+
}
|
|
4238
|
+
if (admitted) {
|
|
4239
|
+
try {
|
|
4240
|
+
const finished = await admitted.scan.next(extraEnv);
|
|
4241
|
+
const row = finished.value;
|
|
4242
|
+
const { key, failureKey } = admitted.fingerprint;
|
|
4243
|
+
if (row.cached || admitted.stored) {
|
|
4244
|
+
const decision = admitted.decision ?? classACacheDecision;
|
|
4245
|
+
for (const id of admitted.members ? admitted.members.map((i) => bScans[i].id) : [s.id]) {
|
|
4246
|
+
let source = admitted.source;
|
|
4247
|
+
// The feature partition admitted this exact group. Keep its own
|
|
4248
|
+
// stored row & descriptor, with each member's complete solo input
|
|
4249
|
+
// identity as comparison evidence; write no projected cache row.
|
|
4250
|
+
if (!source && admitted.members?.length > 1 && row.status === "pass") {
|
|
4251
|
+
const stored = cache.read(key);
|
|
4252
|
+
const member = decision.memberFingerprints.find((entry) => entry.id === id);
|
|
4253
|
+
const signed = row.seam !== true || retainedReceiptValid(stored?.row?.snapshotEvidence);
|
|
4254
|
+
const equivalence = admitted.featureProof;
|
|
4255
|
+
const memberCrate = bScans.find((scan) => scan.id === id)?.batchable?.crate;
|
|
4256
|
+
// NN42: of the group's proofs, the ones about this member: the crate partition of its own target, and (for a command that named
|
|
4257
|
+
// several targets) the finding that those targets resolve alike. A group of several crates needs the first, of several targets the second.
|
|
4258
|
+
const memberProofs = (equivalence ?? []).filter((proof) => (proof?.context?.kind === "targets" ? targetProofCovers(proof, member?.featureContext, memberCrate) : featureProofCovers(proof, member?.featureContext, memberCrate)));
|
|
4259
|
+
const groupCrates = new Set(admitted.members.map((i) => bScans[i].batchable?.crate)).size;
|
|
4260
|
+
const groupTargets = new Set(admitted.members.map((i) => bScans[i].batchable?.target ?? "")).size;
|
|
4261
|
+
const proven = memberProofs.length > 0 && (groupCrates < 2 || memberProofs.some((proof) => proof.context.kind !== "targets")) && (groupTargets < 2 || memberProofs.some((proof) => proof.context.kind === "targets"));
|
|
4262
|
+
if (!admitted.invocationScan.coverageKey && !admitted.invocationScan.provesPublisher && member?.retainedSourceEligible && member.featureContext && member.key && signed && proven && usableStoredPass(stored, admitted.invocationScan, { cacheKey: key, viaSeam: row.seam === true })) source = { schema: "rightkit.retained-invocation/1", key, rowDigest: cacheEntryIdentity(stored.row), memberKey: member.key, memberCrate, featureContext: member.featureContext, scan: admitted.invocationScan, equivalence: memberProofs };
|
|
4263
|
+
}
|
|
4264
|
+
decision.retained.push({ id, key: row.status === "fail" ? failureKey : key, status: row.status, ...(source ? { source } : {}) });
|
|
4265
|
+
}
|
|
4266
|
+
}
|
|
4267
|
+
const out = { ...row, timing: { ...admitted.timing, elapsedMs: performance.now() - admitted.started } };
|
|
4268
|
+
settle(s.id, out);
|
|
4269
|
+
return out;
|
|
4270
|
+
} finally {
|
|
4271
|
+
if (admitted.owned.cargoReadTarget) fs.rmSync(admitted.owned.cargoReadTarget, { recursive: true, force: true });
|
|
4272
|
+
}
|
|
4273
|
+
}
|
|
3626
4274
|
// One invocation owns one timing, including cache lookup, probes, execution and verification.
|
|
3627
4275
|
const started = performance.now();
|
|
3628
4276
|
const timing = { invocationId: crypto.randomUUID(), elapsedMs: null, cacheLookupMs: null, executionMs: null };
|
|
3629
4277
|
const owned = { cargoReadTarget: null };
|
|
3630
4278
|
try {
|
|
3631
|
-
const row = await scanRowIn(s, extraEnv, owned, timing);
|
|
4279
|
+
const { value: row } = await scanRowIn(s, extraEnv, owned, timing).next();
|
|
3632
4280
|
const out = { ...row, timing: { ...timing, elapsedMs: performance.now() - started } };
|
|
3633
4281
|
// A lookup or probe answer (lookupMiss present) says nothing ran: it settles nothing. A cache hit found by a probe is a real answer and does.
|
|
3634
4282
|
if (out.lookupMiss === undefined) settle(s.id, out);
|
|
3635
4283
|
return out;
|
|
3636
4284
|
} finally { if (owned.cargoReadTarget) fs.rmSync(owned.cargoReadTarget, { recursive: true, force: true }); }
|
|
3637
4285
|
}
|
|
3638
|
-
async function scanRowIn(s, extraEnv, owned, timing) {
|
|
4286
|
+
async function* scanRowIn(s, extraEnv, owned, timing, admission = null) {
|
|
3639
4287
|
const row = { id: s.id, class: s.class, command: s.command, tool: s.tool ?? null, toolVersion: null, status: "fail" };
|
|
3640
4288
|
const scanStartedAt = Date.now();
|
|
3641
4289
|
if (s.class === SCAN_CLASS.B && classBBlocked) {
|
|
@@ -3658,40 +4306,47 @@ export async function runScans(plan, options = {}) {
|
|
|
3658
4306
|
try {
|
|
3659
4307
|
const digest = cache.digest(s, {});
|
|
3660
4308
|
if (digest) {
|
|
3661
|
-
|
|
3662
|
-
internalKey = scanCacheKey({ id: s.id, command: s.command ?? `internal:${s.internal}`, toolVersion:
|
|
3663
|
-
internalIndex = { key: sha256(`rk-row-index/1\0${s.id}`), inputs: sha256(String(digest)), env:
|
|
4309
|
+
const ruleIdentity = `${INTERNAL_RULES_SCHEMA}:${CHECKER_IDENTITY}`;
|
|
4310
|
+
internalKey = scanCacheKey({ id: s.id, command: s.command ?? `internal:${s.internal}`, toolVersion: ruleIdentity, env: {}, inheritedEnv: inheritedEnvDigest({}), digest });
|
|
4311
|
+
internalIndex = { key: sha256(`rk-row-index/1\0${s.id}`), inputs: sha256(String(digest)), env: ruleIdentity, raw: { inputs: String(digest), toolVersion: ruleIdentity, env: {}, inherited: null } };
|
|
3664
4312
|
// NN41: a file-only rule's violation list is a function of the same inputs, so it is keyed like its pass plus the rule code (CHECKER_IDENTITY);
|
|
3665
4313
|
// a rule whose answer depends on the day or a remote service (FAILURE_UNCACHEABLE_INTERNAL) never has its failure reused.
|
|
3666
|
-
if (!FAILURE_UNCACHEABLE_INTERNAL.has(s.internal)) internalFailKey = scanCacheKey({ id: s.id, command: `${s.command ?? `internal:${s.internal}`} ;; ${FAILURE_KEY_SCHEMA}`, toolVersion:
|
|
4314
|
+
if (!FAILURE_UNCACHEABLE_INTERNAL.has(s.internal)) internalFailKey = scanCacheKey({ id: s.id, command: `${s.command ?? `internal:${s.internal}`} ;; ${FAILURE_KEY_SCHEMA}`, toolVersion: ruleIdentity, env: {}, inheritedEnv: inheritedEnvDigest({}), digest });
|
|
3667
4315
|
}
|
|
3668
4316
|
} catch (error) { internalKey = null; internalFailKey = null; row.cacheKeyError = String(error?.message ?? error).slice(0, 300); }
|
|
3669
|
-
|
|
3670
|
-
|
|
3671
|
-
if (
|
|
3672
|
-
|
|
3673
|
-
|
|
3674
|
-
|
|
3675
|
-
const failHit = internalFailKey ? cache.read(internalFailKey) : null;
|
|
3676
|
-
if (failHit && failHit.key === internalFailKey && failHit.row?.status === "fail" && failHit.row.id === s.id && typeof failHit.row.detail === "string" && failHit.row.detail !== "") {
|
|
3677
|
-
cacheHits.push(s.id);
|
|
3678
|
-
if (s.class === SCAN_CLASS.A) classAFailed = true;
|
|
3679
|
-
return { ...row, status: "fail", cached: true, failureCached: true, detail: failHit.row.detail };
|
|
4317
|
+
}
|
|
4318
|
+
if (s.internal) {
|
|
4319
|
+
if (admission) {
|
|
4320
|
+
const uncacheableReason = !internalKey ? cache?.uncacheableReason?.(s) ?? (!CACHEABLE_INTERNAL.has(s.internal) ? "internal rule is not eligible for reuse" : null) : null;
|
|
4321
|
+
const problem = row.cacheKeyError ?? (!internalKey && !uncacheableReason ? "internal rule input or identity unavailable" : null);
|
|
4322
|
+
yield classAFingerprint(s, internalKey, internalFailKey, internalIndex, problem, uncacheableReason);
|
|
3680
4323
|
}
|
|
4324
|
+
const hit = readRowCache(internalKey, admission);
|
|
4325
|
+
if (internalIndex && !admission) { const idx = cache.read(internalIndex.key)?.row ?? null; row.cacheMiss = { kind: !idx ? "new" : idx.inputs === internalIndex.inputs && idx.env === internalIndex.env ? "unchanged" : "changed", ...(idx ? { last: idx.at ?? null } : {}), ...(idx?.raw ? { why: explainKeyChange(idx.raw, internalIndex.raw) } : {}), now: { inputs: internalIndex.raw.inputs.slice(0, 4000) } }; }
|
|
4326
|
+
const command = s.command ?? `internal:${s.internal}`;
|
|
4327
|
+
const passHit = hit?.key === internalKey && hit.row?.status === "pass" && hit.row.id === s.id && hit.row.command === command;
|
|
4328
|
+
const failHit = passHit ? null : readRowCache(internalFailKey, admission);
|
|
4329
|
+
let cached = null;
|
|
4330
|
+
if (passHit) cached = { ...row, status: "pass", cached: true, detail: `cached ${String(hit.at ?? "").slice(0, 10) || "earlier"}` };
|
|
4331
|
+
else if (failHit?.key === internalFailKey && failHit.row?.status === "fail" && failHit.row.id === s.id && failHit.row.command === command && typeof failHit.row.detail === "string" && failHit.row.detail !== "") cached = { ...row, status: "fail", cached: true, failureCached: true, detail: failHit.row.detail };
|
|
4332
|
+
if (admission) extraEnv = yield classAObservation(s, internalKey, internalFailKey, cached, admission, Boolean(hit || failHit));
|
|
4333
|
+
if (cached) { cacheHits.push(s.id); return cached; }
|
|
3681
4334
|
}
|
|
3682
4335
|
if (options.cacheLookupOnly && s.internal) return { ...row, status: "not-run", lookupMiss: Boolean(internalKey), detail: internalKey ? "would miss the cache" : "has no cache key" };
|
|
3683
4336
|
if (s.internal) {
|
|
4337
|
+
markScanDispatch(s, row, admission);
|
|
3684
4338
|
const out = await INTERNAL[s.internal](s, ctx);
|
|
3685
4339
|
if (out && out.missing) { status = "fail"; code = "TOOL_MISSING"; detail = out.missing; }
|
|
3686
4340
|
else if (out && !Array.isArray(out) && out.code) { status = "fail"; code = out.code; detail = out.detail; }
|
|
3687
4341
|
else if (out && !Array.isArray(out) && typeof out.advice === "string") { advice = out.advice; }
|
|
3688
4342
|
else if (out.length) { status = "fail"; detail = out.join("; "); }
|
|
3689
4343
|
if (status === "pass" && internalKey && !advice && !signal?.aborted && internalIndex) cache.write(internalIndex.key, { id: s.id, inputs: internalIndex.inputs, env: internalIndex.env, raw: internalIndex.raw, at: new Date().toISOString() });
|
|
3690
|
-
if (status === "pass" && internalKey && !advice && !signal?.aborted)
|
|
4344
|
+
if (status === "pass" && internalKey && !advice && !signal?.aborted) storeScanOutcome(internalKey, { id: s.id, class: s.class, command: s.command ?? `internal:${s.internal}`, tool: null, toolVersion: CHECKER_IDENTITY, status: "pass" }, admission);
|
|
3691
4345
|
// NN41: only a violation list (the rule ran and named what is wrong) is a deterministic failure; a missing tool or a coded refusal is the environment's.
|
|
3692
|
-
else if (status === "fail" && !code && internalFailKey && Array.isArray(out) && out.length && !signal?.aborted)
|
|
4346
|
+
else if (status === "fail" && !code && internalFailKey && Array.isArray(out) && out.length && !signal?.aborted) storeScanOutcome(internalFailKey, { id: s.id, class: s.class, command: s.command ?? `internal:${s.internal}`, tool: null, toolVersion: CHECKER_IDENTITY, status: "fail", detail }, admission);
|
|
3693
4347
|
} else {
|
|
3694
4348
|
const scanDir = path.join(rootDir(s.root), s.cwd ?? "");
|
|
4349
|
+
const metadata = s.id === "cargo-metadata" || s.id.startsWith("cargo-metadata:");
|
|
3695
4350
|
// The RustRight client's version probe starts in a Cargo workspace of the primary checkout; a class A cargo scan's own directory is
|
|
3696
4351
|
// in the snapshot, so its probe uses the checkout's counterpart (reading no file of it), or the checkout when it has none.
|
|
3697
4352
|
let probeAt = scanDir;
|
|
@@ -3731,8 +4386,15 @@ export async function runScans(plan, options = {}) {
|
|
|
3731
4386
|
const viaSeam = Boolean(deps.gateSeam) && s.class === SCAN_CLASS.B && s.root === "cargoLive" && (s.tool === "rustright" || s.tool === "cargo" || (s.tool === "swift" && carriedScan));
|
|
3732
4387
|
if (viaSeam) row.seam = true;
|
|
3733
4388
|
// NN02: a publisher row (coverageKey) is cached too, with the signed broker receipt and test-run evidence its publisher verify needs.
|
|
4389
|
+
const cacheStarted = performance.now();
|
|
4390
|
+
const observedBinding = admission ? observedCommand(s.tool, p.command) : null;
|
|
4391
|
+
if (observedBinding && s.class === SCAN_CLASS.B) commandIdentity(observedBinding);
|
|
4392
|
+
const observed = s.class === SCAN_CLASS.A ? observedBinding : null;
|
|
4393
|
+
if (admission) {
|
|
4394
|
+
admission.toolCommands = [...identities.map((identity) => identity.path), ...(observedBinding ? [observedBinding] : []), ...(s.tool === "pnpm" ? ["pnpm"] : [])];
|
|
4395
|
+
if (s.class === SCAN_CLASS.B) admission.toolIdentities = identities;
|
|
4396
|
+
}
|
|
3734
4397
|
if (cache) {
|
|
3735
|
-
const cacheStarted = performance.now();
|
|
3736
4398
|
try {
|
|
3737
4399
|
// A plain node --check row has no guard, carrier, advisory or
|
|
3738
4400
|
// trusted-tool environment additions. Include its actual ledger
|
|
@@ -3741,7 +4403,8 @@ export async function runScans(plan, options = {}) {
|
|
|
3741
4403
|
const nodeEnv = { ...deps.env, ...(nodeSentinel ? { CARGO_TARGET_DIR: nodeSentinel, CARGO_BUILD_TARGET_DIR: nodeSentinel } : {}), ...s.env, ...(extraEnv ?? {}), ...(cargoLedger ? { [SCAN_TOKEN_ENV]: scanTokenOf(s.id) } : {}) };
|
|
3742
4404
|
const digest = cache.digest(s, { childEnv: nodeEnv, cwd: scanDir, command: p.command, shimProof: options.nodeCheckShimContext ?? null });
|
|
3743
4405
|
// The analyzers a scan runs through (actionlint's shellcheck) judge it too, so their versions key it as well.
|
|
3744
|
-
const
|
|
4406
|
+
const bytes = p.identity?.sha256 ?? (observed ? commandIdentity(observed) : s.tool === "pnpm" && admission ? pnpmIdentity?.digest : null);
|
|
4407
|
+
const toolVersion = [bytes ? `${p.version}@${bytes}` : p.version, ...depVersions].join(" + ");
|
|
3745
4408
|
// The narrow node-check digest already binds the complete actual
|
|
3746
4409
|
// child environment (with its one explicit ownership exception).
|
|
3747
4410
|
// NN29: a publisher row carries the gate's whole environment, per-run identities included (build ownership handle, carrier map, run markers):
|
|
@@ -3757,10 +4420,44 @@ export async function runScans(plan, options = {}) {
|
|
|
3757
4420
|
// NN41: a deterministic compile failure is keyed like the pass plus the tool version (the client's, its identity digest), the installed broker runtime
|
|
3758
4421
|
// identity (options.failureIdentity: version, clientDigest, brokerDigest) and the failure namespace; the digest already binds the unit closure, lock entries and toolchain files.
|
|
3759
4422
|
// No identity from the caller means no failure is ever stored or reused.
|
|
3760
|
-
|
|
4423
|
+
// A Rust test row on a broker host compiles through the broker (--no-run) and runs its executables outside it (runOutside, GC-A08); a batched
|
|
4424
|
+
// group (test:batch:) only ever forms from such rows. Its COMPILE failure is as deterministic as a clippy row's: the store condition below
|
|
4425
|
+
// requires cargo's "could not compile" in the compile's own output, which a compile that succeeded and then had a failing test never carries
|
|
4426
|
+
// (NN41, astra62 review 2026-11-18: excluding runOutside left every test row and group on the Dell unstorable).
|
|
4427
|
+
if (typeof options.failureIdentity === "string" && options.failureIdentity !== "" && (isFailureCacheableCompileId(s.id) || isRustTestRowId(s.id)) && (!s.runOutside || isRustTestRowId(s.id)) && !s.publisherRustTest && (s.tool === "rustright" || s.tool === "cargo")) failKey = scanCacheKey({ id: s.id, command: `${keyCommand({ command: s.command })} ;; ${FAILURE_KEY_SCHEMA}`, toolVersion: `${toolVersion} ;; broker-runtime ${options.failureIdentity}`, env: s.env ?? {}, inheritedEnv: inherited, digest });
|
|
3761
4428
|
}
|
|
3762
4429
|
} catch (error) { cacheKey = null; row.cacheKeyError = String(error?.message ?? error).slice(0, 300); }
|
|
3763
|
-
|
|
4430
|
+
}
|
|
4431
|
+
if (admission) {
|
|
4432
|
+
const uncacheableReason = !cacheKey ? cache?.uncacheableReason?.(s) ?? (metadata && s.cargoWorkspaceUncacheable === true ? "Cargo discovery inputs cannot be fully bound" : /^build-helpers(:|$)/.test(s.id) ? "host trace inputs cannot be bound" : null) : null;
|
|
4433
|
+
const problem = row.cacheKeyError ?? (!cacheKey && !uncacheableReason ? "required scan cache input or identity unavailable" : null);
|
|
4434
|
+
yield classAFingerprint(s, cacheKey, failKey, keyParts, problem, uncacheableReason);
|
|
4435
|
+
}
|
|
4436
|
+
if (admission?.source) {
|
|
4437
|
+
// A historical invocation is retained under its original identity.
|
|
4438
|
+
// Missing/changed evidence is a refused expected hit, never work.
|
|
4439
|
+
const source = admission.source;
|
|
4440
|
+
const hit = readRowCache(source.key, admission);
|
|
4441
|
+
const equivalent = Array.isArray(source.equivalence) && source.equivalence.length > 0 && source.equivalence.every((proof) => {
|
|
4442
|
+
const entry = readRowCache(proof.key, admission);
|
|
4443
|
+
if (proof?.context?.kind === "targets") return targetProofCovers(proof, source.featureContext, source.memberCrate) && targetsProofKey(proof.context) === proof.key && entry?.key === proof.key && entry.row?.id === "feature-partition-targets" && cacheEntryIdentity(entry.row) === proof.rowDigest;
|
|
4444
|
+
return featureProofCovers(proof, source.featureContext, source.memberCrate) && partitionCacheKey(proof.context) === proof.key && entry?.key === proof.key && Array.isArray(entry.row?.partition) && cacheEntryIdentity(entry.row) === proof.rowDigest;
|
|
4445
|
+
});
|
|
4446
|
+
const signed = !viaSeam || retainedReceiptValid(hit?.row?.snapshotEvidence);
|
|
4447
|
+
if (viaSeam && signed) admission.receiptProof = hit.row.snapshotEvidence;
|
|
4448
|
+
const current = admission.fingerprint.memberFingerprint;
|
|
4449
|
+
const compatible = current?.retainedSourceEligible && current.featureContext && s.batchable?.crate === source.memberCrate && canonicalJson(current.featureContext) === canonicalJson(source.featureContext) && !source.scan.coverageKey && !source.scan.provesPublisher;
|
|
4450
|
+
const valid = source.schema === "rightkit.retained-invocation/1" && compatible && equivalent && signed && source.memberKey === cacheKey && cacheEntryIdentity(hit?.row) === source.rowDigest && usableStoredPass(hit, source.scan, { cacheKey: source.key, viaSeam });
|
|
4451
|
+
const observation = valid ? { id: s.id, actual: "hit", status: "pass", key: source.key } : { id: s.id, actual: "run", key: source.key, reason: "retained invocation evidence absent or invalid; removal cause unknown" };
|
|
4452
|
+
yield observation;
|
|
4453
|
+
if (!valid) return { ...row, status: "not-run", code: "CLASS_B_CACHE_DISAGREEMENT", detail: observation.reason };
|
|
4454
|
+
const member = hit.row.memberRuns?.[s.id];
|
|
4455
|
+
cacheHits.push(s.id);
|
|
4456
|
+
return { ...row, status: "pass", cached: true, batchedWith: { id: source.scan.id, units: source.scan.batch.units }, batchCommand: source.scan.command, ...(hit.row.snapshotEvidence ? { snapshotEvidence: hit.row.snapshotEvidence } : {}), ...(member ? { results: member.results, testRun: member.testRun, executableProof: member.executableProof ?? hit.row.executableProof } : hit.row.executableProof ? { executableProof: hit.row.executableProof } : {}), ...(row.seam ? { seamSettled: true } : {}), detail: `retained ${source.scan.id} (${source.key})` };
|
|
4457
|
+
}
|
|
4458
|
+
let cached = null; let found = null;
|
|
4459
|
+
if (cache) {
|
|
4460
|
+
let hit = readRowCache(cacheKey, admission);
|
|
3764
4461
|
// Adrian 2026-11-06: a rerun that misses the cache fails unless the miss is explained. Each stored pass leaves a per-row index
|
|
3765
4462
|
// (its inputs digest and environment digest); a later miss is "unchanged" (inputs and environment the same: the cache failed),
|
|
3766
4463
|
// "changed" (an input or the environment moved: a legitimate rerun) or "new" (no stored pass: a new row, or a cold run).
|
|
@@ -3768,11 +4465,12 @@ export async function runScans(plan, options = {}) {
|
|
|
3768
4465
|
const rowIndexKey = sha256(`rk-row-index/1\0${s.id}`);
|
|
3769
4466
|
const inputsDigest = keyParts.inputs;
|
|
3770
4467
|
const envDigest = keyParts.env;
|
|
3771
|
-
const
|
|
3772
|
-
|
|
4468
|
+
const strictA = admission && s.class === SCAN_CLASS.A;
|
|
4469
|
+
const idx = strictA ? null : readRowCache(rowIndexKey, admission)?.row ?? null;
|
|
4470
|
+
if (!strictA) row.cacheMiss = { kind: !idx ? "new" : idx.inputs === inputsDigest && idx.env === envDigest ? "unchanged" : "changed", ...(idx ? { last: idx.at ?? null } : {}), ...(idx?.raw ? { why: explainKeyChange(idx.raw, keyParts.raw) } : {}), now: { inputs: keyParts.raw.inputs.slice(0, 4000), toolVersion: keyParts.raw.toolVersion, inherited: keyParts.raw.inherited } };
|
|
3773
4471
|
row.rowIndex = { key: rowIndexKey, inputs: inputsDigest, env: envDigest, raw: keyParts.raw };
|
|
3774
4472
|
// A hit refreshes a row index that lacks the environment shape (stored before the shape existed), so a later key change can carry this row over.
|
|
3775
|
-
if (hit && hit.key === cacheKey && hit.row?.status === "pass" && !options.cacheLookupOnly && !probeScans.has(s) && !idx?.raw?.inheritedShape) {
|
|
4473
|
+
if (!admission && hit && hit.key === cacheKey && hit.row?.status === "pass" && !options.cacheLookupOnly && !probeScans.has(s) && !idx?.raw?.inheritedShape) {
|
|
3776
4474
|
try { cache.write(rowIndexKey, { id: s.id, inputs: inputsDigest, env: envDigest, raw: keyParts.raw, at: new Date().toISOString() }); } catch { /* the hit stands */ }
|
|
3777
4475
|
}
|
|
3778
4476
|
// Carry-over (carryOverProof): a pass stored under an earlier key form, whose real inputs provably did not change, is this row's pass.
|
|
@@ -3783,11 +4481,11 @@ export async function runScans(plan, options = {}) {
|
|
|
3783
4481
|
if (!proof.ok && proof.edited?.length && row.cacheMiss.why) row.cacheMiss.why = { ...row.cacheMiss.why, contentOnly: true, formChangesProven: proof.carried };
|
|
3784
4482
|
if (proof.ok) {
|
|
3785
4483
|
const oldKey = scanCacheKey({ id: s.id, command: keyCommand(s), toolVersion: idx.raw.toolVersion, env: idx.raw.env ?? {}, inheritedEnv: idx.raw.inherited, digest: idx.raw.inputs });
|
|
3786
|
-
const old =
|
|
4484
|
+
const old = readRowCache(oldKey, admission);
|
|
3787
4485
|
if (usableStoredPass(old, s, { cacheKey: oldKey, viaSeam })) {
|
|
3788
4486
|
hit = { ...old, key: cacheKey };
|
|
3789
4487
|
row.carriedOver = { from: oldKey.slice(0, 16), files: proof.carried };
|
|
3790
|
-
if (!options.cacheLookupOnly) { try { cache.write(cacheKey, old.row); cache.write(rowIndexKey, { id: s.id, inputs: inputsDigest, env: envDigest, raw: keyParts.raw, at: new Date().toISOString() }); } catch { /* the pass stands; the next run carries it again */ } }
|
|
4488
|
+
if (!admission && !options.cacheLookupOnly) { try { cache.write(cacheKey, old.row); cache.write(rowIndexKey, { id: s.id, inputs: inputsDigest, env: envDigest, raw: keyParts.raw, at: new Date().toISOString() }); } catch { /* the pass stands; the next run carries it again */ } }
|
|
3791
4489
|
}
|
|
3792
4490
|
}
|
|
3793
4491
|
}
|
|
@@ -3799,19 +4497,26 @@ export async function runScans(plan, options = {}) {
|
|
|
3799
4497
|
// One predicate for every stored pass (usableStoredPass; rightkit#1538): the row's own id and command, written by the invocation that ran it, with
|
|
3800
4498
|
// the evidence its kind needs; a test group's hit carries each member's own run, so the members are judged exactly as on the run that stored it.
|
|
3801
4499
|
if (usableStoredPass(hit, s, { cacheKey, viaSeam })) {
|
|
3802
|
-
|
|
3803
|
-
return { ...row, status: "pass", cached: true, detail: `cached ${String(hit.at ?? "").slice(0, 10) || "earlier"}`, ...(s.kind === "test" || s.runOutside || s.coverageKey ? { results: hit.row.results } : {}), ...(s.coverageKey ? { snapshotEvidence: hit.row.snapshotEvidence ?? null, testRun: hit.row.testRun ?? null } : s.provesPublisher ? { snapshotEvidence: hit.row.snapshotEvidence ?? null, ...(hit.row.testRun ? { testRun: hit.row.testRun } : {}) } : hit.row.testRun ? { testRun: hit.row.testRun } : {}), ...(hit.row.memberRuns ? { memberRuns: hit.row.memberRuns } : {}), ...(hit.row.executableProof ? { executableProof: hit.row.executableProof } : {}), ...(row.seam ? { seamSettled: true } : {}) };
|
|
4500
|
+
cached = { ...row, status: "pass", cached: true, detail: `cached ${String(hit.at ?? "").slice(0, 10) || "earlier"}`, ...(s.kind === "test" || s.runOutside || s.coverageKey ? { results: hit.row.results } : {}), ...(s.coverageKey ? { snapshotEvidence: hit.row.snapshotEvidence ?? null, testRun: hit.row.testRun ?? null } : s.provesPublisher ? { snapshotEvidence: hit.row.snapshotEvidence ?? null, ...(hit.row.testRun ? { testRun: hit.row.testRun } : {}) } : hit.row.testRun ? { testRun: hit.row.testRun } : {}), ...(hit.row.memberRuns ? { memberRuns: hit.row.memberRuns } : {}), ...(hit.row.executableProof ? { executableProof: hit.row.executableProof } : {}), ...(row.seam ? { seamSettled: true } : {}) };
|
|
3804
4501
|
}
|
|
3805
4502
|
// NN41: the same inputs, toolchain and broker runtime already failed this compile deterministically: report that failure, marked cached, without running it.
|
|
3806
|
-
const failHit =
|
|
4503
|
+
const failHit = cached ? null : readRowCache(failKey, admission);
|
|
3807
4504
|
if (failHit && failHit.key === failKey && failHit.row?.status === "fail" && failHit.row.id === s.id && sameCommand(failHit.row.command, s) && failHit.row.failureIdentity === options.failureIdentity && failHit.row.code === "EXIT" && typeof failHit.row.detail === "string" && failHit.row.detail !== "") {
|
|
3808
|
-
|
|
3809
|
-
return { ...row, ...(row.seam ? { seamSettled: true } : {}), status: "fail", code: failHit.row.code, cached: true, failureCached: true, detail: `cached failure ${String(failHit.at ?? "").slice(0, 10) || "earlier"} (same inputs, toolchain and broker runtime): ${failHit.row.detail}`, ...(failHit.row.authenticatedFailure ? { authenticatedFailure: failHit.row.authenticatedFailure } : {}), ...(failHit.row.jsonSummary ? { jsonSummary: failHit.row.jsonSummary } : {}) };
|
|
4505
|
+
cached = { ...row, ...(row.seam ? { seamSettled: true } : {}), status: "fail", code: failHit.row.code, cached: true, failureCached: true, detail: `cached failure ${String(failHit.at ?? "").slice(0, 10) || "earlier"} (same inputs, toolchain and broker runtime): ${failHit.row.detail}`, ...(failHit.row.authenticatedFailure ? { authenticatedFailure: failHit.row.authenticatedFailure } : {}), ...(failHit.row.jsonSummary ? { jsonSummary: failHit.row.jsonSummary } : {}) };
|
|
3810
4506
|
}
|
|
4507
|
+
found = hit ?? failHit;
|
|
4508
|
+
}
|
|
4509
|
+
if (admission && cached?.status === "pass" && metadata) options.cargoWorkspaceFactsFor?.(s, null, found.row.cargoWorkspaceFacts ?? null);
|
|
4510
|
+
if (admission) extraEnv = yield classAObservation(s, cacheKey, failKey, cached, admission, Boolean(found));
|
|
4511
|
+
if (cached) {
|
|
4512
|
+
if (!admission && cached.status === "pass" && !options.cacheLookupOnly && !probeScans.has(s) && metadata) options.cargoWorkspaceFactsFor?.(s, null, found.row.cargoWorkspaceFacts ?? null);
|
|
4513
|
+
cacheHits.push(s.id);
|
|
4514
|
+
return cached;
|
|
3811
4515
|
}
|
|
3812
4516
|
// Adrian 2026-11-06: the cache is looked up for every planned row BEFORE anything runs (options.cacheLookupOnly): a miss is reported with its cause, never run.
|
|
3813
4517
|
// A probe (runGroup's per-crate lookup) answers like a lookup.
|
|
3814
4518
|
if (options.cacheLookupOnly || probeScans.has(s)) return { ...row, status: "not-run", lookupMiss: Boolean(cacheKey), uncacheable: !cacheKey, detail: cacheKey ? "would miss the cache" : "has no cache key", ...(row.seam ? { seamSettled: true } : {}) }; // nothing was submitted
|
|
4519
|
+
markScanDispatch(s, row, admission);
|
|
3815
4520
|
// rightkit#1539: a serial test row owns no compile while its plain row is in this run. It waits for the plain row of the same crate and configuration
|
|
3816
4521
|
// (grouped or alone) and runs that row's accepted executables with --test-threads=1 under its own id, results and key; the plain row's compile verdict
|
|
3817
4522
|
// is never stored under this key (store rule). One compile per crate and configuration, whatever happens:
|
|
@@ -3942,15 +4647,15 @@ export async function runScans(plan, options = {}) {
|
|
|
3942
4647
|
// Without a live reader (no client to ask) the stopwatch simply runs, and every unwatched carried scan gives its client the scan's own limit as the operation deadline
|
|
3943
4648
|
// (RUSTRIGHT_OPERATION_DEADLINE_MS, scanOperationEnv), so the client cancels by id before the gate stops it.
|
|
3944
4649
|
const watched = carriedScan && s.class === SCAN_CLASS.B && s.quiet !== true && brokerLive !== null;
|
|
3945
|
-
let
|
|
4650
|
+
let brokerAdmission = null; let graceTimer = null; let genRefDir = null; let clockExpired = false;
|
|
3946
4651
|
// A carried scan is cancelled by id first and its process tree stopped only after a grace; any other scan is stopped at once.
|
|
3947
4652
|
const stopScan = () => {
|
|
3948
4653
|
clockExpired = true;
|
|
3949
|
-
if (
|
|
4654
|
+
if (brokerAdmission) { brokerAdmission.cancelKnown().catch(() => {}); graceTimer = setTimeout(() => timer.abort(), options.brokerCancelGraceMs ?? CARRIED_CANCEL_GRACE_MS); } else timer.abort();
|
|
3950
4655
|
};
|
|
3951
4656
|
// A watched scan also has ONE wall-clock ceiling, its own limit x QUEUED_CEILING_FACTOR: a safety stop for a wedged broker queue (the broker's job deadlines are off by default), not a count.
|
|
3952
4657
|
const runClock = createRunClock({ limitMs, onExpire: stopScan, ...(watched ? { ceilingMs: limitMs * QUEUED_CEILING_FACTOR, onCeiling: stopScan } : {}) });
|
|
3953
|
-
const stopClock = () => { runClock.stop();
|
|
4658
|
+
const stopClock = () => { runClock.stop(); brokerAdmission?.stop(); if (graceTimer) clearTimeout(graceTimer); if (genRefDir) { fs.rmSync(genRefDir, { recursive: true, force: true }); genRefDir = null; } };
|
|
3954
4659
|
const scanSignal = signal ? AbortSignal.any([signal, timer.signal]) : timer.signal;
|
|
3955
4660
|
// A class A test row runs under the launch guard (class-a-launch-guard.mjs): its Node processes may not launch a compile.
|
|
3956
4661
|
// Every class A row that executes repository code (tests, lint/typecheck with repository config, generators) runs under the
|
|
@@ -4001,6 +4706,14 @@ export async function runScans(plan, options = {}) {
|
|
|
4001
4706
|
try { seamVars = seamEnv({ commit: deps.gateSeam.commit, classA: await ensureVerdict(viaSeam ? (s.cwd ?? ".") : ".") }); }
|
|
4002
4707
|
catch (e) { stopClock(); advisory?.cleanup?.(); return { ...row, status: "fail", code: "CLASS_A_VERDICT", detail: `${s.id}: ${e.message}` }; }
|
|
4003
4708
|
}
|
|
4709
|
+
// A contract-test run tags the broker job this row sends (gate-seam.mjs contractJobTag; loop matrix G26). A row that only starts a suite which
|
|
4710
|
+
// reaches the broker itself gets no nonce here: each of that suite's calls is tagged where it is sent (seam-broker.mjs runSeamCall).
|
|
4711
|
+
let contractTag = null;
|
|
4712
|
+
if (viaSeam) {
|
|
4713
|
+
try { contractTag = contractJobTag({ ...deps.env, ...s.env, ...(extraEnv ?? {}) }); }
|
|
4714
|
+
catch (e) { stopClock(); advisory?.cleanup?.(); return { ...row, status: "fail", code: "RK_CONTRACT_RUN", detail: `${s.id}: ${e.message}` }; }
|
|
4715
|
+
if (contractTag) seamVars = { ...seamVars, [RECEIPT_NONCE_ENV]: contractTag.nonce };
|
|
4716
|
+
}
|
|
4004
4717
|
if (swiftSeam) {
|
|
4005
4718
|
// The adapter through the seam: one `rustright run rightkit-swift -- <argv>` in the snapshot; the result line and receipt are judged below exactly as a cargo row's.
|
|
4006
4719
|
const client = toolCommand("rustright");
|
|
@@ -4033,10 +4746,10 @@ export async function runScans(plan, options = {}) {
|
|
|
4033
4746
|
let refFiles;
|
|
4034
4747
|
if (s.tool === "rustright" || s.tool === "cargo") { genRefDir = fs.mkdtempSync(path.join(os.tmpdir(), "rk-scanreq-")); const file = path.join(genRefDir, "request.json"); refEnv = { RUSTRIGHT_REQUEST_ID_FILE: file }; refFiles = () => [file]; }
|
|
4035
4748
|
else refFiles = () => { try { return ledgerToken && cargoLedger ? readLedger(cargoLedger.dir, ledgerToken).entries.filter((e) => e.status === "pending" && typeof e.requestRef === "string").map((e) => e.requestRef) : []; } catch { return []; } };
|
|
4036
|
-
|
|
4037
|
-
|
|
4749
|
+
brokerAdmission = watchBrokerAdmission({ clock: runClock, refFiles, live: brokerLive, poller: statusPoller });
|
|
4750
|
+
brokerAdmission.start();
|
|
4038
4751
|
}
|
|
4039
|
-
try { r = await deps.spawn(p.command, spawnArgs, { cwd: viaSeam ? path.join(deps.gateSeam.snapshot, s.cwd ?? "") : path.join(rootDir(s.root), s.cwd ?? ""), env: seamSpawnEnv({ ...deps.env, ...sentinelEnv, ...readTargetEnv, ...s.env, ...(extraEnv ?? {}), ...guardEnv, ...ledgerEnv, ...refEnv, ...(carriedScan && !watched ? scanOperationEnv({ ...deps.env, ...s.env }, limitMs) : {}), ...trustEnv, ...seamVars }), signal: scanSignal, ...(listingFile ? { stdoutFile: listingFile } : {}), ...(watched ? {} : { timeout: limitMs }) }); } finally { stopClock(); advisory?.cleanup?.(); }
|
|
4752
|
+
try { r = await deps.spawn(p.command, spawnArgs, { cwd: viaSeam ? path.join(deps.gateSeam.snapshot, s.cwd ?? "") : path.join(rootDir(s.root), s.cwd ?? ""), env: seamSpawnEnv({ ...deps.env, ...sentinelEnv, ...readTargetEnv, ...s.env, ...(extraEnv ?? {}), ...guardEnv, ...ledgerEnv, ...refEnv, ...(carriedScan && !watched ? scanOperationEnv({ ...deps.env, ...s.env }, limitMs) : {}), ...trustEnv, ...seamVars }), signal: scanSignal, ...(listingFile ? { stdoutFile: listingFile } : {}), ...(metadata && options.cargoWorkspaceFactsFor ? { stdoutKeep: 32 * OUTPUT_KEEP } : {}), ...(watched ? {} : { timeout: limitMs }) }); } finally { stopClock(); advisory?.cleanup?.(); }
|
|
4040
4753
|
if ((s.runOutside || s.captureJson) && r && !r.error) {
|
|
4041
4754
|
// The whole listing: the file the spawn streamed, else (a spawn that does not know stdoutFile) its stdout. What a reader sees of a failed compile is the rendered errors.
|
|
4042
4755
|
let fromFile = false;
|
|
@@ -4049,7 +4762,7 @@ export async function runScans(plan, options = {}) {
|
|
|
4049
4762
|
}
|
|
4050
4763
|
if (signal?.aborted && (!r || r.error || r.status !== 0)) return { ...row, status: "not-run", code: "CANCELLED", detail: "cancelled while running" };
|
|
4051
4764
|
if ((clockExpired || timer.signal.aborted || r?.error?.code === "ETIMEDOUT") && (!r || r.error || r.status !== 0)) {
|
|
4052
|
-
const how = `was ${
|
|
4765
|
+
const how = `was ${brokerAdmission ? "cancelled at the broker by id and stopped" : "killed"} with its process tree; a scan that does not finish fails`;
|
|
4053
4766
|
if (runClock.ceilingHit) return { ...row, status: "fail", code: "TIMEOUT", detail: `${s.id} hit its wall-clock ceiling while it waited in the broker's queue (${spanText(limitMs * QUEUED_CEILING_FACTOR)}: ${QUEUED_CEILING_FACTOR} x its ${spanText(limitMs)} run limit, a safety stop for a wedged broker queue, not a count; it had waited ${spanText(runClock.queuedMs)} in the queue) and ${how}` };
|
|
4054
4767
|
return { ...row, status: "fail", code: "TIMEOUT", detail: `${s.id} ran longer than its ${spanText(limitMs)} run limit${runClock.queuedMs > 0 ? ` (the ${spanText(runClock.queuedMs)} it waited in the broker's queue does not count)` : ""} and ${how}` };
|
|
4055
4768
|
}
|
|
@@ -4096,6 +4809,7 @@ export async function runScans(plan, options = {}) {
|
|
|
4096
4809
|
const judged = judgeSeamOutcome({ child: r, stderr: r?.stderr ?? "", commit: deps.gateSeam.commit, tree: deps.gateSeam.tree, classA: seamVars[CLASS_A_ENV] ?? null, expect: { argv: sentArgv, cwd: path.join(deps.gateSeam.snapshot, s.cwd ?? ""), adapter: swiftSeam ? "rightkit-swift" : null } });
|
|
4097
4810
|
// The receipt's test executable list is always recorded, a null one with the broker's reason, so every listing is judged against it (GC-A08: an executable runs only when
|
|
4098
4811
|
// it is on the compile receipt's signed list; a seam receipt with no list runs nothing).
|
|
4812
|
+
if (contractTag) { try { recordContractJob(contractTag, { argv: sentArgv, cwd: path.join(deps.gateSeam.snapshot, s.cwd ?? ""), requestId: judged.evidence?.requestId ?? judged.result?.requestId ?? null, receipt: judged.evidence?.receiptPath ?? null, receiptSha256: judged.evidence?.receiptSha256 ?? null, status: r?.status ?? null }); } catch { /* the contract test finds the job missing from its list and fails the run */ } }
|
|
4099
4813
|
if (judged.evidence) row.snapshotEvidence = { receiptSha256: judged.evidence.receiptSha256, receiptPath: judged.evidence.receiptPath, requestId: judged.evidence.requestId, outputDir: judged.evidence.outputDir, targetTriple: judged.evidence.targetTriple ?? null, cargoDir: s.cwd ?? ".", seam: true, testExecutables: judged.evidence.testExecutables ?? null, testExecutablesReason: judged.evidence.testExecutablesReason ?? null, receiptStatus: judged.evidence.receiptStatus ?? null };
|
|
4100
4814
|
// Settled, for the door's lock release (seamRunState): positive evidence only. A parsed result line AND either a durable receipt read (the job reached its
|
|
4101
4815
|
// terminal state) or an explicit before-execution refusal (a code, or exit 125 with nothing admitted). A missing or malformed line, a missing receipt, a killed
|
|
@@ -4221,11 +4935,17 @@ export async function runScans(plan, options = {}) {
|
|
|
4221
4935
|
// whose status is FAILED: a TIMED_OUT or CANCELLED job keeps its observed exit (it may be cargo's own) but its failure is the stop, never the source.
|
|
4222
4936
|
// NN41: store a deterministic compile failure only: the broker's authenticated compile failure, or a plain exit of a compile with compiler error diagnostics and no sign of
|
|
4223
4937
|
// the environment failing. Never a timeout, abort, SCAN_ERROR, refusal, unverified receipt, ledger problem, test run or infrastructure error (those return or carry another code).
|
|
4224
|
-
if (status === "fail" && failKey && !signal?.aborted && !ledgerProblem && typeof detail === "string" && detail !== "" && (code === "EXIT" && (!carriedScan || (viaSeam && row.snapshotEvidence?.receiptStatus === "FAILED"))) && isDeterministicCompileDiagnostics(`${r?.stdout ?? ""}\n${r?.stderr ?? ""}`)) {
|
|
4225
|
-
|
|
4938
|
+
if (status === "fail" && failKey && !signal?.aborted && !ledgerProblem && typeof detail === "string" && detail !== "" && (code === "EXIT" && (!carriedScan || (viaSeam && row.snapshotEvidence?.receiptStatus === "FAILED"))) && isDeterministicCompileDiagnostics(`${r?.stdout ?? ""}\n${r?.stderr ?? ""}`) && (!isRustTestRowId(s.id) || isTestCompileFailure(`${r?.stdout ?? ""}\n${r?.stderr ?? ""}`))) {
|
|
4939
|
+
storeScanOutcome(failKey, { id: s.id, class: s.class, command: s.command, tool: s.tool ?? null, toolVersion: row.toolVersion, status: "fail", code, detail: detail.slice(0, 6000), failureIdentity: options.failureIdentity, ...(row.authenticatedFailure ? { authenticatedFailure: row.authenticatedFailure } : {}), ...(row.jsonSummary ? { jsonSummary: row.jsonSummary } : {}) }, admission);
|
|
4940
|
+
}
|
|
4941
|
+
if (status === "pass" && !signal?.aborted) {
|
|
4942
|
+
if (metadata && options.cargoWorkspaceFactsFor && r?.truncated) throw new Error("Cargo workspace facts require complete metadata output");
|
|
4943
|
+
const facts = metadata ? options.cargoWorkspaceFactsFor?.(s, r) : null;
|
|
4944
|
+
if (cacheKey) {
|
|
4945
|
+
storeScanOutcome(cacheKey, { ...storedPassRow(s, row), ...(facts ? { cargoWorkspaceFacts: facts } : {}) }, admission);
|
|
4946
|
+
if (row.rowIndex) cache.write(row.rowIndex.key, { id: s.id, inputs: row.rowIndex.inputs, env: row.rowIndex.env, raw: row.rowIndex.raw, at: new Date().toISOString() });
|
|
4947
|
+
}
|
|
4226
4948
|
}
|
|
4227
|
-
if (status === "pass" && cacheKey && !signal?.aborted && row.rowIndex) cache.write(row.rowIndex.key, { id: s.id, inputs: row.rowIndex.inputs, env: row.rowIndex.env, raw: row.rowIndex.raw, at: new Date().toISOString() });
|
|
4228
|
-
if (status === "pass" && cacheKey && !signal?.aborted) cache.write(cacheKey, storedPassRow(s, row));
|
|
4229
4949
|
}
|
|
4230
4950
|
}
|
|
4231
4951
|
} catch (e) { status = "fail"; code = "SCAN_ERROR"; detail = e.message; }
|
|
@@ -4259,12 +4979,15 @@ export async function runScans(plan, options = {}) {
|
|
|
4259
4979
|
// Positive evidence only: a seam row is settled when it carries seamSettled (a parsed result with a durable receipt or an explicit refusal, a cache hit, a lookup); every other seam row, whatever its code, keeps the lock.
|
|
4260
4980
|
for (const r of results) if (r.seam === true) { seamRunState.rows += 1; if (r.seamSettled !== true || (cancelled && r.status !== "pass")) seamRunState.unsettled += 1; }
|
|
4261
4981
|
if (deps.gateSeam) seamRunState.open -= 1;
|
|
4262
|
-
const allPassed = !cancelled && verdictFailure === null && results.every((r) => r.status === "pass");
|
|
4982
|
+
const allPassed = !cancelled && verdictFailure === null && !classACacheDecision?.mismatches.length && !classBCacheDecision?.mismatches.length && results.every((r) => r.status === "pass");
|
|
4263
4983
|
return {
|
|
4264
4984
|
schema: SCAN_RESULT_SCHEMA, ok: allPassed, complete: allPassed, classes, checker, ...(cancelled ? { cancelled: true } : {}), ...(verdictFailure ? { verdictFailure } : {}),
|
|
4265
4985
|
inputDigest: plan.inputDigest ?? null,
|
|
4266
4986
|
deferred: results.filter((r) => r.status === "deferred").map((r) => r.id),
|
|
4267
4987
|
scans: results, toolVersions, toolIdentities, cacheHits: [...cacheHits].sort(), notes: [...(plan.notes ?? []), ...batchFailureNotes, ...partitionNotes, ...seamNotes, ...(cargoLedger ? [UNOBSERVED_NESTED_CARGO_NOTE] : [])],
|
|
4988
|
+
...(classACacheDecision ? { classACacheDecision } : {}),
|
|
4989
|
+
...(classALanes.length ? { classALanes } : {}),
|
|
4990
|
+
...(classBCacheDecision ? { classBCacheDecision } : {}),
|
|
4268
4991
|
scanSetDigest: digestScanSet(results),
|
|
4269
4992
|
classDigests: { A: digestScanSet(results.filter((r) => r.class === "A")), B: digestScanSet(results.filter((r) => r.class === "B")) },
|
|
4270
4993
|
};
|