-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker_sandbox_runner.py
More file actions
2320 lines (2237 loc) · 104 KB
/
Copy pathdocker_sandbox_runner.py
File metadata and controls
2320 lines (2237 loc) · 104 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
from __future__ import annotations
import hashlib
import json
import subprocess
import time
import urllib.error
import urllib.request
from datetime import UTC, datetime
from pathlib import Path
from uuid import uuid4
from app.domain.sandbox import (
DeliverableSandboxReport,
SandboxAvailability,
SandboxExecutionResult,
SandboxFailureStage,
SandboxExecutionStatus,
)
from app.domain.task_agent import TaskAgentServiceSpec
from app.domain.workflow import WorkflowRun
from app.services.assignment_workspace_manager import AssignmentWorkspaceManager
from app.services.artifact_materializer import (
ArtifactMaterializer,
DELIVERABLE_MANIFEST_RELATIVE_PATH,
VISIBLE_CHECK_SCRIPT_RELATIVE_PATH,
deliverable_grader_dir,
deliverable_visible_checks_dir,
)
from app.services.coursegen_logging import log_coursegen_event
from app.services.dependency_contract_materializer import DependencyContractMaterializer
from app.services.generated_test_harness import GeneratedTestScriptRunner
from app.services.learner_studio_service import LearnerStudioService, RuntimeImageBuildError
class DockerSandboxRunner:
def __init__(
self,
*,
docker_binary: str = "docker",
build_timeout_s: int = 600,
run_timeout_s: int = 600,
keep_image: bool = False,
cache_images: bool = True,
cache_namespace: str = "course-gen-cache",
workspace_manager: AssignmentWorkspaceManager | None = None,
dependency_contract_materializer: DependencyContractMaterializer | None = None,
) -> None:
self.docker_binary = docker_binary
self.build_timeout_s = build_timeout_s
self.run_timeout_s = run_timeout_s
self.keep_image = keep_image
self.cache_images = cache_images
self.cache_namespace = cache_namespace
self.workspace_manager = workspace_manager
# start_timeout_s gates how long `_wait_for_http` polls /health
# before giving up. Rails `bundle install` on aarch64 with
# native extensions (nokogiri, sqlite3, puma, bootsnap, psych)
# consistently takes 5-7 min on a cold cache. The prior 90s/300s
# caps caused timeouts at "Installing rdoc 7.2.0" — near the END
# of a successful install. The timeout-aware summarizer makes
# genuine timeouts identifiable; the 600s cap lets the heaviest
# stack we currently support (Rails) complete first-run installs
# with margin. Faster stacks (Go ~1min, Python ~2min) finish
# well before the cap.
self.runtime_harness = LearnerStudioService(
docker_binary=docker_binary,
build_timeout_s=build_timeout_s,
start_timeout_s=min(run_timeout_s, 600),
host="127.0.0.1",
)
self.test_script_runner = GeneratedTestScriptRunner(command_timeout_s=min(run_timeout_s, 600))
self.dependency_contract_materializer = dependency_contract_materializer or DependencyContractMaterializer(
docker_binary=docker_binary,
command_timeout_s=min(build_timeout_s, 600),
)
def status(self) -> SandboxAvailability:
try:
version = subprocess.run(
[self.docker_binary, "info", "--format", "{{json .ServerVersion}}"],
check=False,
capture_output=True,
text=True,
timeout=20,
)
except (OSError, subprocess.TimeoutExpired) as exc:
return SandboxAvailability(
available=False,
message=f"Docker sandbox unavailable: {exc}",
)
if version.returncode != 0:
detail = (version.stderr or version.stdout).strip() or "docker info failed"
return SandboxAvailability(
available=False,
message=f"Docker sandbox unavailable: {detail}",
)
return SandboxAvailability(
available=True,
message="Docker daemon is available for assignment sandbox execution.",
docker_version=version.stdout.strip().strip('"') or None,
)
def execute(self, run: WorkflowRun) -> SandboxExecutionResult:
availability = self.status()
started = time.perf_counter()
now = datetime.now(UTC)
log_coursegen_event(
"sandbox_execute_started",
workflow_run_id=run.id,
title=run.title,
docker_available=availability.available,
)
if run.artifacts.task_agent_spec is None:
result = SandboxExecutionResult(
status=SandboxExecutionStatus.unavailable,
available=availability.available,
generated_at=now,
duration_ms=0,
error="Sandbox execution only supports task-agent workflow runs.",
)
log_coursegen_event(
"sandbox_execute_completed",
workflow_run_id=run.id,
title=run.title,
sandbox_status=result.status.value,
error=result.error,
duration_ms=result.duration_ms,
)
return result
if not availability.available:
result = SandboxExecutionResult(
status=SandboxExecutionStatus.unavailable,
available=False,
generated_at=now,
duration_ms=0,
error=availability.message,
)
log_coursegen_event(
"sandbox_execute_completed",
workflow_run_id=run.id,
title=run.title,
sandbox_status=result.status.value,
error=result.error,
duration_ms=result.duration_ms,
)
return result
try:
bundle = self._materialize_workspace(run)
workspace_root = Path(bundle.public_dir)
log_coursegen_event(
"sandbox_workspace_ready",
workflow_run_id=run.id,
title=run.title,
workspace_root=str(workspace_root),
)
starter_root = workspace_root / "starter"
if starter_root.exists():
result = self._execute_starter_harness(
workspace_root=workspace_root,
spec=run.artifacts.task_agent_spec,
workflow_run_id=run.id,
now=now,
started=started,
)
else:
result = self._execute_legacy_runtime(
workspace_root=workspace_root,
now=now,
started=started,
)
log_coursegen_event(
"sandbox_execute_completed",
workflow_run_id=run.id,
title=run.title,
sandbox_status=result.status.value,
build_succeeded=result.build_succeeded,
run_succeeded=result.run_succeeded,
deliverable_report_count=len(result.deliverable_reports),
duration_ms=result.duration_ms,
error=result.error,
)
return result
except subprocess.TimeoutExpired as exc:
result = SandboxExecutionResult(
status=SandboxExecutionStatus.failed,
available=True,
build_succeeded=False,
build_cached=False,
run_succeeded=False,
generated_at=now,
duration_ms=int((time.perf_counter() - started) * 1000),
workspace_root=None,
image_tag=None,
cache_key=None,
build_command=[],
run_command=[],
build_stdout=self._coerce_bytes(getattr(exc, "stdout", b"")),
build_stderr=self._coerce_bytes(getattr(exc, "stderr", b"")),
error=f"Docker sandbox timed out: {exc}",
)
log_coursegen_event(
"sandbox_execute_completed",
workflow_run_id=run.id,
title=run.title,
sandbox_status=result.status.value,
build_succeeded=result.build_succeeded,
run_succeeded=result.run_succeeded,
duration_ms=result.duration_ms,
error=result.error,
)
return result
def _materialize_workspace(self, run: WorkflowRun):
if run.artifacts.workspace_snapshot is not None:
existing = Path(run.artifacts.workspace_snapshot.root_dir)
if existing.exists():
return run.artifacts.workspace_snapshot
if self.workspace_manager is not None:
bundle = self.workspace_manager.prepare_run_workspace(run, overwrite=True)
run.artifacts.workspace_snapshot = bundle
return bundle
materializer = ArtifactMaterializer()
return materializer.materialize_run(run, overwrite=True)
if self.workspace_manager is not None:
bundle = self.workspace_manager.prepare_run_workspace(run, overwrite=True)
run.artifacts.workspace_snapshot = bundle
return bundle
materializer = ArtifactMaterializer()
return materializer.materialize_run(run, overwrite=True)
def _execute_legacy_runtime(
self,
*,
workspace_root: Path,
now: datetime,
started: float,
) -> SandboxExecutionResult:
image_tag = f"course-gen-{workspace_root.name.lower()}-{uuid4().hex[:8]}"
cache_key: str | None = None
build_cached = False
runtime_dir = workspace_root / "runtime"
dockerfile = runtime_dir / "Dockerfile"
if self.cache_images:
cache_key = self._workspace_cache_key(workspace_root)
image_tag = self._cached_image_tag(cache_key)
build_command = [
self.docker_binary,
"build",
"-f",
str(dockerfile.relative_to(workspace_root)),
"-t",
image_tag,
".",
]
if self.cache_images and self._image_exists(image_tag):
build_cached = True
build_result = subprocess.CompletedProcess(
build_command,
0,
stdout=f"Reused cached Docker image {image_tag} for workspace hash {cache_key}.",
stderr="",
)
else:
build_result = subprocess.run(
build_command,
cwd=workspace_root,
check=False,
capture_output=True,
text=True,
timeout=self.build_timeout_s,
)
if build_result.returncode != 0:
return SandboxExecutionResult(
status=SandboxExecutionStatus.failed,
available=True,
build_succeeded=False,
build_cached=build_cached,
run_succeeded=False,
generated_at=now,
duration_ms=int((time.perf_counter() - started) * 1000),
workspace_root=str(workspace_root),
image_tag=image_tag,
cache_key=cache_key,
build_command=build_command,
build_stdout=build_result.stdout,
build_stderr=build_result.stderr,
error="Docker build failed for the generated assignment runtime.",
)
run_command = [self.docker_binary, "run", "--rm", image_tag]
run_result = subprocess.run(
run_command,
cwd=workspace_root,
check=False,
capture_output=True,
text=True,
timeout=self.run_timeout_s,
)
parsed = self._parse_run_output(run_result.stdout)
deliverable_reports = [
DeliverableSandboxReport.model_validate(item)
for item in parsed.get("deliverable_reports", [])
]
run_succeeded = run_result.returncode == 0 and bool(parsed.get("success"))
return SandboxExecutionResult(
status=SandboxExecutionStatus.passed if run_succeeded else SandboxExecutionStatus.failed,
available=True,
build_succeeded=True,
build_cached=build_cached,
run_succeeded=run_succeeded,
generated_at=now,
duration_ms=int((time.perf_counter() - started) * 1000),
workspace_root=str(workspace_root),
image_tag=image_tag,
cache_key=cache_key,
build_command=build_command,
run_command=run_command,
build_stdout=build_result.stdout,
build_stderr=build_result.stderr,
run_stdout=run_result.stdout,
run_stderr=run_result.stderr,
deliverable_reports=deliverable_reports,
error=None if run_succeeded else parsed.get("error") or "Assignment sandbox verification failed.",
)
def _execute_starter_harness(
self,
*,
workspace_root: Path,
spec: TaskAgentServiceSpec,
workflow_run_id: str,
now: datetime,
started: float,
) -> SandboxExecutionResult:
build_stdout_parts: list[str] = []
build_stderr_parts: list[str] = []
run_stdout_parts: list[str] = []
run_stderr_parts: list[str] = []
deliverable_reports: list[DeliverableSandboxReport] = []
build_command: list[str] = []
run_command: list[str] = []
all_builds_succeeded = True
all_runs_succeeded = True
any_cached = False
fail_fast = bool(spec.course_structure.shared_codebase)
log_coursegen_event(
"sandbox_starter_harness_started",
workflow_run_id=workflow_run_id,
workspace_root=str(workspace_root),
deliverable_count=len(spec.deliverables),
)
shared_codebase = bool(spec.course_structure.shared_codebase)
shared_starter_root = workspace_root / "starter"
if shared_codebase:
return self._execute_shared_starter_harness(
workspace_root=workspace_root,
shared_starter_root=shared_starter_root,
spec=spec,
workflow_run_id=workflow_run_id,
now=now,
started=started,
fail_fast=fail_fast,
)
for deliverable in spec.deliverables:
# Non-shared (legacy) path: one starter per deliverable.
starter_root = workspace_root / "starter" / deliverable.id
log_coursegen_event(
"sandbox_deliverable_started",
workflow_run_id=workflow_run_id,
deliverable_id=deliverable.id,
deliverable_title=deliverable.title,
starter_root=str(starter_root),
)
if not starter_root.exists():
all_builds_succeeded = False
log_coursegen_event(
"sandbox_deliverable_completed",
workflow_run_id=workflow_run_id,
deliverable_id=deliverable.id,
sandbox_status="failed",
error="Starter workspace is missing for this deliverable.",
)
deliverable_reports.append(
DeliverableSandboxReport(
deliverable_id=deliverable.id,
compile_succeeded=False,
runtime_succeeded=False,
error="Starter workspace is missing for this deliverable.",
)
)
continue
host_port = self.runtime_harness._allocate_port()
container_name = f"course-gen-sandbox-{deliverable.id}-{uuid4().hex[:8]}".lower()
network_name = f"{container_name}-net"
base_url = f"http://127.0.0.1:{host_port}"
logs = ""
runtime_image_ready = False
current_runtime_workspace: Path | None = None
fail_fast_triggered = False
dependency_services: list[dict] = []
try:
manifest = self.runtime_harness._runtime_manifest(starter_root)
materialization = self.dependency_contract_materializer.materialize(
starter_root=starter_root,
runtime_plan=spec.project_contract.runtime_plan,
deliverable_id=deliverable.id,
)
if materialization.attempted:
log_coursegen_event(
"sandbox_dependency_contract_materialized",
workflow_run_id=workflow_run_id,
deliverable_id=deliverable.id,
image_name=materialization.image_name,
synced_paths=materialization.synced_paths,
success=materialization.succeeded,
error=materialization.error,
)
if materialization.stdout:
build_stdout_parts.append(
f"[{deliverable.id}] Dependency contract materialization stdout:\n{materialization.stdout}".strip()
)
if materialization.stderr:
build_stderr_parts.append(
f"[{deliverable.id}] Dependency contract materialization stderr:\n{materialization.stderr}".strip()
)
if not materialization.succeeded:
all_builds_succeeded = False
log_coursegen_event(
"sandbox_deliverable_completed",
workflow_run_id=workflow_run_id,
deliverable_id=deliverable.id,
sandbox_status="failed",
error=materialization.error,
)
deliverable_reports.append(
DeliverableSandboxReport(
deliverable_id=deliverable.id,
compile_succeeded=False,
runtime_succeeded=False,
failed_stage=SandboxFailureStage.dependency_materialization,
stage_command=list(materialization.command),
stage_exit_code=materialization.return_code,
stdout=materialization.stdout,
stderr=materialization.stderr,
error=materialization.error
or "Dependency contract materialization failed before runtime boot.",
)
)
fail_fast_triggered = fail_fast
continue
with self.runtime_harness._ephemeral_runtime_workspace(starter_root) as runtime_workspace:
current_runtime_workspace = runtime_workspace
image_name = self.runtime_harness._workspace_runtime_image_name(runtime_workspace)
build_command = []
build_stdout_parts.append(
f"[{deliverable.id}] Using runtime image {image_name} from the authored runtime plan."
)
if materialization.synced_paths:
build_stdout_parts.append(
f"[{deliverable.id}] Materialized dependency contract paths: {', '.join(materialization.synced_paths)}"
)
self.runtime_harness._ensure_runtime_image_available(image_name)
runtime_image_ready = True
if self.runtime_harness._image_exists(image_name):
any_cached = True
dependency_services = self.runtime_harness._dependency_services(runtime_workspace) or []
log_coursegen_event(
"sandbox_deliverable_support_services_starting",
workflow_run_id=workflow_run_id,
deliverable_id=deliverable.id,
dependency_service_count=len(dependency_services),
network_name=network_name,
)
self.runtime_harness._start_runtime_support_services(
runtime_workspace,
network_name=network_name,
container_prefix=container_name,
)
log_coursegen_event(
"sandbox_deliverable_support_services_started",
workflow_run_id=workflow_run_id,
deliverable_id=deliverable.id,
dependency_service_count=len(dependency_services),
)
local_run_command = [
self.docker_binary,
"run",
"-d",
"--name",
container_name,
"-p",
f"{host_port}:8000",
"-v",
f"{runtime_workspace}:/workspace",
"-w",
"/workspace",
*(
[
"--network",
network_name,
"--network-alias",
"app",
]
if dependency_services
else []
),
*self.runtime_harness._docker_env_args(
self.runtime_harness._app_runtime_environment(runtime_workspace)
),
image_name,
*self.runtime_harness._runtime_shell_command(
self.runtime_harness._runtime_launch_script(
workspace_path=runtime_workspace,
spec=spec,
include_setup=True,
)
),
]
run_command = local_run_command
log_coursegen_event(
"sandbox_deliverable_runtime_launching",
workflow_run_id=workflow_run_id,
deliverable_id=deliverable.id,
image_name=image_name,
host_port=host_port,
container_name=container_name,
)
run_result = subprocess.run(
local_run_command,
cwd=starter_root,
check=False,
capture_output=True,
text=True,
timeout=self.run_timeout_s,
)
if run_result.returncode != 0:
all_runs_succeeded = False
logs = self.runtime_harness._container_logs(container_name) or ""
container_stderr = self.runtime_harness._container_stderr(container_name) or ""
failed_stage = self._deliverable_runtime_stage(
logs=logs,
error_text="\n".join(part for part in (run_result.stderr, run_result.stdout) if part),
default=SandboxFailureStage.container_launch,
)
log_coursegen_event(
"sandbox_deliverable_runtime_launch_failed",
workflow_run_id=workflow_run_id,
deliverable_id=deliverable.id,
return_code=run_result.returncode,
error="Could not start the starter runtime container.",
)
run_stdout_parts.append(f"[{deliverable.id}] {run_result.stdout}".strip())
run_stderr_parts.append(f"[{deliverable.id}] {run_result.stderr}\n{logs}".strip())
report_stderr = "\n".join(
part for part in [run_result.stderr, container_stderr or logs] if part
)
(
app_stdout_tail,
app_exit_state,
sidecar_diagnostics,
) = self._collect_failure_diagnostics(
app_container_name=container_name,
dependency_services=dependency_services,
sidecar_container_prefix=container_name,
)
deliverable_reports.append(
DeliverableSandboxReport(
deliverable_id=deliverable.id,
compile_succeeded=self._compile_succeeded_for_stage(failed_stage),
runtime_succeeded=False,
failed_stage=failed_stage,
stage_command=self._stage_command_for_report(
workspace_path=runtime_workspace,
spec=spec,
failed_stage=failed_stage,
fallback=local_run_command,
),
stage_exit_code=run_result.returncode,
stdout=run_result.stdout,
stderr=report_stderr,
error=self._summarize_stage_failure(
deliverable_id=deliverable.id,
failed_stage=failed_stage,
error_text=run_result.stderr,
logs=container_stderr or logs,
default="Could not start the starter runtime container.",
),
stdout_tail=app_stdout_tail,
exit_state=app_exit_state,
sidecar_diagnostics=sidecar_diagnostics,
)
)
fail_fast_triggered = fail_fast
continue
healthcheck_path = self.runtime_harness._healthcheck_path(runtime_workspace, spec)
log_coursegen_event(
"sandbox_deliverable_healthcheck_wait_started",
workflow_run_id=workflow_run_id,
deliverable_id=deliverable.id,
healthcheck_url=f"{base_url}{healthcheck_path}",
)
self.runtime_harness._wait_for_http(
f"{base_url}{healthcheck_path}",
container_name=container_name,
)
log_coursegen_event(
"sandbox_deliverable_healthcheck_wait_completed",
workflow_run_id=workflow_run_id,
deliverable_id=deliverable.id,
healthcheck_url=f"{base_url}{healthcheck_path}",
)
log_coursegen_event(
"sandbox_deliverable_public_checks_started",
workflow_run_id=workflow_run_id,
deliverable_id=deliverable.id,
base_url=base_url,
)
contract_passed, contract_output, contract_error, contract_http_response = self._probe_contract_smoke(
manifest,
base_url,
starter_type=spec.runtime_dependencies.starter_type.value,
)
checks_passed, check_output, check_error = self._run_visible_suite(
starter_root=starter_root,
manifest=manifest,
base_url=base_url,
)
logs = self.runtime_harness._container_logs(container_name) or ""
combined_output = "\n\n".join(
part
for part in (contract_output, check_output)
if part and part.strip()
)
run_stdout_parts.append(f"[{deliverable.id}] {combined_output}".strip())
if logs:
run_stderr_parts.append(f"[{deliverable.id}] {logs}".strip())
if not contract_passed:
all_runs_succeeded = False
failed_stage: SandboxFailureStage | None = None
if not contract_passed:
failed_stage = SandboxFailureStage.contract
elif not checks_passed:
failed_stage = SandboxFailureStage.checks
log_coursegen_event(
"sandbox_deliverable_public_checks_completed",
workflow_run_id=workflow_run_id,
deliverable_id=deliverable.id,
contract_passed=contract_passed,
checks_passed=checks_passed,
error=check_error,
)
contract_failure_diagnostics = None
if not contract_passed or not checks_passed:
contract_failure_diagnostics = self._collect_failure_diagnostics(
app_container_name=container_name,
dependency_services=dependency_services,
sidecar_container_prefix=container_name,
)
deliverable_reports.append(
DeliverableSandboxReport(
deliverable_id=deliverable.id,
compile_succeeded=True,
runtime_succeeded=contract_passed,
failed_stage=failed_stage,
stage_command=(
[str(manifest.get("visible_check_command") or "sh .coursegen/runtime/check_visible.sh")]
if failed_stage == SandboxFailureStage.checks
else []
),
public_checks_passed=checks_passed,
health_status_code=200,
stdout=combined_output,
stderr=logs,
error=self._post_boot_failure_error(
deliverable_id=deliverable.id,
failed_stage=failed_stage,
contract_error=contract_error,
check_error=check_error,
logs=logs,
contract_http_response=contract_http_response,
),
stdout_tail=(
contract_failure_diagnostics[0]
if contract_failure_diagnostics
else None
),
exit_state=(
contract_failure_diagnostics[1]
if contract_failure_diagnostics
else None
),
sidecar_diagnostics=(
contract_failure_diagnostics[2]
if contract_failure_diagnostics
else None
),
http_response=contract_http_response,
)
)
fail_fast_triggered = fail_fast and (not contract_passed or not checks_passed)
log_coursegen_event(
"sandbox_deliverable_completed",
workflow_run_id=workflow_run_id,
deliverable_id=deliverable.id,
sandbox_status="passed" if contract_passed else "failed",
error=check_error,
)
except RuntimeImageBuildError as build_exc:
all_builds_succeeded = False
all_runs_succeeded = False
build_stderr_tail = self._tail_lines(build_exc.stderr, max_lines=80)
build_stdout_tail = self._tail_lines(build_exc.stdout, max_lines=40)
combined_log = "\n".join(part for part in (build_stderr_tail, build_stdout_tail) if part)
build_stderr_parts.append(f"[{deliverable.id}] {build_stderr_tail}".strip())
if build_stdout_tail:
build_stdout_parts.append(f"[{deliverable.id}] {build_stdout_tail}".strip())
log_coursegen_event(
"sandbox_deliverable_completed",
workflow_run_id=workflow_run_id,
deliverable_id=deliverable.id,
sandbox_status="failed",
error=str(build_exc),
)
deliverable_reports.append(
DeliverableSandboxReport(
deliverable_id=deliverable.id,
compile_succeeded=False,
runtime_succeeded=False,
failed_stage=SandboxFailureStage.image_build,
stage_command=list(build_exc.command),
stage_exit_code=build_exc.returncode,
stdout=build_stdout_tail,
stderr=combined_log,
error=self._summarize_stage_failure(
deliverable_id=deliverable.id,
failed_stage=SandboxFailureStage.image_build,
error_text=str(build_exc),
logs=combined_log,
default="Could not build the starter runtime image.",
),
stdout_tail=build_stdout_tail or None,
)
)
fail_fast_triggered = fail_fast
except Exception as exc: # noqa: BLE001
if not runtime_image_ready:
all_builds_succeeded = False
all_runs_succeeded = False
logs = self.runtime_harness._container_logs(container_name) or ""
container_stderr = self.runtime_harness._container_stderr(container_name) or ""
failed_stage = self._deliverable_runtime_stage(
logs=logs,
error_text=str(exc),
default=(
SandboxFailureStage.boot if runtime_image_ready else SandboxFailureStage.runtime
),
)
log_coursegen_event(
"sandbox_deliverable_completed",
workflow_run_id=workflow_run_id,
deliverable_id=deliverable.id,
sandbox_status="failed",
error=str(exc),
)
run_stderr_parts.append(f"[{deliverable.id}] {exc}\n{logs}".strip())
(
app_stdout_tail,
app_exit_state,
sidecar_diagnostics,
) = self._collect_failure_diagnostics(
app_container_name=container_name,
dependency_services=dependency_services,
sidecar_container_prefix=container_name,
)
deliverable_reports.append(
DeliverableSandboxReport(
deliverable_id=deliverable.id,
compile_succeeded=self._compile_succeeded_for_stage(failed_stage),
runtime_succeeded=False,
failed_stage=failed_stage,
stage_command=self._stage_command_for_report(
workspace_path=(
current_runtime_workspace
if current_runtime_workspace is not None and current_runtime_workspace.exists()
else starter_root
),
spec=spec,
failed_stage=failed_stage,
fallback=run_command,
),
stdout="",
stderr=container_stderr or logs,
error=self._summarize_stage_failure(
deliverable_id=deliverable.id,
failed_stage=failed_stage,
error_text=str(exc),
logs=container_stderr or logs,
default=str(exc),
),
stdout_tail=app_stdout_tail,
exit_state=app_exit_state,
sidecar_diagnostics=sidecar_diagnostics,
)
)
fail_fast_triggered = fail_fast
finally:
self.runtime_harness._remove_runtime_support(
starter_root,
network_name=network_name,
container_prefix=container_name,
)
if fail_fast_triggered:
log_coursegen_event(
"sandbox_fail_fast_stopped_after_deliverable",
workflow_run_id=workflow_run_id,
deliverable_id=deliverable.id,
shared_codebase=spec.course_structure.shared_codebase,
)
break
success = all_builds_succeeded and all_runs_succeeded and bool(deliverable_reports)
result = SandboxExecutionResult(
status=SandboxExecutionStatus.passed if success else SandboxExecutionStatus.failed,
available=True,
build_succeeded=all_builds_succeeded,
build_cached=any_cached,
run_succeeded=all_runs_succeeded,
generated_at=now,
duration_ms=int((time.perf_counter() - started) * 1000),
workspace_root=str(workspace_root),
build_command=build_command,
run_command=run_command,
build_stdout="\n\n".join(part for part in build_stdout_parts if part),
build_stderr="\n\n".join(part for part in build_stderr_parts if part),
run_stdout="\n\n".join(part for part in run_stdout_parts if part),
run_stderr="\n\n".join(part for part in run_stderr_parts if part),
deliverable_reports=deliverable_reports,
error=None
if success
else self._summarize_failed_deliverables(deliverable_reports),
)
log_coursegen_event(
"sandbox_starter_harness_completed",
workflow_run_id=workflow_run_id,
workspace_root=str(workspace_root),
sandbox_status=result.status.value,
deliverable_report_count=len(result.deliverable_reports),
duration_ms=result.duration_ms,
error=result.error,
)
return result
def _execute_shared_starter_harness(
self,
*,
workspace_root: Path,
shared_starter_root: Path,
spec: TaskAgentServiceSpec,
workflow_run_id: str,
now: datetime,
started: float,
fail_fast: bool,
) -> SandboxExecutionResult:
"""Shared-codebase variant: build the runtime image and boot the shared
starter ONCE, then run each deliverable's visible suite + contract
probe against the single running app."""
build_stdout_parts: list[str] = []
build_stderr_parts: list[str] = []
run_stdout_parts: list[str] = []
run_stderr_parts: list[str] = []
deliverable_reports: list[DeliverableSandboxReport] = []
build_command: list[str] = []
run_command: list[str] = []
all_builds_succeeded = True
all_runs_succeeded = True
any_cached = False
private_root = workspace_root.parent / "private"
# Sanity: shared starter must exist.
if not shared_starter_root.exists():
for deliverable in spec.deliverables:
deliverable_reports.append(
DeliverableSandboxReport(
deliverable_id=deliverable.id,
compile_succeeded=False,
runtime_succeeded=False,
failed_stage=SandboxFailureStage.missing_workspace,
error="Shared starter workspace is missing.",
)
)
return self._finalize_starter_result(
workspace_root=workspace_root,
now=now,
started=started,
deliverable_reports=deliverable_reports,
build_command=build_command,
run_command=run_command,
build_stdout_parts=build_stdout_parts,
build_stderr_parts=build_stderr_parts,
run_stdout_parts=run_stdout_parts,
run_stderr_parts=run_stderr_parts,
all_builds_succeeded=False,
all_runs_succeeded=False,
any_cached=False,
workflow_run_id=workflow_run_id,
)
# Materialize the dependency contract ONCE against the shared starter.
try:
materialization = self.dependency_contract_materializer.materialize(
starter_root=shared_starter_root,
runtime_plan=spec.project_contract.runtime_plan,
deliverable_id="shared",
)
except Exception as exc: # noqa: BLE001
for deliverable in spec.deliverables:
deliverable_reports.append(
DeliverableSandboxReport(
deliverable_id=deliverable.id,
compile_succeeded=False,
runtime_succeeded=False,
failed_stage=SandboxFailureStage.dependency_materialization,
error=str(exc),
)
)
return self._finalize_starter_result(
workspace_root=workspace_root,
now=now,
started=started,
deliverable_reports=deliverable_reports,
build_command=build_command,
run_command=run_command,
build_stdout_parts=build_stdout_parts,
build_stderr_parts=build_stderr_parts,
run_stdout_parts=run_stdout_parts,
run_stderr_parts=run_stderr_parts,
all_builds_succeeded=False,
all_runs_succeeded=False,
any_cached=False,
workflow_run_id=workflow_run_id,
)
if materialization.attempted:
log_coursegen_event(
"sandbox_dependency_contract_materialized",
workflow_run_id=workflow_run_id,
deliverable_id="shared",
image_name=materialization.image_name,
synced_paths=materialization.synced_paths,
success=materialization.succeeded,
error=materialization.error,
)
if materialization.stdout:
build_stdout_parts.append(
f"[shared] Dependency contract materialization stdout:\n{materialization.stdout}".strip()
)
if materialization.stderr:
build_stderr_parts.append(
f"[shared] Dependency contract materialization stderr:\n{materialization.stderr}".strip()
)
if not materialization.succeeded:
# Fail every deliverable with the same materialization error and
# short-circuit (no per-deliverable boot).
for deliverable in spec.deliverables:
deliverable_reports.append(
DeliverableSandboxReport(
deliverable_id=deliverable.id,
compile_succeeded=False,
runtime_succeeded=False,
failed_stage=SandboxFailureStage.dependency_materialization,
stage_command=list(materialization.command),
stage_exit_code=materialization.return_code,
stdout=materialization.stdout,
stderr=materialization.stderr,
error=materialization.error
or "Dependency contract materialization failed before runtime boot.",
)
)
return self._finalize_starter_result(
workspace_root=workspace_root,
now=now,
started=started,
deliverable_reports=deliverable_reports,
build_command=build_command,
run_command=run_command,
build_stdout_parts=build_stdout_parts,
build_stderr_parts=build_stderr_parts,
run_stdout_parts=run_stdout_parts,
run_stderr_parts=run_stderr_parts,