File size: 19,025 Bytes
2c2dc59 | 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 | import { existsSync } from 'fs'
import { mkdir, mkdtemp, readFile, writeFile } from 'fs/promises'
import { dirname, join } from 'path'
import { tmpdir } from 'os'
import { describe, expect, test } from 'bun:test'
import { runSourceTaskLoop } from './sourceTaskLoop.js'
import type {
JudgeRunner,
SourceAgentSession,
SourceAgentTurnInput,
} from './types.js'
async function makeTask(root: string, taskId: string, withRuntime = false): Promise<void> {
const taskDir = join(root, taskId)
await mkdir(join(taskDir, 'visible_data'), { recursive: true })
await mkdir(join(taskDir, 'evaluation'), { recursive: true })
await writeFile(join(taskDir, 'README.md'), '# Demo\n', 'utf8')
await writeFile(join(taskDir, 'visible_data', 'cases.json'), '[]', 'utf8')
await writeFile(join(taskDir, 'evaluation', 'judge.py'), '', 'utf8')
if (withRuntime) {
const pythonRel =
process.platform === 'win32'
? 'envs/runtime/.venv/Scripts/python.exe'
: 'envs/runtime/.venv-posix/bin/python'
const pythonAbs = join(taskDir, ...pythonRel.split('/'))
await mkdir(dirname(pythonAbs), { recursive: true })
await writeFile(pythonAbs, '', 'utf8')
await mkdir(join(taskDir, 'envs'), { recursive: true })
await writeFile(
join(taskDir, 'envs', 'env_manifest.json'),
JSON.stringify({
default_env: 'runtime',
envs: {
runtime: {
python: {
[process.platform === 'win32' ? 'windows' : 'posix']: pythonRel,
},
},
},
}),
'utf8',
)
}
await writeFile(
join(taskDir, 'task_manifest.json'),
JSON.stringify({
version: 1,
task_id: taskId,
public_bundle: withRuntime
? ['README.md', 'visible_data/', 'envs/']
: ['README.md', 'visible_data/'],
private_judge_bundle: ['evaluation/'],
entrypoints: withRuntime ? { environment: 'envs/env_manifest.json' } : {},
submission: { output_dir: 'outputs' },
}),
'utf8',
)
}
describe('runSourceTaskLoop', () => {
test('interrupts and closes agent event generator when agent inference times out', async () => {
const root = await mkdtemp(join(tmpdir(), 'source-loop-timeout-close-'))
const tasksDir = join(root, 'tasks')
const runsDir = join(root, 'runs')
await makeTask(tasksDir, 'timeout_close_task', true)
let generatorClosed = false
let interrupted = false
let disposed = false
let releaseGenerator!: () => void
async function* hangingSubmit() {
try {
await new Promise<void>(resolve => {
releaseGenerator = resolve
})
} finally {
generatorClosed = true
}
}
const result = await runSourceTaskLoop({
taskId: 'timeout_close_task',
tasksDir,
runsDir,
maxRounds: 1,
timeoutSeconds: 1,
sessionDisposeGraceMs: 50,
sessionFactory: async () => ({
submit: hangingSubmit,
interrupt() {
interrupted = true
releaseGenerator()
},
async dispose() {
disposed = true
},
}),
judge: {
async run() {
throw new Error('judge should not run')
},
},
})
expect(result.status).toBe('timeout')
expect(generatorClosed).toBe(true)
expect(interrupted).toBe(true)
expect(disposed).toBe(true)
})
test('does not hang forever when session dispose never resolves', async () => {
const root = await mkdtemp(join(tmpdir(), 'source-loop-dispose-hang-'))
const tasksDir = join(root, 'tasks')
const runsDir = join(root, 'runs')
await makeTask(tasksDir, 'dispose_hang_task', true)
const result = await runSourceTaskLoop({
taskId: 'dispose_hang_task',
tasksDir,
runsDir,
maxRounds: 1,
timeoutSeconds: 1,
sessionDisposeGraceMs: 50,
sessionFactory: async () => ({
async *submit() {
throw new Error('force dispose path')
},
async dispose() {
await new Promise(() => {})
},
}),
judge: {
async run() {
throw new Error('judge should not run')
},
},
})
expect(result.status).toBe('failed')
const events = await readFile(join(result.run.logsDir, 'run_events.jsonl'), 'utf8')
expect(events).toContain('session_dispose_timeout')
})
test('uses one source agent session across multiple judge feedback turns', async () => {
const root = await mkdtemp(join(tmpdir(), 'source-loop-'))
const tasksDir = join(root, 'tasks')
const runsDir = join(root, 'runs')
await makeTask(tasksDir, 'demo_task', true)
const prompts: string[] = []
const startMaxTurns: Array<number | undefined> = []
const turnMaxTurns: Array<number | undefined> = []
const judgeRuntimePythons: string[] = []
const sessionRuntimePythons: string[] = []
let sessionCreations = 0
let disposed = false
const session: SourceAgentSession = {
async *submit(input: SourceAgentTurnInput) {
prompts.push(input.prompt)
turnMaxTurns.push(input.maxTurnsPerRound)
sessionRuntimePythons.push(input.runtime.python)
yield { type: 'assistant_text', text: `turn ${prompts.length}` }
yield {
type: 'finalize',
summary: 'ready',
files: ['outputs/case_000.npz'],
}
},
async dispose() {
disposed = true
},
}
const judge: JudgeRunner = {
async run(input) {
judgeRuntimePythons.push(input.runtime.python)
return prompts.length < 3
? {
status: 'fail',
reward: 0,
feedback: `missing final detail ${prompts.length}`,
raw: { status: 'fail' },
}
: {
status: 'pass',
reward: 1,
feedback: 'ok',
raw: { status: 'pass' },
}
},
}
const result = await runSourceTaskLoop({
taskId: 'demo_task',
tasksDir,
runsDir,
maxRounds: 3,
maxTurnsPerRound: 7,
timeoutSeconds: 30,
sessionFactory: async input => {
sessionCreations++
startMaxTurns.push(input.maxTurnsPerRound)
return session
},
judge,
})
expect(result.status).toBe('success')
expect(result.rounds).toBe(3)
expect(sessionCreations).toBe(1)
expect(startMaxTurns).toEqual([7])
expect(turnMaxTurns).toEqual([7, 7, 7])
expect(prompts).toHaveLength(3)
expect(prompts[0]).toContain('round_plan_file: workspace/plans/round_01.md')
expect(prompts[0]).toContain('# Demo')
expect(prompts[1]).toContain('<judge_feedback>')
expect(prompts[1]).toContain('message: missing final detail 1')
expect(prompts[1]).toContain('workspace/plans/round_02.md')
expect(prompts[2]).toContain('message: missing final detail 2')
expect(prompts[2]).toContain('workspace/plans/round_03.md')
expect(new Set(sessionRuntimePythons).size).toBe(1)
expect(judgeRuntimePythons).toEqual(sessionRuntimePythons)
expect(disposed).toBe(true)
expect(existsSync(join(result.run.logsDir, 'trajectory.clean.jsonl'))).toBe(true)
const clean = await readFile(join(result.run.logsDir, 'trajectory.clean.jsonl'), 'utf8')
expect(clean).toContain('"kind":"judge_result"')
expect(clean).not.toContain('result_path')
expect(clean).not.toContain('.judge_private')
expect(clean).not.toContain('"system_prompt"')
const raw = await readFile(join(result.run.logsDir, 'trajectory.raw.jsonl'), 'utf8')
expect(raw).toContain('"kind":"judge_result_raw"')
})
test('returns infra_error before creating a session when runtime is missing', async () => {
const root = await mkdtemp(join(tmpdir(), 'source-loop-infra-'))
const tasksDir = join(root, 'tasks')
const runsDir = join(root, 'runs')
await makeTask(tasksDir, 'broken_runtime', false)
await mkdir(join(tasksDir, 'broken_runtime', 'envs'), { recursive: true })
await writeFile(
join(tasksDir, 'broken_runtime', 'envs', 'env_manifest.json'),
JSON.stringify({
default_env: 'runtime',
envs: {
runtime: {
python: {
windows: 'envs/runtime/.venv/Scripts/python.exe',
posix: 'envs/runtime/.venv/bin/python',
},
},
},
}),
'utf8',
)
const manifestPath = join(tasksDir, 'broken_runtime', 'task_manifest.json')
const manifest = JSON.parse(await readFile(manifestPath, 'utf8'))
manifest.public_bundle.push('envs/')
manifest.entrypoints = { environment: 'envs/env_manifest.json' }
await writeFile(manifestPath, JSON.stringify(manifest), 'utf8')
let sessionCreations = 0
const result = await runSourceTaskLoop({
taskId: 'broken_runtime',
tasksDir,
runsDir,
maxRounds: 1,
timeoutSeconds: 30,
sessionFactory: async () => {
sessionCreations++
throw new Error('should not create session')
},
judge: {
async run() {
throw new Error('judge should not run')
},
},
})
expect(result.status).toBe('infra_error')
expect(sessionCreations).toBe(0)
expect(result.lastJudgeResult).toBeUndefined()
})
test('does not impose a per-round turn cap unless explicitly requested', async () => {
const root = await mkdtemp(join(tmpdir(), 'source-loop-unlimited-'))
const tasksDir = join(root, 'tasks')
const runsDir = join(root, 'runs')
await makeTask(tasksDir, 'unlimited_task', true)
const startMaxTurns: Array<number | undefined> = []
const turnMaxTurns: Array<number | undefined> = []
const result = await runSourceTaskLoop({
taskId: 'unlimited_task',
tasksDir,
runsDir,
maxRounds: 1,
timeoutSeconds: 30,
sessionFactory: async input => {
startMaxTurns.push(input.maxTurnsPerRound)
return {
async *submit(turnInput: SourceAgentTurnInput) {
turnMaxTurns.push(turnInput.maxTurnsPerRound)
yield { type: 'finalize', summary: 'ready', files: [] }
},
}
},
judge: {
async run() {
return {
status: 'pass',
reward: 1,
feedback: 'ok',
raw: { status: 'pass' },
}
},
},
})
expect(result.status).toBe('success')
expect(startMaxTurns).toEqual([undefined])
expect(turnMaxTurns).toEqual([undefined])
})
test('requests same-session recovery when an agent turn ends without finalize', async () => {
const root = await mkdtemp(join(tmpdir(), 'source-loop-recovery-'))
const tasksDir = join(root, 'tasks')
const runsDir = join(root, 'runs')
await makeTask(tasksDir, 'recovery_task', true)
const prompts: string[] = []
let sessionCreations = 0
let judgeCalls = 0
const result = await runSourceTaskLoop({
taskId: 'recovery_task',
tasksDir,
runsDir,
maxRounds: 1,
timeoutSeconds: 30,
sessionFactory: async () => {
sessionCreations++
return {
async *submit(input: SourceAgentTurnInput) {
prompts.push(input.prompt)
if (prompts.length === 1) {
yield {
type: 'agent_result',
subtype: 'success',
stopReason: 'end_turn',
durationMs: 10,
usage: { input_tokens: 12, output_tokens: 3 },
} as never
return
}
yield { type: 'assistant_text', text: 'Recovering by submitting output.' }
yield {
type: 'finalize',
summary: 'ready after recovery',
files: ['outputs/case_000.npz'],
}
},
}
},
judge: {
async run() {
judgeCalls++
return {
status: 'pass',
reward: 1,
feedback: 'ok',
raw: { status: 'pass' },
}
},
},
})
expect(result.status).toBe('success')
expect(result.rounds).toBe(1)
expect(sessionCreations).toBe(1)
expect(judgeCalls).toBe(1)
expect(prompts).toHaveLength(2)
expect(prompts[1]).toContain('<no_finalize_recovery>')
expect(prompts[1]).toContain('call finalize_submission now')
const events = await readFile(join(result.run.logsDir, 'run_events.jsonl'), 'utf8')
expect(events).toContain('"type":"agent_recovery_started"')
expect(events).toContain('"type":"agent_recovery_finished"')
const clean = await readFile(join(result.run.logsDir, 'trajectory.clean.jsonl'), 'utf8')
expect(clean).toContain('"kind":"agent_result"')
expect(clean).toContain('"stop_reason":"end_turn"')
expect(clean).toContain('"kind":"recovery_started"')
expect(clean).toContain('"kind":"recovery_finished"')
expect(clean).toContain('"finalized":true')
expect(clean).toContain('ready after recovery')
})
test('does not judge or consume a round when validation never passes', async () => {
const root = await mkdtemp(join(tmpdir(), 'source-loop-validation-fail-'))
const tasksDir = join(root, 'tasks')
const runsDir = join(root, 'runs')
await makeTask(tasksDir, 'validation_fail_task', true)
let judgeCalls = 0
const result = await runSourceTaskLoop({
taskId: 'validation_fail_task',
tasksDir,
runsDir,
maxRounds: 1,
timeoutSeconds: 30,
llmOptions: { temperature: 1, thinking: 'disabled' },
sessionFactory: async () => ({
async *submit(input: SourceAgentTurnInput) {
if (input.prompt.includes('<no_finalize_recovery>')) return
yield {
type: 'run_warning',
code: 'missing_round_plan',
message: 'workspace/plans/round_01.md is missing.',
}
yield {
type: 'submission_validation_failed',
result: {
ok: false,
normalizedFiles: [],
issues: [
{
code: 'missing_output_file',
path: 'outputs/case_000.npz',
message: 'outputs/case_000.npz is missing',
},
],
},
}
},
}),
judge: {
async run() {
judgeCalls++
throw new Error('judge should not run')
},
},
})
expect(result.status).toBe('failed')
expect(result.rounds).toBe(0)
expect(judgeCalls).toBe(0)
const summary = JSON.parse(
await readFile(join(result.run.logsDir, 'run_summary.json'), 'utf8'),
)
expect(summary.run_metadata.temperature_configured).toBe(1)
expect(summary.run_metadata.temperature_sent).toBe(1)
expect(summary.validation_attempts).toHaveLength(1)
expect(summary.validation_attempts[0].ok).toBe(false)
expect(summary.warnings).toHaveLength(1)
expect(summary.warnings[0].code).toBe('missing_round_plan')
const events = await readFile(join(result.run.logsDir, 'run_events.jsonl'), 'utf8')
expect(events).toContain('"type":"submission_validation_failed"')
expect(events).toContain('"type":"run_warning"')
const clean = await readFile(join(result.run.logsDir, 'trajectory.clean.jsonl'), 'utf8')
expect(clean).toContain('"kind":"submission_validation_failed"')
expect(clean).toContain('"kind":"trajectory_warning"')
})
test('invalid validation followed by valid finalize consumes one judge round', async () => {
const root = await mkdtemp(join(tmpdir(), 'source-loop-validation-retry-'))
const tasksDir = join(root, 'tasks')
const runsDir = join(root, 'runs')
await makeTask(tasksDir, 'validation_retry_task', true)
let judgeCalls = 0
const result = await runSourceTaskLoop({
taskId: 'validation_retry_task',
tasksDir,
runsDir,
maxRounds: 2,
timeoutSeconds: 30,
sessionFactory: async () => ({
async *submit() {
yield {
type: 'submission_validation_failed',
result: {
ok: false,
normalizedFiles: [],
issues: [
{
code: 'shape_mismatch',
path: 'outputs/case_000.npz',
key: 'reconstruction',
message: 'shape mismatch',
},
],
},
}
yield {
type: 'submission_validation_passed',
result: {
ok: true,
normalizedFiles: ['outputs/case_000.npz'],
issues: [],
},
}
yield {
type: 'finalize',
summary: 'ready after retry',
files: ['outputs/case_000.npz'],
}
},
}),
judge: {
async run() {
judgeCalls++
return {
status: 'pass',
reward: 1,
feedback: 'ok',
raw: { status: 'pass' },
}
},
},
})
expect(result.status).toBe('success')
expect(result.rounds).toBe(1)
expect(judgeCalls).toBe(1)
const summary = JSON.parse(
await readFile(join(result.run.logsDir, 'run_summary.json'), 'utf8'),
)
expect(summary.validation_attempts.map((attempt: { ok: boolean }) => attempt.ok)).toEqual([
false,
true,
])
})
test('stops draining agent events immediately after finalize', async () => {
const root = await mkdtemp(join(tmpdir(), 'source-loop-finalize-terminal-'))
const tasksDir = join(root, 'tasks')
const runsDir = join(root, 'runs')
await makeTask(tasksDir, 'finalize_terminal_task', true)
const result = await runSourceTaskLoop({
taskId: 'finalize_terminal_task',
tasksDir,
runsDir,
maxRounds: 1,
timeoutSeconds: 30,
sessionFactory: async () => ({
async *submit() {
yield {
type: 'submission_validation_passed',
result: {
ok: true,
normalizedFiles: ['outputs/case_000.npz'],
issues: [],
},
}
yield {
type: 'finalize',
summary: 'ready',
files: ['outputs/case_000.npz'],
}
yield {
type: 'assistant_text',
text: 'BUG: this event should not be consumed after finalize.',
}
},
}),
judge: {
async run() {
return {
status: 'pass',
reward: 1,
feedback: 'ok',
raw: { status: 'pass' },
}
},
},
})
expect(result.status).toBe('success')
const clean = await readFile(join(result.run.logsDir, 'trajectory.clean.jsonl'), 'utf8')
expect(clean).toContain('"kind":"finalize"')
expect(clean).not.toContain('BUG: this event should not be consumed')
})
})
|