-
Notifications
You must be signed in to change notification settings - Fork 404
Expand file tree
/
Copy pathharness-executor.ts
More file actions
1304 lines (1244 loc) · 42.9 KB
/
Copy pathharness-executor.ts
File metadata and controls
1304 lines (1244 loc) · 42.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { spawn, type ChildProcess } from 'node:child_process';
import { createHash, randomBytes } from 'node:crypto';
import { once } from 'node:events';
import { createReadStream } from 'node:fs';
import { chmod, lstat, mkdir, readFile, readdir, unlink, writeFile } from 'node:fs/promises';
import { createServer, type Server, type Socket } from 'node:net';
import { basename, dirname, join, posix, relative, resolve, sep } from 'node:path';
import { createInterface } from 'node:readline';
import { decodeJsonObject, type ExperimentCell, type JsonObject } from './experiment.js';
import {
BUNDLED_HARNESS_RELAY_ROOT,
createHarnessPreparationEnvironment,
resolveRealPathWithinRoot,
} from './harness-environment.js';
import {
preflightHarnessInstallation,
type HarnessPreflightDependencies,
} from './install-preflight.js';
import {
MAKA_RUNTIME_ARTIFACT_PATH,
MAKA_SUBJECT_STDERR_PATH,
MAKA_SUBJECT_STDOUT_PATH,
} from './maka-artifacts.js';
import {
type ExecutorAttemptOutcome,
type ExperimentExecutor,
type ExecutorPreparationCode,
type ExecutorVerification,
type SubjectExecutionContext,
} from './runner.js';
import type { EvalResult } from './result.js';
export type HarnessFramework = 'harbor' | 'pier';
type RelayTransportStage = 'ready' | 'execute' | 'receive' | 'decision';
const PIER_FRAMEWORK_LOG_MOUNTS = Object.freeze([
{ directory: 'agent', target: '/logs/agent' },
{ directory: 'verifier', target: '/logs/verifier' },
{ directory: 'artifacts', target: '/logs/artifacts' },
]);
interface RelayTransportFailure {
readonly stage: RelayTransportStage;
readonly category:
| 'broken-pipe'
| 'connection-reset'
| 'peer-closed'
| 'protocol-error'
| 'transport-error';
readonly delivery: 'not-delivered' | 'unknown';
}
interface RelayTransport {
readonly socket: Socket;
stage: RelayTransportStage;
failure?: RelayTransportFailure;
}
interface RelayState {
readonly child: ChildProcess;
readonly transport: RelayTransport;
readonly closeRelay: () => Promise<void>;
readonly lines: AsyncIterator<string>;
readonly token: string;
readonly trialName: string;
readonly trialPath: string;
readonly taskInput: string;
readonly credentials: Readonly<Record<string, string>>;
readonly cwd: string;
readonly executionEnvironment: Readonly<Record<string, string>>;
used: boolean;
diagnostic?: SubjectProcessDiagnostic;
}
type SubjectProcessDiagnostic = NonNullable<
Awaited<ReturnType<SubjectExecutionContext['execute']>>['diagnostic']
>;
export interface HarnessExecutor extends ExperimentExecutor {
preflight(
input: {
readonly subjectCredentialNames: readonly string[];
readonly signal?: AbortSignal;
},
dependencies?: Partial<HarnessPreflightDependencies>,
): Promise<void>;
}
export function createHarborExecutor(config: JsonObject, specPath: string): HarnessExecutor {
return createHarnessExecutor('harbor', config, specPath);
}
export function createPierExecutor(config: JsonObject, specPath: string): HarnessExecutor {
return createHarnessExecutor('pier', config, specPath);
}
function createHarnessExecutor(
framework: HarnessFramework,
config: JsonObject,
specPath: string,
): HarnessExecutor {
const options = decodeHarnessOptions(config, framework);
const executor: HarnessExecutor = {
kind: framework,
preflight: (input, dependencies) =>
preflightHarnessInstallation(
{
framework,
options,
specPath,
subjectCredentialNames: input.subjectCredentialNames,
...(input.signal ? { signal: input.signal } : {}),
},
dependencies,
),
validate: (cell) => {
decodeTask(framework, options, cell);
},
runAttempt: (input, operation) =>
runHarnessAttempt(framework, options, specPath, input, operation),
};
return executor;
}
async function runHarnessAttempt(
framework: HarnessFramework,
options: HarnessOptions,
specPath: string,
{
cell,
subjectCredentialNames,
signal,
}: {
readonly cell: ExperimentCell;
readonly subjectCredentialNames: readonly string[];
readonly signal?: AbortSignal;
},
operation: (attempt: {
readonly context: SubjectExecutionContext;
verify(): Promise<ExecutorVerification>;
}) => Promise<EvalResult>,
): Promise<ExecutorAttemptOutcome> {
if (signal?.aborted) return notStarted('cancelled');
let prepared: Awaited<ReturnType<typeof startTrial>>;
try {
prepared = await startTrial(framework, options, specPath, cell, subjectCredentialNames, signal);
} catch {
return notStarted('preparation-failed');
}
if (prepared.kind === 'not_started') return prepared;
const state = prepared.state;
let decision = false;
let value: EvalResult | undefined;
let hasValue = false;
let hostCancellationObserved = false;
let verificationConfirmedBeforeCancellation = false;
let finalizationEvidence: TrialWaitEvidence | undefined;
let cleanupAction: 'abort' | 'terminate-unused' | undefined;
let cleanupEvidence: TrialWaitEvidence | undefined;
let cleanup: Promise<TrialWaitEvidence> | undefined;
const terminate = () => {
cleanupAction ??= state.used ? 'abort' : 'terminate-unused';
cleanup ??= (async () => {
const evidence = await waitForTrial(state.child, {
phase: state.used ? 'abort' : 'unused',
deadlineMs: state.used ? RELAY_SETTLEMENT_DEADLINE_MS : TERM_SETTLEMENT_DEADLINE_MS,
});
if (evidence.outcome === 'unsettled') await state.closeRelay();
return evidence;
})();
return cleanup;
};
const onAbort = () => {
hostCancellationObserved = true;
void terminate();
};
signal?.addEventListener('abort', onAbort, { once: true });
if (signal?.aborted) onAbort();
const decide = () => {
if (decision) return true;
if (
!sendRelayMessage(state.transport, 'decision', { token: state.token, kind: 'verify' }, true)
) {
void terminate();
return false;
}
decision = true;
return true;
};
try {
value = await operation({
context: relayContext(state, signal),
verify: async () => {
if (!decide()) {
cleanupEvidence = await terminate();
finalizationEvidence = cleanupEvidence;
throw new Error('relay verify decision was not delivered');
}
const completed = cleanup
? await cleanup
: await waitForTrial(state.child, { phase: 'completion' });
finalizationEvidence = completed;
if (!finalizationConfirmed(completed)) throw new Error('Trial did not finalize cleanly');
const verification = await readVerification(
state,
cell,
framework,
Boolean(options.egressProxy),
);
verificationConfirmedBeforeCancellation = !hostCancellationObserved;
return verification;
},
});
hasValue = true;
} finally {
signal?.removeEventListener('abort', onAbort);
if (!decision || cleanup) {
cleanupEvidence = await terminate();
finalizationEvidence = cleanupEvidence;
}
await state.closeRelay();
}
if (
hasValue &&
(state.transport.failure || cleanupAction || state.diagnostic?.category !== 'none')
) {
value = {
...value!,
artifacts: [
...value!.artifacts,
...(state.transport.failure
? [{ kind: 'executor-relay', ...state.transport.failure }]
: []),
...(cleanupAction
? [
{
kind: 'executor-cleanup',
action: cleanupAction,
phase: cleanupEvidence!.phase,
deadlineMs: cleanupEvidence!.deadlineMs,
escalation: cleanupEvidence!.escalation,
outcome: cleanupEvidence!.outcome,
},
]
: []),
...(state.diagnostic && state.diagnostic.category !== 'none'
? [{ kind: 'executor-relay-result', ...state.diagnostic }]
: []),
],
};
}
if (hostCancellationObserved && !verificationConfirmedBeforeCancellation) {
return hasValue
? { kind: 'indeterminate', cause: 'host-cancelled', value }
: { kind: 'indeterminate', cause: 'host-cancelled' };
}
if (!finalizationEvidence || !finalizationConfirmed(finalizationEvidence)) {
return hasValue
? { kind: 'indeterminate', cause: 'cleanup-unconfirmed', value }
: { kind: 'indeterminate', cause: 'cleanup-unconfirmed' };
}
if (!hasValue) throw new Error('executor operation did not settle');
return { kind: 'settled', value };
}
function relayContext(state: RelayState, signal?: AbortSignal): SubjectExecutionContext {
const resultToken = randomBytes(16).toString('hex');
const metadata: JsonObject = {
trialName: state.trialName,
trialPath: state.trialPath,
meteringSecret: resultToken,
};
return {
cwd: state.cwd,
taskInput: state.taskInput,
metadata,
...(signal ? { signal } : {}),
execute: async (input) => {
signal?.throwIfAborted();
if (state.used) throw new Error('Trial already executed its subject');
state.used = true;
const credentials = Object.fromEntries(
Object.entries(input.credentialEnvironment).map(([target, source]) => {
const value = state.credentials[source];
if (value === undefined) throw new Error(`credential ${source} was not admitted`);
return [target, value];
}),
);
if (
!sendRelayMessage(state.transport, 'execute', {
token: state.token,
kind: 'execute',
command: input.command,
args: input.args,
environment: mergeExecutionEnvironment(
state.executionEnvironment,
input.environment ?? {},
),
credentials,
resultToken,
captureStdout: input.captureStdout ?? true,
})
) {
throw new Error('relay transport is unavailable');
}
state.transport.stage = 'receive';
let executed: Record<string, unknown>;
try {
executed = await readLine(state.lines);
} catch {
state.transport.failure ??= {
stage: 'receive',
category: 'protocol-error',
delivery: 'unknown',
};
throw new Error('relay execution result was unavailable');
}
if (
executed.token !== state.token ||
executed.kind !== 'executed' ||
(executed.termination !== 'exited' && executed.termination !== 'framework_timeout') ||
typeof executed.exitCode !== 'number' ||
typeof executed.stdout !== 'string' ||
!validProcessDiagnostic(executed.diagnostic)
) {
state.transport.failure ??= {
stage: 'receive',
category: 'protocol-error',
delivery: 'unknown',
};
throw new Error('relay returned an invalid execution result');
}
state.diagnostic = executed.diagnostic;
return {
termination: executed.termination,
exitCode: executed.exitCode,
stdout: executed.stdout,
diagnostic: executed.diagnostic,
};
},
};
}
function validProcessDiagnostic(value: unknown): value is {
category:
| 'none'
| 'unstructured-output'
| 'result-frame-missing'
| 'result-frame-invalid'
| 'result-frame-ambiguous'
| 'result-frame-oversize'
| 'execution-scope-unavailable';
bytes?: number;
sha256?: string;
} {
if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
const diagnostic = value as Record<string, unknown>;
const fields = Object.keys(diagnostic);
return (
(diagnostic.category === 'none' && fields.length === 1) ||
([
'unstructured-output',
'result-frame-missing',
'result-frame-invalid',
'result-frame-ambiguous',
'result-frame-oversize',
'execution-scope-unavailable',
].includes(String(diagnostic.category)) &&
fields.length === 3 &&
typeof diagnostic.bytes === 'number' &&
Number.isSafeInteger(diagnostic.bytes) &&
diagnostic.bytes >= 0 &&
typeof diagnostic.sha256 === 'string' &&
/^[0-9a-f]{64}$/u.test(diagnostic.sha256))
);
}
async function startTrial(
framework: HarnessFramework,
options: HarnessOptions,
specPath: string,
cell: ExperimentCell,
subjectCredentialNames: readonly string[],
signal?: AbortSignal,
): Promise<
| { readonly kind: 'ready'; readonly state: RelayState }
| Extract<ExecutorAttemptOutcome, { readonly kind: 'not_started' }>
> {
const credentials = requireCredentials(cell.subject.credentials);
const token = randomBytes(24).toString('hex');
const trialsRoot = resolve(process.env[options.trialsRootEnv]!);
await mkdir(trialsRoot, { recursive: true, mode: 0o700 });
await chmod(trialsRoot, 0o700);
const trialName = `${safeName(cell.id)}-${randomBytes(6).toString('hex')}`;
const configPath = join(trialsRoot, `${trialName}.json`);
const trialPath = join(trialsRoot, trialName);
const task = decodeTask(framework, options, cell);
const timeoutMultiplier = positive(cell.budget.timeoutMultiplier, 'budget.timeoutMultiplier');
const egressPaths = await resolveEgressPaths(options);
const environmentConfig = resolveEnvironmentConfig(options, egressPaths, framework, trialPath);
const networkPolicyPath = egressPaths?.networkPolicyPath;
const executionEnvironment = {
...UNATTENDED_EXECUTION_ENVIRONMENT,
...egressExecutionEnvironment(options.egressProxy),
};
const environment = createHarnessPreparationEnvironment({
subjectCredentialNames: [...subjectCredentialNames, ...cell.subject.credentials],
declared: options.preparationEnvironment,
...(options.egressProxy && networkPolicyPath
? {
egress: {
allowedHost: options.egressProxy.allowedHost,
networkPolicyPath,
},
}
: {}),
});
const server = createServer();
const connections = new Set<Socket>();
server.on('connection', (socket) => {
connections.add(socket);
socket.on('error', () => undefined);
socket.once('close', () => connections.delete(socket));
});
let child: ChildProcess | undefined;
let serverClosed: Promise<void> | undefined;
const stopServer = (destroyConnections = false) => {
serverClosed ??= closeServer(server);
if (destroyConnections) {
for (const socket of connections) socket.destroy();
}
return serverClosed;
};
let stage: 'spawn' | 'exit-before-ready' | 'ready-decode' = 'spawn';
try {
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const address = server.address();
if (!address || typeof address === 'string') throw new Error('relay did not bind TCP');
await writeFile(
configPath,
`${JSON.stringify({
task,
trial_name: trialName,
trials_dir: trialsRoot,
timeout_multiplier: timeoutMultiplier,
agent: {
import_path: 'relay_agent:RelayAgent',
kwargs: {
relay_host: '127.0.0.1',
relay_port: address.port,
relay_token: token,
teardown_timeout_ms: PYTHON_TEARDOWN_DEADLINE_MS,
},
},
environment: environmentConfig,
...(options.egressProxy
? {
artifacts: [
{
source: '/opt/maka-egress-state/hits.jsonl',
destination: EGRESS_AUDIT_DESTINATION,
service: 'maka-eval-mitmproxy',
},
],
}
: {}),
})}\n`,
{ flag: 'wx', mode: 0o600 },
);
child = spawn(
process.env[options.pythonPathEnv]!,
[
join(BUNDLED_HARNESS_RELAY_ROOT, 'run_trial.py'),
framework,
options.frameworkVersion,
configPath,
],
{ cwd: dirname(specPath), env: environment, stdio: 'ignore' },
);
await once(child, 'spawn', signal ? { signal } : undefined);
stage = 'exit-before-ready';
const exitedBeforeReady = once(child, 'exit').then(([code]) => {
throw new Error(`Trial exited before Agent.run (${code})`);
});
const connectionWait = new AbortController();
const connectionSignal = signal
? AbortSignal.any([signal, connectionWait.signal])
: connectionWait.signal;
let socket: Socket;
try {
socket = await Promise.race([
once(server, 'connection', { signal: connectionSignal }).then(
([connected]) => connected as Socket,
),
exitedBeforeReady,
]);
} finally {
connectionWait.abort();
}
const relayClosed = stopServer();
stage = 'ready-decode';
const transport = createRelayTransport(socket);
transport.stage = 'receive';
const lines = createInterface({ input: socket, crlfDelay: Number.POSITIVE_INFINITY })[
Symbol.asyncIterator
]();
const ready = await abortable(Promise.race([readLine(lines), exitedBeforeReady]), signal);
if (
ready.token !== token ||
ready.kind !== 'ready' ||
typeof ready.instruction !== 'string' ||
typeof ready.cwd !== 'string' ||
!ready.cwd.startsWith('/')
) {
throw new Error('relay returned an invalid ready message');
}
return {
kind: 'ready',
state: {
child,
transport,
closeRelay: async () => {
for (const connection of connections) connection.destroy();
await relayClosed;
},
lines,
token,
trialName,
trialPath,
taskInput: ready.instruction,
credentials,
cwd: ready.cwd,
executionEnvironment,
used: false,
},
};
} catch (error) {
const relayClosed = stopServer(true);
if (child?.pid !== undefined) {
await waitForTrial(child, {
phase: 'unused',
deadlineMs: TERM_SETTLEMENT_DEADLINE_MS,
});
}
await relayClosed;
await unlink(configPath).catch(() => undefined);
await mkdir(trialPath, { recursive: true, mode: 0o700 });
const diagnosticPath = 'preparation-error.json';
const code = preparationCode(stage, child?.exitCode ?? null, signal);
await writeFile(
join(trialPath, diagnosticPath),
`${JSON.stringify({
stage,
framework,
code,
errorCode: safeErrorCode(error),
exitCode: child?.exitCode ?? null,
signal: child?.signalCode ?? null,
})}\n`,
{ flag: 'wx', mode: 0o600 },
);
return notStarted(code, [
{ kind: 'executor-preparation', framework, trialName, path: diagnosticPath },
]);
}
}
function createRelayTransport(socket: Socket): RelayTransport {
const transport: RelayTransport = { socket, stage: 'ready' };
socket.on('error', (error: NodeJS.ErrnoException) => {
transport.failure ??= {
stage: transport.stage,
category: relayTransportCategory(error.code),
delivery: 'unknown',
};
});
return transport;
}
function sendRelayMessage(
transport: RelayTransport,
stage: RelayTransportStage,
value: Record<string, unknown>,
end = false,
): boolean {
transport.stage = stage;
const socket = transport.socket;
if (socket.destroyed || !socket.writable || socket.writableEnded || transport.failure) {
transport.failure = {
stage,
category: transport.failure?.category ?? 'peer-closed',
delivery: 'not-delivered',
};
return false;
}
try {
const payload = `${JSON.stringify(value)}\n`;
if (end) socket.end(payload);
else {
socket.write(payload, (error) => {
if (!error) return;
transport.failure = {
stage,
category: relayTransportCategory((error as NodeJS.ErrnoException).code),
delivery: 'unknown',
};
});
}
return true;
} catch (error) {
transport.failure = {
stage,
category: relayTransportCategory((error as NodeJS.ErrnoException).code),
delivery: 'not-delivered',
};
return false;
}
}
function relayTransportCategory(code: string | undefined): RelayTransportFailure['category'] {
if (code === 'EPIPE') return 'broken-pipe';
if (code === 'ECONNRESET') return 'connection-reset';
if (code === 'ERR_STREAM_WRITE_AFTER_END') return 'peer-closed';
return 'transport-error';
}
function notStarted(
code: ExecutorPreparationCode,
artifacts: readonly JsonObject[] = [],
): Extract<ExecutorAttemptOutcome, { readonly kind: 'not_started' }> {
return { kind: 'not_started', code, artifacts };
}
function preparationCode(
stage: 'spawn' | 'exit-before-ready' | 'ready-decode',
exitCode: number | null,
signal?: AbortSignal,
): ExecutorPreparationCode {
if (signal?.aborted) return 'cancelled';
if (stage === 'exit-before-ready' && exitCode === 78) return 'framework-version-mismatch';
if (stage === 'spawn') return 'spawn-failed';
if (stage === 'ready-decode') return 'invalid-ready';
return 'exit-before-ready';
}
function mergeExecutionEnvironment(
required: Readonly<Record<string, string>>,
subject: Readonly<Record<string, string>>,
): Record<string, string> {
const overlap = Object.keys(required).filter((name) => Object.hasOwn(subject, name));
if (overlap.length > 0) {
throw new Error(
`subject environment overrides Eval execution environment: ${overlap.join(', ')}`,
);
}
return { ...subject, ...required };
}
// Every subject runs unattended in a fresh container, where a package manager
// that stops to ask a question is indistinguishable from one that hung. That is
// a property of the environment, not of any one arm: tasks install packages, and
// subjects only decide when.
const UNATTENDED_EXECUTION_ENVIRONMENT: Readonly<Record<string, string>> = {
DEBIAN_FRONTEND: 'noninteractive',
TZ: 'Etc/UTC',
};
function egressExecutionEnvironment(
options: HarnessOptions['egressProxy'],
): Readonly<Record<string, string>> {
if (!options) return {};
const noProxy = '127.0.0.1,localhost';
return {
HTTP_PROXY: options.proxyUrl,
HTTPS_PROXY: options.proxyUrl,
http_proxy: options.proxyUrl,
https_proxy: options.proxyUrl,
NO_PROXY: noProxy,
no_proxy: noProxy,
SSL_CERT_FILE: options.containerCaPath,
REQUESTS_CA_BUNDLE: options.containerCaPath,
CURL_CA_BUNDLE: options.containerCaPath,
GIT_SSL_CAINFO: options.containerCaPath,
NODE_EXTRA_CA_CERTS: options.containerCaPath,
};
}
function safeErrorCode(error: unknown): string | null {
const code = error instanceof Error ? (error as NodeJS.ErrnoException).code : undefined;
return code && ['ENOENT', 'EACCES', 'EPERM'].includes(code) ? code : null;
}
async function closeServer(server: Server): Promise<void> {
if (!server.listening) return;
await new Promise<void>((resolveClose, rejectClose) => {
server.close((error) => (error ? rejectClose(error) : resolveClose()));
});
}
export const EGRESS_AUDIT_DESTINATION = 'egress-hits.jsonl';
export const EGRESS_AUDIT_ARTIFACT_PATH = `artifacts/${EGRESS_AUDIT_DESTINATION}`;
export function collectEgressAuditArtifact(
audit: Buffer | undefined,
expected: boolean,
): {
readonly missing: boolean;
readonly failureReason: string | null;
readonly artifacts: readonly JsonObject[];
} {
if (!expected) return { missing: false, failureReason: null, artifacts: [] };
if (audit === undefined) {
return {
missing: true,
failureReason: 'egress audit log missing',
artifacts: [{ kind: 'egress-audit-missing', path: EGRESS_AUDIT_ARTIFACT_PATH }],
};
}
const forensics = inspectEgressAudit(audit);
return {
missing: false,
failureReason: null,
artifacts: [
{
kind: 'egress-audit',
path: EGRESS_AUDIT_ARTIFACT_PATH,
bytes: audit.byteLength,
sha256: `sha256:${createHash('sha256').update(audit).digest('hex')}`,
truncated: forensics.truncated,
policyErrorCount: forensics.policyErrorCount,
malformedLineCount: forensics.malformedLineCount,
},
],
};
}
function inspectEgressAudit(audit: Buffer): {
readonly truncated: boolean;
readonly policyErrorCount: number;
readonly malformedLineCount: number;
} {
let truncated = false;
let policyErrorCount = 0;
let malformedLineCount = 0;
for (const line of audit.toString('utf8').split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed) continue;
let record: unknown;
try {
record = JSON.parse(trimmed);
} catch {
malformedLineCount += 1;
continue;
}
if (!record || typeof record !== 'object' || Array.isArray(record)) {
malformedLineCount += 1;
continue;
}
const ruleId = (record as { ruleId?: unknown }).ruleId;
if (ruleId === 'audit_truncated') truncated = true;
if (ruleId === 'policy_error') policyErrorCount += 1;
}
return { truncated, policyErrorCount, malformedLineCount };
}
async function readVerification(
state: RelayState,
cell: ExperimentCell,
framework: HarnessFramework,
expectEgressAudit: boolean,
): Promise<ExecutorVerification> {
const result = JSON.parse(await readFile(join(state.trialPath, 'result.json'), 'utf8')) as {
exception_info?: { exception_type?: unknown } | null;
verifier_result?: { rewards?: Record<string, number> | null } | null;
};
const score = result.verifier_result?.rewards?.[rewardKey(cell)] ?? null;
const subjectException = ['AgentTimeoutError', 'NonZeroAgentExitCodeError'].includes(
String(result.exception_info?.exception_type),
);
if (result.exception_info && !subjectException) {
throw new Error('Trial failed outside subject execution');
}
const egressAuditPath = join(state.trialPath, EGRESS_AUDIT_ARTIFACT_PATH);
let egressAudit: Buffer | undefined;
try {
egressAudit = await readFile(egressAuditPath);
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (expectEgressAudit && code !== 'ENOENT') {
return {
status: 'infra_failed',
score,
failureReason: `failed to read egress audit log ${egressAuditPath}${code ? ` (${code})` : ''}`,
artifacts: [
{ kind: 'trial', framework: cell.executor.kind, trialName: state.trialName },
...(await collectedArtifactInventory(state.trialPath, framework)),
{ kind: 'egress-audit-unreadable', path: EGRESS_AUDIT_ARTIFACT_PATH },
],
};
}
}
const audit = collectEgressAuditArtifact(egressAudit, expectEgressAudit);
return {
status: audit.failureReason
? 'infra_failed'
: score === null
? 'infra_failed'
: subjectException
? 'subject_failed'
: 'completed',
score,
failureReason: audit.failureReason ?? (score === null ? 'verifier produced no reward' : null),
artifacts: [
{ kind: 'trial', framework: cell.executor.kind, trialName: state.trialName },
...(await collectedArtifactInventory(state.trialPath, framework)),
...audit.artifacts,
],
};
}
async function collectedArtifactInventory(
trialPath: string,
framework: HarnessFramework,
): Promise<JsonObject[]> {
const root =
framework === 'pier'
? join(trialPath, 'artifacts')
: join(trialPath, 'artifacts', 'logs', 'artifacts');
const files: JsonObject[] = [];
const targets = [
join(root, basename(MAKA_RUNTIME_ARTIFACT_PATH)),
join(root, basename(MAKA_SUBJECT_STDOUT_PATH)),
join(root, basename(MAKA_SUBJECT_STDERR_PATH)),
];
for (const target of targets) {
await walkCollectedArtifacts(trialPath, target, files).catch((error: NodeJS.ErrnoException) => {
if (error.code !== 'ENOENT') throw error;
});
}
return files.sort((left, right) => String(left.path).localeCompare(String(right.path)));
}
async function walkCollectedArtifacts(
trialPath: string,
current: string,
files: JsonObject[],
): Promise<void> {
const metadata = await lstat(current);
if (metadata.isSymbolicLink()) return;
if (metadata.isFile()) {
const hash = createHash('sha256');
for await (const chunk of createReadStream(current)) hash.update(chunk as Buffer);
files.push({
kind: 'collected-artifact',
path: relative(trialPath, current).split(sep).join('/'),
bytes: metadata.size,
sha256: `sha256:${hash.digest('hex')}`,
});
return;
}
if (!metadata.isDirectory()) return;
for (const entry of await readdir(current, { withFileTypes: true })) {
const path = join(current, entry.name);
if (entry.isSymbolicLink()) continue;
await walkCollectedArtifacts(trialPath, path, files);
}
}
export interface HarnessOptions {
readonly frameworkVersion: string;
readonly pythonPathEnv: string;
readonly trialsRootEnv: string;
readonly tasksRootEnv?: string;
readonly environment: JsonObject;
readonly preparationEnvironment: readonly string[];
readonly egressProxy?: {
readonly composeSourceEnv: string;
readonly composeRelativePath: string;
readonly networkPolicyRelativePath: string;
readonly proxyUrl: string;
readonly allowedHost: string;
readonly containerCaPath: string;
};
readonly mounts: readonly {
readonly sourceEnv: string;
readonly target: string;
readonly readOnly: true;
}[];
}
function decodeHarnessOptions(value: JsonObject, framework: HarnessFramework): HarnessOptions {
if (!Object.hasOwn(value, 'preparationEnvironment')) {
throw new Error('executor.config.preparationEnvironment is required');
}
const fields = [
'frameworkVersion',
'pythonPathEnv',
'trialsRootEnv',
'environment',
'preparationEnvironment',
'mounts',
];
// Only the Harbor branch of run_trial.py applies the namespace policy, so a
// pier spec declaring egressProxy would set the proxy up and inject its
// environment while enforcement silently did not exist.
if (framework === 'pier' && Object.hasOwn(value, 'egressProxy')) {
throw new Error(
'executor.config.egressProxy is Harbor-only: pier does not apply the subject namespace policy',
);
}
if (Object.hasOwn(value, 'egressProxy')) fields.push('egressProxy');
if (framework === 'pier') fields.push('tasksRootEnv');
const options = exact(value, fields, 'executor.config');
const preparationEnvironment = array(
options.preparationEnvironment,
'preparationEnvironment',
).map((name, index) => machinePathEnv(name, `preparationEnvironment[${index}]`));
if (new Set(preparationEnvironment).size !== preparationEnvironment.length) {
throw new Error('preparationEnvironment must contain unique names');
}
const decoded: HarnessOptions = {
frameworkVersion: text(options.frameworkVersion, 'frameworkVersion'),
pythonPathEnv: machinePathEnv(options.pythonPathEnv, 'pythonPathEnv'),
trialsRootEnv: machinePathEnv(options.trialsRootEnv, 'trialsRootEnv'),
environment: decodeJsonObject(options.environment, 'environment'),
preparationEnvironment,
...(Object.hasOwn(options, 'egressProxy')
? { egressProxy: decodeEgressProxy(options.egressProxy) }
: {}),
mounts: array(options.mounts, 'mounts').map((mount, index) => decodeMount(mount, index)),
...(framework === 'pier'
? { tasksRootEnv: machinePathEnv(options.tasksRootEnv, 'tasksRootEnv') }
: {}),
};
if (framework === 'pier') {
const reservedTargets = PIER_FRAMEWORK_LOG_MOUNTS.map((mount) => mount.target);
const collision = decoded.mounts.find((mount) => {
const target = posix.normalize(mount.target);
return reservedTargets.some(
(reserved) => target === reserved || target.startsWith(`${reserved}/`),
);
});
if (collision) {
throw new Error(`Pier mount target ${collision.target} is reserved for framework logs`);
}
}
for (const name of [
decoded.pythonPathEnv,
decoded.trialsRootEnv,
decoded.tasksRootEnv,
decoded.egressProxy?.composeSourceEnv,
]) {
if (name && !process.env[name]) throw new Error(`machine path ${name} is unavailable`);
}
return decoded;
}
function decodeEgressProxy(value: unknown): NonNullable<HarnessOptions['egressProxy']> {
const proxy = exact(
value,
[
'composeSourceEnv',
'composeRelativePath',
'networkPolicyRelativePath',
'proxyUrl',
'allowedHost',
'containerCaPath',
],
'egressProxy',
);
const proxyUrl = text(proxy.proxyUrl, 'egressProxy.proxyUrl');
if (!URL.canParse(proxyUrl) || new URL(proxyUrl).protocol !== 'http:') {
throw new Error('egressProxy.proxyUrl must be an HTTP proxy URL');
}
return {
composeSourceEnv: machinePathEnv(proxy.composeSourceEnv, 'egressProxy.composeSourceEnv'),
composeRelativePath: relativePath(proxy.composeRelativePath, 'egressProxy.composeRelativePath'),
networkPolicyRelativePath: relativePath(
proxy.networkPolicyRelativePath,
'egressProxy.networkPolicyRelativePath',