Skip to content

Commit 38539b8

Browse files
agorischekCopilot
andauthored
Comparator runtime: a caller's signal stops a check or comparison (#104)
* Comparator runtime: a caller's signal stops a check or comparison RulesRuntime.check and compare take {signal}: aborting it terminates the Worker (or kills the native runner) and rejects with cancelled, and an aborted signal never starts one. loadArtifact passes ArtifactRules.signal to the runtime. A caller with one budget across several calls, such as a hosted artifact verifier, can now stop work at its deadline instead of letting each call run to its own. Code review, finding 8 (public part). Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Comparator runtime: document RulesRuntime Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Comparator runtime: a signal ends only its own caller's wait or check An aborted call is rejected before it loads the interpreter or looks in the check cache; waiting for the shared interpreter is abortable for each caller without cancelling the load; a check still running is shared only by callers without a signal, while one with a signal runs its own and shares the result once it succeeds, so cancelling one caller never fails another. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 67f4a55 commit 38539b8

11 files changed

Lines changed: 197 additions & 51 deletions

File tree

‎packages/comparators/runtime/js/README.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,12 @@ try {
4040
and `projections_compare` exports must match the ABI.
4141
- The deadline (default 30 s) is wall-clock time; when it passes the Worker is
4242
terminated and the call rejects with `deadline`.
43+
- `check` and `compare` also take `{signal}`: aborting it terminates the Worker
44+
(or kills the native runner) and rejects with `cancelled`; an aborted signal
45+
never starts one. A caller with an overall budget across several calls passes
46+
`AbortSignal.timeout(remaining)` or its own controller, so no call outlives
47+
it. `loadArtifact` passes `rules.signal` through when it reruns a comparator
48+
file.
4349
- Memory is capped at `maxMemoryPages` (default 4096, 256 MiB). A module whose
4450
initial memory exceeds the cap is rejected; a module that declares a maximum
4551
within the cap is bounded natively; otherwise the memory size is checked after

‎packages/comparators/runtime/js/src/abi.ts‎

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,8 @@ export const limits = Object.freeze({
4040
* (`invalid-module`, `forbidden-import`, `missing-export`, `invalid-export`), the input was (`invalid-input`,
4141
* `input-too-large`), it hit a bound (`out-of-fuel` and `table-limit` in the native runner, `deadline`,
4242
* `memory-limit`), it trapped (`trap`), its result was malformed (`invalid-return`, `output-too-large`,
43-
* `invalid-output`), it returned `{"error": message}` (`comparator-error`), or its Worker or runner process failed
44-
* (`worker`).
43+
* `invalid-output`), it returned `{"error": message}` (`comparator-error`), its Worker or runner process failed
44+
* (`worker`), or the caller's signal cancelled it (`cancelled`, the run stopped).
4545
*/
4646
export type ComparatorErrorCode =
4747
| 'invalid-module'
@@ -60,6 +60,7 @@ export type ComparatorErrorCode =
6060
| 'invalid-output'
6161
| 'comparator-error'
6262
| 'worker'
63+
| 'cancelled'
6364

6465
/** A comparator module could not be loaded or run. Never falls back to another comparison. */
6566
export class ComparatorRuntimeError extends Error {
@@ -72,6 +73,35 @@ export class ComparatorRuntimeError extends Error {
7273
}
7374
}
7475

76+
/** The error for a run its caller's signal cancelled. */
77+
export function cancelled(signal: AbortSignal): ComparatorRuntimeError {
78+
const reason = signal.reason instanceof Error ? `: ${signal.reason.message}` : ''
79+
return new ComparatorRuntimeError('cancelled', `the comparator run was cancelled${reason}`)
80+
}
81+
82+
/**
83+
* `promise`, or a rejection with `cancelled` as soon as `signal` aborts: this caller stops waiting, and the work
84+
* `promise` stands for, which other callers may share, carries on.
85+
*/
86+
export function abortable<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
87+
if (!signal) return promise
88+
if (signal.aborted) return Promise.reject(cancelled(signal))
89+
return new Promise<T>((resolve, reject) => {
90+
const abort = () => reject(cancelled(signal))
91+
signal.addEventListener('abort', abort, {once: true})
92+
promise.then(
93+
value => {
94+
signal.removeEventListener('abort', abort)
95+
resolve(value)
96+
},
97+
(error: unknown) => {
98+
signal.removeEventListener('abort', abort)
99+
reject(error)
100+
},
101+
)
102+
})
103+
}
104+
75105
export const fail = (code: ComparatorErrorCode, message: string): never => {
76106
throw new ComparatorRuntimeError(code, message)
77107
}

‎packages/comparators/runtime/js/src/browser-worker.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,12 @@ import {runInWorker} from './host.js'
22
import type {ExecuteRequest} from './execute.js'
33

44
/** Runs one request in a fresh module Web Worker, terminated at the deadline. */
5-
export function run(request: ExecuteRequest, deadlineMs: number, workerUrl: URL | string | undefined): Promise<unknown> {
5+
export function run(
6+
request: ExecuteRequest,
7+
deadlineMs: number,
8+
workerUrl: URL | string | undefined,
9+
signal?: AbortSignal,
10+
): Promise<unknown> {
611
return runInWorker(
712
events => {
813
const worker = new Worker(workerUrl ?? new URL('./worker-entry.js', import.meta.url), {type: 'module'})
@@ -19,5 +24,6 @@ export function run(request: ExecuteRequest, deadlineMs: number, workerUrl: URL
1924
},
2025
request,
2126
deadlineMs,
27+
signal,
2228
)
2329
}

‎packages/comparators/runtime/js/src/browser.ts‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,19 @@
1+
import {abortable} from './abi.js'
12
import {run} from './browser-worker.js'
23
import {settings, type RunComparatorOptions} from './host.js'
34
import {cachedChecks, checkedRules, compareRequest, inspectRequest, loadRulesInterpreter, type RulesRuntime} from './rules.js'
45

56
export {ComparatorRuntimeError, limits, type ComparatorErrorCode} from './abi.js'
67
export type {RunComparatorOptions} from './host.js'
7-
export {RulesError, isComparatorFile, rulesComparatorDigest, type CheckedRules, type RulesDiagnostic, type RulesRuntime} from './rules.js'
8+
export {
9+
RulesError,
10+
isComparatorFile,
11+
rulesComparatorDigest,
12+
type CheckedRules,
13+
type RulesCallOptions,
14+
type RulesDiagnostic,
15+
type RulesRuntime,
16+
} from './rules.js'
817

918
/** The sandbox bounds for `createRulesRuntime` in a browser, and where its Worker script and interpreter are served. */
1019
export interface BrowserComparatorOptions extends RunComparatorOptions {
@@ -35,19 +44,21 @@ export function createRulesRuntime(options: BrowserComparatorOptions = {}): Rule
3544
return new Uint8Array(await response.arrayBuffer())
3645
})
3746
return {
38-
check: cachedChecks(async rules => {
39-
const loaded = await interpreter()
47+
check: cachedChecks(async (rules, call) => {
48+
// Waiting for the shared interpreter, a caller can still be cancelled; the load carries on for the others.
49+
const loaded = await abortable(interpreter(), call?.signal)
4050
const report = await run(
4151
inspectRequest(loaded, rules, resolved.maxMemoryPages, resolved.maxOutputBytes),
4252
resolved.deadlineMs,
4353
options.workerUrl,
54+
call?.signal,
4455
)
4556
return checkedRules(loaded, report)
4657
}),
47-
async compare(rules, input) {
48-
const loaded = await interpreter()
58+
async compare(rules, input, call) {
59+
const loaded = await abortable(interpreter(), call?.signal)
4960
const request = compareRequest(loaded, rules, input, resolved.maxInputBytes, resolved.maxMemoryPages, resolved.maxOutputBytes)
50-
return run(request, resolved.deadlineMs, options.workerUrl)
61+
return run(request, resolved.deadlineMs, options.workerUrl, call?.signal)
5162
},
5263
}
5364
}

‎packages/comparators/runtime/js/src/host.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import {ComparatorRuntimeError, PAGE_BYTES, errors, limits} from './abi.js'
1+
import {ComparatorRuntimeError, PAGE_BYTES, cancelled, errors, limits} from './abi.js'
22
import {encodeInput} from './input.js'
33
import {inspectModule} from './module-check/inspect.js'
44
import type {ExecuteRequest, ExecuteResult} from './execute.js'
@@ -84,14 +84,22 @@ export interface WorkerEvents {
8484
}
8585

8686
/** Runs one request in a fresh worker, terminating it on completion, failure or deadline. */
87-
export function runInWorker(spawn: (events: WorkerEvents) => WorkerHandle, request: ExecuteRequest, deadlineMs: number): Promise<unknown> {
87+
export function runInWorker(
88+
spawn: (events: WorkerEvents) => WorkerHandle,
89+
request: ExecuteRequest,
90+
deadlineMs: number,
91+
signal?: AbortSignal,
92+
): Promise<unknown> {
8893
return new Promise((resolve, reject) => {
94+
if (signal?.aborted) return reject(cancelled(signal))
8995
let settled = false
9096
let worker: WorkerHandle | undefined
97+
const abort = () => finish(cancelled(signal!))
9198
const finish = (error: ComparatorRuntimeError | undefined, value?: unknown) => {
9299
if (settled) return
93100
settled = true
94101
clearTimeout(timer)
102+
signal?.removeEventListener('abort', abort)
95103
worker?.terminate()
96104
if (error) reject(error)
97105
else resolve(value)
@@ -100,6 +108,7 @@ export function runInWorker(spawn: (events: WorkerEvents) => WorkerHandle, reque
100108
() => finish(new ComparatorRuntimeError('deadline', `comparator exceeded its ${deadlineMs} ms deadline`)),
101109
deadlineMs,
102110
)
111+
signal?.addEventListener('abort', abort, {once: true})
103112
try {
104113
worker = spawn({
105114
message(data) {

‎packages/comparators/runtime/js/src/node-worker.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import {runInWorker} from './host.js'
33
import type {ExecuteRequest} from './execute.js'
44

55
/** Runs one request in a fresh `worker_threads` Worker, terminated at the deadline. */
6-
export function run(request: ExecuteRequest, deadlineMs: number): Promise<unknown> {
6+
export function run(request: ExecuteRequest, deadlineMs: number, signal?: AbortSignal): Promise<unknown> {
77
return runInWorker(
88
events => {
99
const worker = new Worker(new URL('./node-worker-entry.js', import.meta.url))
@@ -18,5 +18,6 @@ export function run(request: ExecuteRequest, deadlineMs: number): Promise<unknow
1818
},
1919
request,
2020
deadlineMs,
21+
signal,
2122
)
2223
}

‎packages/comparators/runtime/js/src/node.ts‎

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,19 @@ import {fileURLToPath} from 'node:url'
55
import {settings, type RunComparatorOptions} from './host.js'
66
import {run} from './node-worker.js'
77
import {cachedChecks, checkedRules, diagnostic, compareRequest, inspectRequest, loadRulesInterpreter, type RulesRuntime} from './rules.js'
8-
import {ComparatorRuntimeError, limits} from './abi.js'
8+
import {ComparatorRuntimeError, abortable, cancelled, limits} from './abi.js'
99

1010
export {ComparatorRuntimeError, limits, type ComparatorErrorCode} from './abi.js'
1111
export type {RunComparatorOptions} from './host.js'
12-
export {RulesError, isComparatorFile, rulesComparatorDigest, type CheckedRules, type RulesDiagnostic, type RulesRuntime} from './rules.js'
12+
export {
13+
RulesError,
14+
isComparatorFile,
15+
rulesComparatorDigest,
16+
type CheckedRules,
17+
type RulesCallOptions,
18+
type RulesDiagnostic,
19+
type RulesRuntime,
20+
} from './rules.js'
1321

1422
const rulesUrl = new URL('./rules.wasm', import.meta.url)
1523
/** The packaged rules interpreter, checked and compiled once. */
@@ -23,15 +31,19 @@ export const nodeRulesInterpreter = () => loadRulesInterpreter(rulesUrl.href, as
2331
export function createRulesRuntime(options: RunComparatorOptions = {}): RulesRuntime {
2432
const resolved = settings(options)
2533
return {
26-
check: cachedChecks(async rules => {
27-
const interpreter = await nodeRulesInterpreter()
28-
const report = await run(inspectRequest(interpreter, rules, resolved.maxMemoryPages, resolved.maxOutputBytes), resolved.deadlineMs)
34+
check: cachedChecks(async (rules, call) => {
35+
const interpreter = await abortable(nodeRulesInterpreter(), call?.signal)
36+
const report = await run(
37+
inspectRequest(interpreter, rules, resolved.maxMemoryPages, resolved.maxOutputBytes),
38+
resolved.deadlineMs,
39+
call?.signal,
40+
)
2941
return checkedRules(interpreter, report)
3042
}),
31-
async compare(rules, input) {
32-
const interpreter = await nodeRulesInterpreter()
43+
async compare(rules, input, call) {
44+
const interpreter = await abortable(nodeRulesInterpreter(), call?.signal)
3345
const request = compareRequest(interpreter, rules, input, resolved.maxInputBytes, resolved.maxMemoryPages, resolved.maxOutputBytes)
34-
return run(request, resolved.deadlineMs)
46+
return run(request, resolved.deadlineMs, call?.signal)
3547
},
3648
}
3749
}
@@ -62,10 +74,10 @@ export function createNativeRulesRuntime(options: NativeRulesRuntimeOptions = {}
6274
}
6375
const interpreter = options.interpreter ?? fileURLToPath(new URL('./rules.wasm', import.meta.url))
6476
const executable = options.executable ?? packagedRunner()
65-
const call = (request: unknown) => runNative(executable, interpreter, request, deadlineMs)
77+
const call = (request: unknown, signal?: AbortSignal) => runNative(executable, interpreter, request, deadlineMs, signal)
6678
return {
67-
check: cachedChecks(async rules => {
68-
const result = (await call({operation: 'check', rules: rulesSource(rules)})) as {
79+
check: cachedChecks(async (rules, options) => {
80+
const result = (await call({operation: 'check', rules: rulesSource(rules)}, options?.signal)) as {
6981
digest?: unknown
7082
canonical?: unknown
7183
warnings?: unknown
@@ -79,7 +91,7 @@ export function createNativeRulesRuntime(options: NativeRulesRuntimeOptions = {}
7991
warnings: Array.isArray(result.warnings) ? result.warnings.map(diagnostic) : [],
8092
}
8193
}),
82-
compare: (rules, input) => call({operation: 'compare', rules: rulesSource(rules), input}),
94+
compare: (rules, input, options) => call({operation: 'compare', rules: rulesSource(rules), input}, options?.signal),
8395
}
8496
}
8597

@@ -127,16 +139,19 @@ const codes = new Set<string>([
127139
'comparator-error',
128140
])
129141

130-
function runNative(executable: string, interpreter: string, request: unknown, deadlineMs: number): Promise<unknown> {
142+
function runNative(executable: string, interpreter: string, request: unknown, deadlineMs: number, signal?: AbortSignal): Promise<unknown> {
131143
return new Promise((resolve, reject) => {
144+
if (signal?.aborted) return reject(cancelled(signal))
132145
const child = spawn(executable, ['--interpreter', interpreter], {stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true})
133146
const chunks: Buffer[] = []
134147
let size = 0
135148
let settled = false
149+
const abort = () => finish(cancelled(signal!))
136150
const finish = (error: ComparatorRuntimeError | undefined, value?: unknown) => {
137151
if (settled) return
138152
settled = true
139153
clearTimeout(timer)
154+
signal?.removeEventListener('abort', abort)
140155
if (error) {
141156
child.kill('SIGKILL')
142157
reject(error)
@@ -146,6 +161,7 @@ function runNative(executable: string, interpreter: string, request: unknown, de
146161
() => finish(new ComparatorRuntimeError('deadline', `the rules runner exceeded its ${deadlineMs} ms deadline`)),
147162
deadlineMs,
148163
)
164+
signal?.addEventListener('abort', abort, {once: true})
149165
child.on('error', error => finish(new ComparatorRuntimeError('worker', `the rules runner failed to start: ${error.message}`)))
150166
child.stdout.on('data', (chunk: Buffer) => {
151167
size += chunk.length

‎packages/comparators/runtime/js/src/rules.ts‎

Lines changed: 44 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
* comparator file is checked once per content.
77
* Portable: no Node or DOM-only APIs.
88
*/
9-
import {ComparatorRuntimeError, RULES_INSPECT_EXPORT, errors, limits} from './abi.js'
9+
import {ComparatorRuntimeError, RULES_INSPECT_EXPORT, abortable, cancelled, errors, limits} from './abi.js'
1010
import {encodeInput} from './input.js'
1111
import {inspectModule} from './module-check/inspect.js'
1212
import type {ExecuteRequest} from './execute.js'
@@ -168,28 +168,57 @@ export function diagnostic(value: unknown): RulesDiagnostic {
168168
* load-time checks and returns the comparator digest, cached per rules
169169
* content; `compare` runs one comparison.
170170
*/
171+
/**
172+
* Per call: `signal` cancels the check or comparison, which then stops its Worker or runner process and rejects with
173+
* `cancelled`, so a caller with an overall deadline (`AbortSignal.timeout`) never leaves one running past it.
174+
*/
175+
export interface RulesCallOptions {
176+
signal?: AbortSignal
177+
}
178+
179+
/** Checks and runs comparator files sandboxed, each call in its own Worker or runner process; see `RulesCallOptions`. */
171180
export interface RulesRuntime {
172-
check(rules: Uint8Array): Promise<CheckedRules>
173-
compare(rules: Uint8Array, input: unknown): Promise<unknown>
181+
check(rules: Uint8Array, options?: RulesCallOptions): Promise<CheckedRules>
182+
compare(rules: Uint8Array, input: unknown, options?: RulesCallOptions): Promise<unknown>
174183
}
175184

176-
/** Caches `check` per rules content, so a host checks each rules file once. */
185+
/**
186+
* Caches `check` per rules content, so a host checks each rules file once. A check that succeeded is shared by every
187+
* caller; one still running is shared only by callers without a signal. A caller with a signal runs its own check,
188+
* which its signal alone can cancel, and shares the result once it succeeds, so cancelling one caller never fails
189+
* another. An aborted signal is rejected before anything is looked up or run.
190+
*/
177191
export function cachedChecks(
178-
check: (rules: Uint8Array) => Promise<CheckedRules>,
192+
check: (rules: Uint8Array, options?: RulesCallOptions) => Promise<CheckedRules>,
179193
capacity = 64,
180-
): (rules: Uint8Array) => Promise<CheckedRules> {
194+
): (rules: Uint8Array, options?: RulesCallOptions) => Promise<CheckedRules> {
181195
const cache = new Map<string, Promise<CheckedRules>>()
182-
return async rules => {
183-
const key = await sha256(rules)
184-
let checked = cache.get(key)
185-
if (checked) {
186-
cache.delete(key)
187-
} else {
188-
checked = check(rules)
189-
checked.catch(() => cache.delete(key))
190-
}
196+
const succeeded = new WeakSet<Promise<CheckedRules>>()
197+
const remember = (key: string, checked: Promise<CheckedRules>) => {
198+
cache.delete(key)
191199
cache.set(key, checked)
192200
while (cache.size > capacity) cache.delete(cache.keys().next().value!)
201+
}
202+
return async (rules, options) => {
203+
const signal = options?.signal
204+
if (signal?.aborted) throw cancelled(signal)
205+
const key = await sha256(rules)
206+
const cached = cache.get(key)
207+
if (cached && (!signal || succeeded.has(cached))) {
208+
remember(key, cached)
209+
return abortable(cached, signal)
210+
}
211+
const checked = check(rules, signal ? {signal} : {})
212+
if (!signal) remember(key, checked)
213+
checked.then(
214+
() => {
215+
succeeded.add(checked)
216+
if (signal && !cache.has(key)) remember(key, checked)
217+
},
218+
() => {
219+
if (cache.get(key) === checked) cache.delete(key)
220+
},
221+
)
193222
return checked
194223
}
195224
}

‎packages/comparators/runtime/js/src/testing.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,8 @@ export async function runModuleInWorkerForTests(
5353
moduleBytes: Uint8Array,
5454
input: unknown,
5555
options: RunComparatorOptions = {},
56+
signal?: AbortSignal,
5657
): Promise<unknown> {
5758
const resolved = settings(options)
58-
return run(await prepare(moduleBytes, input, resolved), resolved.deadlineMs)
59+
return run(await prepare(moduleBytes, input, resolved), resolved.deadlineMs, signal)
5960
}

0 commit comments

Comments
 (0)