tslaws 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,162 @@
1
+ // Optional native Z3 backend: uses a persistent pooled `z3 -in -smt2` process with `(reset)` between queries when a
2
+ // native `z3` binary is available (`TSLAWS_Z3` or `z3` on PATH). Faster and far less memory-hungry than the
3
+ // WebAssembly build in `smtWorker.ts`, lifting the 4-worker RAM cap. Falls back seamlessly to WASM when absent or
4
+ // when `TSLAWS_Z3=wasm`.
5
+ import { spawn, spawnSync } from 'node:child_process';
6
+ import { statSync } from 'node:fs';
7
+ import { SolverCrash } from "./chc.js";
8
+ import { jobs, lowerPriority, WorkerPool } from "./pool.js";
9
+ const sentinel = '__TSLAWS_Z3_DONE__';
10
+ const modelSentinel = '__TSLAWS_Z3_VALS__';
11
+ let detectedPath;
12
+ let detectedEnv;
13
+ /** Resolves the native `z3` binary path if installed and enabled, else undefined. */
14
+ export function nativeZ3Path(env = process.env) {
15
+ const configured = env.TSLAWS_Z3?.trim();
16
+ if (configured === 'wasm' || configured === '0' || configured === 'false')
17
+ return undefined;
18
+ if (detectedPath !== undefined && detectedEnv === configured)
19
+ return detectedPath ?? undefined;
20
+ detectedEnv = configured;
21
+ const candidate = configured !== undefined && configured !== '' ? configured : 'z3';
22
+ try {
23
+ const probe = spawnSync(candidate, ['--version'], {
24
+ encoding: 'utf8',
25
+ timeout: 3000,
26
+ windowsHide: true,
27
+ });
28
+ if (probe.error === undefined && probe.status === 0 && /Z3 version/i.test(probe.stdout ?? '')) {
29
+ detectedPath = candidate;
30
+ return candidate;
31
+ }
32
+ }
33
+ catch {
34
+ // Native Z3 is not available; fall back to WebAssembly.
35
+ }
36
+ detectedPath = null;
37
+ return undefined;
38
+ }
39
+ /** Fingerprint of the active Z3 backend for proof cache keys. */
40
+ export function z3Fingerprint(env = process.env) {
41
+ const bin = nativeZ3Path(env);
42
+ if (bin === undefined)
43
+ return 'z3-wasm';
44
+ try {
45
+ const st = statSync(bin);
46
+ return `z3-native:${bin}:${st.size}:${st.mtimeMs}`;
47
+ }
48
+ catch {
49
+ return `z3-native:${bin}`;
50
+ }
51
+ }
52
+ class NativeZ3Process {
53
+ child;
54
+ buffer = '';
55
+ alive = true;
56
+ waiter;
57
+ constructor(binary) {
58
+ this.child = spawn(binary, ['-in', '-smt2'], {
59
+ stdio: ['pipe', 'pipe', 'pipe'],
60
+ windowsHide: true,
61
+ });
62
+ lowerPriority(this.child.pid);
63
+ this.child.unref();
64
+ let stderr = '';
65
+ this.child.stderr?.setEncoding('utf8').on('data', (chunk) => {
66
+ stderr = (stderr + chunk).slice(-2000);
67
+ });
68
+ this.child.stdout?.setEncoding('utf8').on('data', (chunk) => {
69
+ this.buffer += chunk;
70
+ this.drain();
71
+ });
72
+ const fail = (why) => {
73
+ this.alive = false;
74
+ const pending = this.waiter;
75
+ this.waiter = undefined;
76
+ pending?.reject(new SolverCrash(`the native Z3 solver crashed: ${why}${stderr ? ` (${stderr.trim()})` : ''}`));
77
+ };
78
+ this.child.on('error', (error) => fail(error.message));
79
+ this.child.on('exit', (code, signal) => fail(`exited with ${signal ?? `code ${code}`}`));
80
+ this.child.stdin?.on('error', () => undefined);
81
+ }
82
+ drain() {
83
+ if (this.waiter === undefined)
84
+ return;
85
+ const token = `"${this.waiter.marker}"`;
86
+ const idx = this.buffer.indexOf(token);
87
+ if (idx < 0)
88
+ return;
89
+ const before = this.buffer.slice(0, idx).trim();
90
+ const afterNl = this.buffer.indexOf('\n', idx + token.length);
91
+ this.buffer = afterNl < 0 ? '' : this.buffer.slice(afterNl + 1);
92
+ const { resolve } = this.waiter;
93
+ this.waiter = undefined;
94
+ resolve(before);
95
+ }
96
+ sendAndWait(script, marker) {
97
+ if (!this.alive || this.child.stdin === null)
98
+ return Promise.reject(new SolverCrash('native Z3 process closed'));
99
+ return new Promise((resolve, reject) => {
100
+ this.waiter = { marker, resolve, reject };
101
+ this.child.stdin.write(`${script}\n(echo "${marker}")\n`);
102
+ this.drain();
103
+ });
104
+ }
105
+ async solve(query, values) {
106
+ const out = await this.sendAndWait(`(reset)\n${query}`, sentinel);
107
+ const vals = out.startsWith('sat') && values !== '' ? await this.sendAndWait(values, modelSentinel) : '';
108
+ return { out, vals };
109
+ }
110
+ terminate() {
111
+ this.alive = false;
112
+ try {
113
+ this.child.kill('SIGKILL');
114
+ }
115
+ catch {
116
+ // Already exited.
117
+ }
118
+ }
119
+ }
120
+ let poolBinary;
121
+ let pool;
122
+ function poolFor(binary) {
123
+ if (pool !== undefined && poolBinary === binary)
124
+ return pool;
125
+ pool?.close();
126
+ poolBinary = binary;
127
+ pool = new WorkerPool(() => new NativeZ3Process(binary), jobs, 10000);
128
+ return pool;
129
+ }
130
+ /** Terminates idle native Z3 processes (e.g. after a solver crash). */
131
+ export function closeNativeZ3() {
132
+ pool?.close();
133
+ }
134
+ /** Runs one SMT-LIB query against a pooled native Z3 process; rejects with `Unsupported` on timeout. */
135
+ export async function solveNative(binary, query, values, timeoutMs, onTimeout) {
136
+ const activePool = poolFor(binary);
137
+ const proc = await activePool.acquire();
138
+ let timer;
139
+ let timedOut = false;
140
+ try {
141
+ const timeout = new Promise((_resolve, reject) => {
142
+ timer = setTimeout(() => {
143
+ timedOut = true;
144
+ activePool.discard(proc);
145
+ reject(onTimeout());
146
+ }, timeoutMs + 3000);
147
+ });
148
+ const reply = await Promise.race([proc.solve(query, values), timeout]);
149
+ if (!timedOut)
150
+ activePool.release(proc);
151
+ return reply;
152
+ }
153
+ catch (error) {
154
+ if (!timedOut)
155
+ activePool.discard(proc);
156
+ throw error;
157
+ }
158
+ finally {
159
+ if (timer !== undefined)
160
+ clearTimeout(timer);
161
+ }
162
+ }
package/dist/plan.d.ts CHANGED
@@ -25,9 +25,16 @@ export type Plan = {
25
25
  name: string;
26
26
  fallback?: Plan;
27
27
  security?: true;
28
+ } | {
29
+ k: 'intRange';
30
+ min: number;
31
+ max: number;
28
32
  } | {
29
33
  k: 'array';
30
34
  of: Plan;
35
+ } | {
36
+ k: 'nonEmpty';
37
+ of: Plan;
31
38
  } | {
32
39
  k: 'tuple';
33
40
  required: Plan[];
package/dist/plan.js CHANGED
@@ -10,6 +10,13 @@ export class UnsupportedType extends Error {
10
10
  const numbers = fc.oneof({ weight: 4, arbitrary: fc.integer({ min: -8, max: 8 }) }, { weight: 3, arbitrary: fc.integer({ min: -1000, max: 1000 }) }, { weight: 1, arbitrary: fc.integer() }, { weight: 2, arbitrary: fc.double({ noNaN: true, noDefaultInfinity: true }) });
11
11
  // `int` from 'tslaws': whole numbers, biased to small ones.
12
12
  arbitraryRegistry().set('int', fc.oneof({ weight: 4, arbitrary: fc.integer({ min: -8, max: 8 }) }, { weight: 3, arbitrary: fc.integer({ min: -1000, max: 1000 }) }, { weight: 1, arbitrary: fc.integer({ min: -Number.MAX_SAFE_INTEGER, max: Number.MAX_SAFE_INTEGER }) }));
13
+ // Built-in refinement types from 'tslaws'.
14
+ arbitraryRegistry().set('nat', fc.oneof({ weight: 4, arbitrary: fc.integer({ min: 0, max: 16 }) }, { weight: 3, arbitrary: fc.integer({ min: 0, max: 1000 }) }, { weight: 1, arbitrary: fc.integer({ min: 0, max: Number.MAX_SAFE_INTEGER }) }));
15
+ arbitraryRegistry().set('posInt', fc.oneof({ weight: 4, arbitrary: fc.integer({ min: 1, max: 16 }) }, { weight: 3, arbitrary: fc.integer({ min: 1, max: 1000 }) }, { weight: 1, arbitrary: fc.integer({ min: 1, max: Number.MAX_SAFE_INTEGER }) }));
16
+ arbitraryRegistry().set('nonZeroInt', fc.oneof({ weight: 4, arbitrary: fc.integer({ min: 1, max: 16 }) }, { weight: 4, arbitrary: fc.integer({ min: -16, max: -1 }) }, { weight: 2, arbitrary: fc.integer({ min: 1, max: 1000 }) }, { weight: 2, arbitrary: fc.integer({ min: -1000, max: -1 }) }, { weight: 1, arbitrary: fc.integer({ min: 1, max: Number.MAX_SAFE_INTEGER }) }, { weight: 1, arbitrary: fc.integer({ min: -Number.MAX_SAFE_INTEGER, max: -1 }) }));
17
+ arbitraryRegistry().set('asciiString', fc.string({ maxLength: 24 }));
18
+ arbitraryRegistry().set('nonEmptyString', fc.string({ minLength: 1, maxLength: 24 }));
19
+ arbitraryRegistry().set('finite', fc.double({ noNaN: true, noDefaultInfinity: true }));
13
20
  /** Marks a generated function on the wire: browser laws receive their arguments as structured data. */
14
21
  export const wireKey = '$tslawsFn';
15
22
  function pick(samples, args) {
@@ -97,8 +104,12 @@ export function arbitraryOf(plan) {
97
104
  throw new UnsupportedType(`no generator registered for ${plan.name}`);
98
105
  return arbitraryOf(plan.fallback);
99
106
  }
107
+ case 'intRange':
108
+ return fc.integer({ min: Math.ceil(plan.min), max: Math.floor(plan.max) });
100
109
  case 'array':
101
110
  return sequence(arbitraryOf(plan.of), { maxLength: 8 });
111
+ case 'nonEmpty':
112
+ return sequence(arbitraryOf(plan.of), { minLength: 1, maxLength: 8 });
102
113
  case 'tuple': {
103
114
  const required = plan.required.map(arbitraryOf);
104
115
  const optional = plan.optional.map(arbitraryOf);
@@ -0,0 +1,24 @@
1
+ import type { CertifyMode } from './certificates.ts';
2
+ import { type SolverName } from './solvers.ts';
3
+ import type { ProofResult } from './smt.ts';
4
+ /** Fingerprint of the solver + certificate toolchain relevant to a proof query. */
5
+ export declare function toolchainFingerprint(solvers: readonly SolverName[] | undefined, certify: CertifyMode | undefined): string;
6
+ export interface ProofCache {
7
+ get(key: string, keep?: {
8
+ dir: string;
9
+ name: string;
10
+ root: string;
11
+ }): ProofResult | undefined;
12
+ set(key: string, result: ProofResult): void;
13
+ flush(): void;
14
+ }
15
+ /** Computes the cache key for an exact SMT-LIB query (or Horn system) under the given solver/certify configuration. */
16
+ export declare function proofCacheKey(input: {
17
+ query: string;
18
+ bounded: readonly string[];
19
+ assumptions: readonly string[];
20
+ solvers: readonly SolverName[] | undefined;
21
+ certify: CertifyMode | undefined;
22
+ }): string;
23
+ /** Opens the project's proof cache (`.tslaws/proof-cache.json`). Deferred write: call `flush()` once at end of check. */
24
+ export declare function openProofCache(cwd: string): ProofCache;
@@ -0,0 +1,135 @@
1
+ // On-disk proof & certificate verdict cache keyed by exact SMT-LIB query hash and solver/tool fingerprints.
2
+ // Unchanged laws skip Z3, cvc5 and Carcara on incremental/watch/CI runs; any change to the law, its called code,
3
+ // solver config, or tool binary invalidates the entry.
4
+ import { createHash } from 'node:crypto';
5
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
6
+ import { dirname, join } from 'node:path';
7
+ import { hashOf } from "./certificates.js";
8
+ import { z3Fingerprint } from "./nativeZ3.js";
9
+ import { toolCommand } from "./solvers.js";
10
+ const cacheVersion = 1;
11
+ const maxEntries = 2000;
12
+ function toolStamp(env, binary) {
13
+ const cmd = toolCommand(env, binary);
14
+ const target = cmd.args[0] ?? cmd.file;
15
+ try {
16
+ const st = statSync(target);
17
+ return `${cmd.file}:${cmd.args.join(',')}:${st.size}:${st.mtimeMs}`;
18
+ }
19
+ catch {
20
+ return `${cmd.file}:${cmd.args.join(',')}`;
21
+ }
22
+ }
23
+ /** Fingerprint of the solver + certificate toolchain relevant to a proof query. */
24
+ export function toolchainFingerprint(solvers, certify) {
25
+ const parts = [z3Fingerprint()];
26
+ const usesCvc5 = (solvers?.includes('cvc5') ?? false) || (certify !== undefined && certify !== false);
27
+ if (usesCvc5)
28
+ parts.push(`cvc5=${toolStamp('TSLAWS_CVC5', 'cvc5')}`);
29
+ if (certify !== undefined && certify !== false)
30
+ parts.push(`carcara=${toolStamp('TSLAWS_CARCARA', 'carcara')}`);
31
+ return parts.join('|');
32
+ }
33
+ const noopCache = {
34
+ get: () => undefined,
35
+ set: () => undefined,
36
+ flush: () => undefined,
37
+ };
38
+ /** Computes the cache key for an exact SMT-LIB query (or Horn system) under the given solver/certify configuration. */
39
+ export function proofCacheKey(input) {
40
+ const hash = createHash('sha256');
41
+ hash.update(JSON.stringify([
42
+ cacheVersion,
43
+ input.query,
44
+ input.bounded,
45
+ input.assumptions,
46
+ input.solvers ?? ['z3'],
47
+ input.certify ?? false,
48
+ toolchainFingerprint(input.solvers, input.certify),
49
+ ]));
50
+ return hash.digest('hex');
51
+ }
52
+ /** Verifies that a cached certified result still has intact saved proof files on disk when `keep` is requested. */
53
+ function keptFilesIntact(certificate, keep) {
54
+ if (certificate === undefined || certificate.status !== 'certified' || keep === undefined)
55
+ return true;
56
+ const smtFile = join(keep.dir, `${keep.name}.smt2`);
57
+ const proofFile = join(keep.dir, `${keep.name}.alethe`);
58
+ if (!existsSync(smtFile) || !existsSync(proofFile))
59
+ return false;
60
+ try {
61
+ if (certificate.problemHash !== undefined && hashOf(readFileSync(smtFile, 'utf8')) !== certificate.problemHash)
62
+ return false;
63
+ if (certificate.proofHash !== undefined && hashOf(readFileSync(proofFile, 'utf8')) !== certificate.proofHash)
64
+ return false;
65
+ if (certificate.systemHash !== undefined) {
66
+ const hornFile = join(keep.dir, `${keep.name}.horn`);
67
+ const invFile = join(keep.dir, `${keep.name}.inv`);
68
+ if (!existsSync(hornFile) || !existsSync(invFile))
69
+ return false;
70
+ if (hashOf(readFileSync(hornFile, 'utf8')) !== certificate.systemHash)
71
+ return false;
72
+ }
73
+ return true;
74
+ }
75
+ catch {
76
+ return false;
77
+ }
78
+ }
79
+ /** Opens the project's proof cache (`.tslaws/proof-cache.json`). Deferred write: call `flush()` once at end of check. */
80
+ export function openProofCache(cwd) {
81
+ if (process.env.TSLAWS_NO_PROOF_CACHE === '1')
82
+ return noopCache;
83
+ const path = join(cwd, '.tslaws', 'proof-cache.json');
84
+ let stored = { version: cacheVersion, entries: {} };
85
+ try {
86
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
87
+ if (parsed?.version === cacheVersion && typeof parsed.entries === 'object' && parsed.entries !== null)
88
+ stored = parsed;
89
+ }
90
+ catch {
91
+ // No cache yet.
92
+ }
93
+ let dirty = false;
94
+ return {
95
+ get(key, keep) {
96
+ const entry = stored.entries[key];
97
+ if (entry === undefined)
98
+ return undefined;
99
+ // Never serve an unavailable/uncertified certificate from cache so newly installed tools are picked up immediately.
100
+ if (entry.result.certificate !== undefined && entry.result.certificate.status !== 'certified')
101
+ return undefined;
102
+ if (!keptFilesIntact(entry.result.certificate, keep))
103
+ return undefined;
104
+ entry.at = Date.now();
105
+ return entry.result;
106
+ },
107
+ set(key, result) {
108
+ if (result.kind !== 'proved' && result.kind !== 'bounded')
109
+ return;
110
+ if (result.certificate !== undefined && result.certificate.status !== 'certified')
111
+ return;
112
+ stored.entries[key] = { result, at: Date.now() };
113
+ dirty = true;
114
+ },
115
+ flush() {
116
+ if (!dirty)
117
+ return;
118
+ dirty = false;
119
+ try {
120
+ const keys = Object.keys(stored.entries);
121
+ if (keys.length > maxEntries) {
122
+ keys
123
+ .sort((a, b) => (stored.entries[a]?.at ?? 0) - (stored.entries[b]?.at ?? 0))
124
+ .slice(0, keys.length - maxEntries)
125
+ .forEach((k) => delete stored.entries[k]);
126
+ }
127
+ mkdirSync(dirname(path), { recursive: true });
128
+ writeFileSync(path, JSON.stringify(stored));
129
+ }
130
+ catch {
131
+ // Not caching is only slower.
132
+ }
133
+ },
134
+ };
135
+ }
@@ -14,7 +14,7 @@ export interface LawTypes {
14
14
  /** Every declaration file the compiler emitted: the laws' own do not import the code they are about. */
15
15
  export declare function declarationFiles(outDir: string): string[];
16
16
  export declare function dtsPath(outDir: string, file: string): string;
17
- /** What the prover models of `type`: numbers, `int`s, bigints, strings, booleans, arrays and records of them. */
17
+ /** What the prover models of `type`: numbers, `int`s (and refinements), bigints, strings, booleans, arrays and records. */
18
18
  export declare function shapeOf(checker: ts.TypeChecker, type: ts.Type): Shape;
19
19
  /** `cwd` is given when `program` is the one that compiled the laws, whose source files hold the types the declarations would. */
20
20
  export declare function typesOf(program: ts.Program, outDir: string, law: ManifestLaw, cwd?: string): LawTypes;
@@ -22,4 +22,4 @@ export declare const compilerOptions: ts.CompilerOptions;
22
22
  /** Starts `n` property workers ahead of the first law, so they load while the code compiles. */
23
23
  export declare function warmWorkers(n: number): void;
24
24
  /** Runs the property test of `law` in a pooled worker, giving up on it after `options.propertyTimeoutMs`. */
25
- export declare function runLawGuarded(outDir: string, law: ManifestLaw, options: CheckOptions, plans: Plan[]): Promise<PropertyOutcome | 'timeout'>;
25
+ export declare function runLawGuarded(outDir: string, law: ManifestLaw, options: CheckOptions, plans: Plan[], buildKey?: string): Promise<PropertyOutcome | 'timeout'>;
package/dist/property.js CHANGED
@@ -2,7 +2,7 @@ import { Worker } from 'node:worker_threads';
2
2
  import { readdirSync, statSync } from 'node:fs';
3
3
  import { join, resolve } from 'node:path';
4
4
  import ts from 'typescript';
5
- import { GeneratorFactory } from "./generators.js";
5
+ import { GeneratorFactory, readIntRangeBounds, readNonEmptyElement } from "./generators.js";
6
6
  import { lawEnv } from "./coverage.js";
7
7
  import { arbitraryOf, UnsupportedType } from "./plan.js";
8
8
  import { budget, WorkerPool } from "./pool.js";
@@ -27,11 +27,35 @@ export function declarationFiles(outDir) {
27
27
  export function dtsPath(outDir, file) {
28
28
  return join(outDir, file.replace(/\.(ts|tsx|mts|cts)$/, '.d.ts'));
29
29
  }
30
- /** What the prover models of `type`: numbers, `int`s, bigints, strings, booleans, arrays and records of them. */
30
+ /** What the prover models of `type`: numbers, `int`s (and refinements), bigints, strings, booleans, arrays and records. */
31
31
  export function shapeOf(checker, type) {
32
- if ((type.aliasSymbol ?? type.getSymbol())?.getName() === 'int' &&
33
- type.flags & (ts.TypeFlags.Intersection | ts.TypeFlags.Number))
34
- return 'int';
32
+ const aliasName = (type.aliasSymbol ?? type.getSymbol())?.getName();
33
+ if (type.flags & (ts.TypeFlags.Intersection | ts.TypeFlags.Number)) {
34
+ const bounds = readIntRangeBounds(checker, type);
35
+ if (bounds !== undefined)
36
+ return { intRange: bounds };
37
+ if (aliasName === 'int')
38
+ return 'int';
39
+ if (aliasName === 'nat')
40
+ return 'nat';
41
+ if (aliasName === 'posInt')
42
+ return 'posInt';
43
+ if (aliasName === 'nonZeroInt')
44
+ return 'nonZeroInt';
45
+ if (aliasName === 'finite')
46
+ return 'number';
47
+ }
48
+ if (type.flags & (ts.TypeFlags.Intersection | ts.TypeFlags.String)) {
49
+ if (aliasName === 'asciiString')
50
+ return 'asciiString';
51
+ if (aliasName === 'nonEmptyString')
52
+ return 'nonEmptyString';
53
+ }
54
+ if (aliasName === 'nonEmpty') {
55
+ const elemType = readNonEmptyElement(checker, type);
56
+ const element = elemType === undefined ? undefined : shapeOf(checker, elemType);
57
+ return element === undefined ? undefined : { array: element, minLength: 1 };
58
+ }
35
59
  if (type.flags & ts.TypeFlags.Number)
36
60
  return 'number';
37
61
  if (type.flags & ts.TypeFlags.BigInt)
@@ -110,11 +134,11 @@ export function warmWorkers(n) {
110
134
  workers.warm(n);
111
135
  }
112
136
  /** Runs the property test of `law` in a pooled worker, giving up on it after `options.propertyTimeoutMs`. */
113
- export async function runLawGuarded(outDir, law, options, plans) {
137
+ export async function runLawGuarded(outDir, law, options, plans, buildKey) {
114
138
  // The worker task is a slot of the budget (the law's own, when it runs under one).
115
- return budget.run(() => runInWorker(outDir, law, options, plans));
139
+ return budget.run(() => runInWorker(outDir, law, options, plans, buildKey));
116
140
  }
117
- async function runInWorker(outDir, law, options, plans) {
141
+ async function runInWorker(outDir, law, options, plans, buildKey) {
118
142
  const current = await workers.acquire();
119
143
  return new Promise((resolve, reject) => {
120
144
  const timer = setTimeout(() => {
@@ -138,6 +162,7 @@ async function runInWorker(outDir, law, options, plans) {
138
162
  plans,
139
163
  options: { ...options, onEvent: undefined },
140
164
  env: lawEnv(options.cwd, 'node'),
165
+ buildKey,
141
166
  });
142
167
  });
143
168
  }
@@ -12,15 +12,23 @@ import { installLoaderHooks, setImportMetaEnv } from "./runtimeEnv.js";
12
12
  // from `require.cache` and loaded again; an `import()` of it could not be forgotten.
13
13
  const require = createRequire(import.meta.url);
14
14
  installLoaderHooks();
15
+ const loadedBuildKeys = new Map();
15
16
  parentPort.on('message', async (request) => {
16
17
  try {
17
- const { outDir, law, plans, options, env } = request;
18
+ const { outDir, law, plans, options, env, buildKey } = request;
18
19
  setImportMetaEnv(env);
19
20
  const generators = plans.map(arbitraryOf);
20
- // The build left the project's module resolution beside the output (aliases from its tsconfig, TypeScript sources).
21
- installLawRuntime(JSON.parse(readFileSync(join(outDir, runtimeFile), 'utf8')));
22
- // The worker outlives a check, and the code may have been recompiled since the last one. Files a plugin loaded go too.
23
- evictLoaded(require.cache, outDir);
21
+ const sameBuild = buildKey !== undefined && loadedBuildKeys.get(outDir) === buildKey;
22
+ if (!sameBuild) {
23
+ // The build left the project's module resolution beside the output (aliases from its tsconfig, TypeScript sources).
24
+ installLawRuntime(JSON.parse(readFileSync(join(outDir, runtimeFile), 'utf8')));
25
+ // The worker outlives a check, and the code may have been recompiled since the last one. Files a plugin loaded go too.
26
+ evictLoaded(require.cache, outDir);
27
+ if (buildKey !== undefined)
28
+ loadedBuildKeys.set(outDir, buildKey);
29
+ else
30
+ loadedBuildKeys.delete(outDir);
31
+ }
24
32
  const fn = require(jsPath(outDir, law.file))[law.symbol ?? law.name];
25
33
  parentPort.postMessage({ ok: summarise(await runLaw(fn, generators, options), options) });
26
34
  }
package/dist/sandbox.d.ts CHANGED
@@ -89,7 +89,7 @@ export declare class Sandbox {
89
89
  private ask;
90
90
  private askOnce;
91
91
  /** The property test of `law`, `'timeout'` when it does not finish; throws `LawLoadError` when it cannot be loaded. */
92
- run(outDir: string, law: ManifestLaw, options: CheckOptions, plans: Plan[]): Promise<SandboxedRun | 'timeout'>;
92
+ run(outDir: string, law: ManifestLaw, options: CheckOptions, plans: Plan[], buildKey?: string): Promise<SandboxedRun | 'timeout'>;
93
93
  /**
94
94
  * Whether the law holds on `inputs` (a model the prover found), as the prover's replay needs it. A law that hangs or
95
95
  * cannot be loaded counts as holding: the model is then not confirmed, and nothing is reported as refuted.
package/dist/sandbox.js CHANGED
@@ -12,7 +12,7 @@
12
12
  // them (`--allow-e2e`). `--no-sandbox` turns it all off, with a warning.
13
13
  import { fork } from 'node:child_process';
14
14
  import { createHash, randomBytes } from 'node:crypto';
15
- import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs';
15
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
16
16
  import { homedir } from 'node:os';
17
17
  import { dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
18
18
  import { fileURLToPath } from 'node:url';
@@ -316,6 +316,35 @@ const namesOf = (manifest, fields) => fields.flatMap((field) => {
316
316
  const value = manifest?.[field];
317
317
  return typeof value === 'object' && value !== null ? Object.keys(value) : [];
318
318
  });
319
+ const trustedPackagesCache = new Map();
320
+ function manifestStamp(dir) {
321
+ const out = [];
322
+ for (const name of ['package.json', 'package-lock.json', 'pnpm-lock.yaml']) {
323
+ const p = join(dir, name);
324
+ try {
325
+ const st = statSync(p);
326
+ out.push([p, st.size, st.mtimeMs]);
327
+ }
328
+ catch {
329
+ out.push([p, -1, -1]);
330
+ }
331
+ }
332
+ return out;
333
+ }
334
+ function stampsMatch(stamps) {
335
+ for (const [p, size, mtimeMs] of stamps) {
336
+ try {
337
+ const st = statSync(p);
338
+ if (st.size !== size || st.mtimeMs !== mtimeMs)
339
+ return false;
340
+ }
341
+ catch {
342
+ if (size !== -1 || mtimeMs !== -1)
343
+ return false;
344
+ }
345
+ }
346
+ return true;
347
+ }
319
348
  /**
320
349
  * The packages the code may load: those the manifests declare (the project's `package.json` with its dev dependencies,
321
350
  * and tslaws's own) and, from each one's manifest, what it declares in turn. Anything else in a `node_modules` was put
@@ -324,6 +353,10 @@ const namesOf = (manifest, fields) => fields.flatMap((field) => {
324
353
  */
325
354
  export function trustedPackages(cwd) {
326
355
  const project = realOf(resolve(cwd));
356
+ const cached = trustedPackagesCache.get(project);
357
+ if (cached !== undefined && stampsMatch(cached.stamps))
358
+ return cached.value;
359
+ const stamps = [...manifestStamp(project), ...manifestStamp(tslawsRoot)];
327
360
  const modules = new Set();
328
361
  const linked = new Set();
329
362
  const seen = new Set();
@@ -358,7 +391,11 @@ export function trustedPackages(cwd) {
358
391
  for (const [dir, fields] of manifests)
359
392
  for (const name of namesOf(readManifest(join(dir, 'package.json')), fields))
360
393
  visit(name, dir);
361
- return { modules: [...modules], linked: [...linked] };
394
+ const value = { modules: [...modules], linked: [...linked] };
395
+ if (trustedPackagesCache.size > 256)
396
+ trustedPackagesCache.clear();
397
+ trustedPackagesCache.set(project, { stamps, value });
398
+ return value;
362
399
  }
363
400
  /**
364
401
  * The reviewed set of a project after a build: the build's output, the files its laws reach, the packages, and the
@@ -476,11 +513,11 @@ class LawProcess {
476
513
  configKey;
477
514
  /** Answers only requests that carry it. The process learns it from `configure` and no law can read it. */
478
515
  token = randomBytes(24).toString('hex');
479
- constructor(cwd, extra) {
516
+ constructor(flags) {
480
517
  this.child = fork(hostFile, [], {
481
518
  // The allowlisted environment the token-free check process gets (see isolate.ts): no credential, no code loader.
482
519
  env: scrubbedEnv(process.env),
483
- execArgv: sandboxFlags(cwd, extra),
520
+ execArgv: flags,
484
521
  serialization: 'advanced',
485
522
  stdio: ['ignore', 'inherit', 'inherit', 'ipc'],
486
523
  windowsHide: true,
@@ -551,7 +588,7 @@ export function liveSandboxProcesses() {
551
588
  * Makes room for a process about to start: the cap is shared by every project, not held by each, so an idle process of
552
589
  * another project (or configuration) ends when the budget is already spent. The pool counts the new one before it starts.
553
590
  */
554
- function startProcess(cwd, extra) {
591
+ function startProcess(flags) {
555
592
  const cap = jobs();
556
593
  for (const { pool } of pools.values()) {
557
594
  if (liveSandboxProcesses() <= cap)
@@ -559,15 +596,17 @@ function startProcess(cwd, extra) {
559
596
  while (liveSandboxProcesses() > cap && pool.evictOne())
560
597
  ;
561
598
  }
562
- return new LawProcess(cwd, extra);
599
+ return new LawProcess(flags);
563
600
  }
564
601
  function poolFor(cwd, extra) {
565
602
  const key = JSON.stringify([resolve(cwd), extra]);
566
603
  let entry = pools.get(key);
567
604
  if (entry === undefined) {
605
+ // Compute permission flags once per pool instead of re-walking node_modules for every forked process.
606
+ const flags = sandboxFlags(cwd, extra);
568
607
  entry = {
569
608
  cwd: resolve(cwd),
570
- pool: new WorkerPool(() => startProcess(cwd, extra), jobs, idleMs),
609
+ pool: new WorkerPool(() => startProcess(flags), jobs, idleMs),
571
610
  };
572
611
  pools.set(key, entry);
573
612
  }
@@ -633,7 +672,7 @@ export class Sandbox {
633
672
  }
634
673
  }
635
674
  /** The property test of `law`, `'timeout'` when it does not finish; throws `LawLoadError` when it cannot be loaded. */
636
- async run(outDir, law, options, plans) {
675
+ async run(outDir, law, options, plans, buildKey) {
637
676
  const reply = await this.ask(options.propertyTimeoutMs ?? 30000, (id) => ({
638
677
  type: 'run',
639
678
  id,
@@ -643,6 +682,7 @@ export class Sandbox {
643
682
  // Functions cannot cross to the process; it needs only the numbers.
644
683
  options: { ...options, onEvent: undefined },
645
684
  env: lawEnv(options.cwd, 'node'),
685
+ buildKey,
646
686
  }));
647
687
  if (reply === 'timeout')
648
688
  return reply;