tslaws 1.1.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +177 -187
- package/dist/api.d.ts +86 -0
- package/dist/api.js +78 -0
- package/dist/badge.d.ts +58 -11
- package/dist/badge.js +194 -27
- package/dist/browser.d.ts +5 -2
- package/dist/browser.js +403 -173
- package/dist/browserApi.d.ts +305 -0
- package/dist/browserApi.js +456 -0
- package/dist/browserServer.d.ts +13 -0
- package/dist/browserServer.js +406 -0
- package/dist/certificates.js +50 -28
- package/dist/chc.js +30 -7
- package/dist/check.js +55 -30
- package/dist/cli.js +12 -2
- package/dist/compile.js +41 -4
- package/dist/coverage.d.ts +17 -0
- package/dist/coverage.js +269 -18
- package/dist/derived.d.ts +2 -0
- package/dist/derived.js +9 -4
- package/dist/generators.d.ts +5 -1
- package/dist/generators.js +50 -4
- package/dist/githubCli.js +67 -7
- package/dist/lawHost.d.ts +2 -0
- package/dist/lawHost.js +31 -18
- package/dist/lock.d.ts +1 -0
- package/dist/lock.js +7 -4
- package/dist/nativeZ3.d.ts +11 -0
- package/dist/nativeZ3.js +162 -0
- package/dist/plan.d.ts +7 -0
- package/dist/plan.js +11 -0
- package/dist/proofCache.d.ts +24 -0
- package/dist/proofCache.js +135 -0
- package/dist/property.d.ts +2 -2
- package/dist/property.js +33 -8
- package/dist/propertyWorker.js +13 -5
- package/dist/sandbox.d.ts +1 -1
- package/dist/sandbox.js +48 -8
- package/dist/seal.js +47 -8
- package/dist/smt.d.ts +7 -1
- package/dist/smt.js +202 -26
- package/dist/symbolic.d.ts +38 -3
- package/dist/symbolic.js +504 -47
- package/dist/types.d.ts +4 -0
- package/package.json +6 -6
package/dist/lawHost.d.ts
CHANGED
|
@@ -26,6 +26,8 @@ export type HostRequest = {
|
|
|
26
26
|
plans: Plan[];
|
|
27
27
|
options: CheckOptions;
|
|
28
28
|
env: ImportMetaEnv;
|
|
29
|
+
/** Identifies the build; unchanged keys reuse already-loaded compiled modules instead of evicting require.cache per law. */
|
|
30
|
+
buildKey?: string;
|
|
29
31
|
} | {
|
|
30
32
|
type: 'holds';
|
|
31
33
|
token: string;
|
package/dist/lawHost.js
CHANGED
|
@@ -16,6 +16,7 @@ const guard = new Guard();
|
|
|
16
16
|
let secret;
|
|
17
17
|
const transformed = new Map();
|
|
18
18
|
const loaded = new Map();
|
|
19
|
+
const loadedBuildKeys = new Map();
|
|
19
20
|
let guarded = false;
|
|
20
21
|
// The channel is the only way out. Keep it, and take it from the code that runs here so it cannot answer for the host.
|
|
21
22
|
// `process.send` calls `this._send`, which lockDown hides, so the inner function is kept as well.
|
|
@@ -114,28 +115,40 @@ function lookup(kind, file) {
|
|
|
114
115
|
throw new Error(prepared.error);
|
|
115
116
|
return prepared.code;
|
|
116
117
|
}
|
|
117
|
-
function load(outDir, law, env, fresh) {
|
|
118
|
+
function load(outDir, law, env, fresh, buildKey) {
|
|
118
119
|
const key = `${outDir}\0${law.file}\0${law.symbol ?? law.name}`;
|
|
120
|
+
const sameBuild = buildKey !== undefined && loadedBuildKeys.get(outDir) === buildKey;
|
|
119
121
|
const known = loaded.get(key);
|
|
120
|
-
if (!fresh && known !== undefined)
|
|
122
|
+
if ((!fresh || sameBuild) && known !== undefined) {
|
|
123
|
+
setImportMetaEnv(env);
|
|
121
124
|
return known;
|
|
125
|
+
}
|
|
122
126
|
setImportMetaEnv(env);
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
guarded
|
|
134
|
-
|
|
135
|
-
|
|
127
|
+
if (!sameBuild) {
|
|
128
|
+
installLoaderHooks();
|
|
129
|
+
useTransforms({
|
|
130
|
+
source: (file) => lookup('ts', file),
|
|
131
|
+
plugin: (file, _cwd, _plugins, format) => lookup(format, file),
|
|
132
|
+
});
|
|
133
|
+
installLawRuntime(JSON.parse(readFileSync(join(outDir, runtimeFile), 'utf8')));
|
|
134
|
+
// Before the guard: the resolver loads TypeScript, which needs Node modules that no law may load.
|
|
135
|
+
loadResolver();
|
|
136
|
+
// From here on only reviewed files load. Installed after the runtime's own hooks, so it sees what they resolve.
|
|
137
|
+
if (!guarded) {
|
|
138
|
+
guarded = true;
|
|
139
|
+
installGuard(guard);
|
|
140
|
+
lockDown();
|
|
141
|
+
}
|
|
142
|
+
// The process outlives a check, and the code may have been recompiled since the last one.
|
|
143
|
+
evictLoaded(require.cache, outDir);
|
|
144
|
+
for (const k of loaded.keys())
|
|
145
|
+
if (k.startsWith(`${outDir}\0`))
|
|
146
|
+
loaded.delete(k);
|
|
147
|
+
if (buildKey !== undefined)
|
|
148
|
+
loadedBuildKeys.set(outDir, buildKey);
|
|
149
|
+
else
|
|
150
|
+
loadedBuildKeys.delete(outDir);
|
|
136
151
|
}
|
|
137
|
-
// The process outlives a check, and the code may have been recompiled since the last one.
|
|
138
|
-
evictLoaded(require.cache, outDir);
|
|
139
152
|
const fn = require(jsPath(outDir, law.file))[law.symbol ?? law.name];
|
|
140
153
|
if (typeof fn !== 'function')
|
|
141
154
|
throw new Error('compiled module does not export the law');
|
|
@@ -169,7 +182,7 @@ process.on('message', async (request) => {
|
|
|
169
182
|
const { id } = request;
|
|
170
183
|
let fn;
|
|
171
184
|
try {
|
|
172
|
-
fn = load(request.outDir, request.law, request.env, request.type === 'run');
|
|
185
|
+
fn = load(request.outDir, request.law, request.env, request.type === 'run', request.type === 'run' ? request.buildKey : undefined);
|
|
173
186
|
}
|
|
174
187
|
catch (error) {
|
|
175
188
|
send({ id, error: message(error), phase: 'load' });
|
package/dist/lock.d.ts
CHANGED
|
@@ -26,6 +26,7 @@ export interface Lock {
|
|
|
26
26
|
export declare function lawKey(file: string, name: string): string;
|
|
27
27
|
/** The hash of a law: its own text, whether it is `proved`, and its seal (the code it depends on and the run settings). */
|
|
28
28
|
export declare function lawHash(law: ManifestLaw): string;
|
|
29
|
+
export declare function parseLock(text: string): Lock;
|
|
29
30
|
export declare function readLock(path: string): Lock | undefined;
|
|
30
31
|
/** The records that still describe their law: the law is in the lock with the hash the record was made for. */
|
|
31
32
|
export declare function currentCertificates(laws: LockEntries, records: Record<string, CertificateRecord> | undefined): Record<string, CertificateRecord>;
|
package/dist/lock.js
CHANGED
|
@@ -20,10 +20,8 @@ export function lawHash(law) {
|
|
|
20
20
|
.update(law.seal ?? '')
|
|
21
21
|
.digest('hex');
|
|
22
22
|
}
|
|
23
|
-
export function
|
|
24
|
-
|
|
25
|
-
return undefined;
|
|
26
|
-
const lock = JSON.parse(readFileSync(path, 'utf8'));
|
|
23
|
+
export function parseLock(text) {
|
|
24
|
+
const lock = JSON.parse(text);
|
|
27
25
|
return {
|
|
28
26
|
version: typeof lock.version === 'number' ? Math.min(lockFormat, Math.max(0, lock.version)) : 0,
|
|
29
27
|
laws: lock.laws,
|
|
@@ -32,6 +30,11 @@ export function readLock(path) {
|
|
|
32
30
|
...(lock.certificates === undefined ? {} : { certificates: lock.certificates }),
|
|
33
31
|
};
|
|
34
32
|
}
|
|
33
|
+
export function readLock(path) {
|
|
34
|
+
if (!existsSync(path))
|
|
35
|
+
return undefined;
|
|
36
|
+
return parseLock(readFileSync(path, 'utf8'));
|
|
37
|
+
}
|
|
35
38
|
/** The records that still describe their law: the law is in the lock with the hash the record was made for. */
|
|
36
39
|
export function currentCertificates(laws, records) {
|
|
37
40
|
const kept = {};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Resolves the native `z3` binary path if installed and enabled, else undefined. */
|
|
2
|
+
export declare function nativeZ3Path(env?: NodeJS.ProcessEnv): string | undefined;
|
|
3
|
+
/** Fingerprint of the active Z3 backend for proof cache keys. */
|
|
4
|
+
export declare function z3Fingerprint(env?: NodeJS.ProcessEnv): string;
|
|
5
|
+
/** Terminates idle native Z3 processes (e.g. after a solver crash). */
|
|
6
|
+
export declare function closeNativeZ3(): void;
|
|
7
|
+
/** Runs one SMT-LIB query against a pooled native Z3 process; rejects with `Unsupported` on timeout. */
|
|
8
|
+
export declare function solveNative(binary: string, query: string, values: string, timeoutMs: number, onTimeout: () => Error): Promise<{
|
|
9
|
+
out: string;
|
|
10
|
+
vals: string;
|
|
11
|
+
}>;
|
package/dist/nativeZ3.js
ADDED
|
@@ -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
|
+
}
|
package/dist/property.d.ts
CHANGED
|
@@ -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
|
|
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
|
|
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
|
-
|
|
33
|
-
|
|
34
|
-
|
|
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
|
}
|
package/dist/propertyWorker.js
CHANGED
|
@@ -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
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
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.
|