"""Bounded external profiling; never wrap numeric or model operations. Container CPU/memory/I/O and host GPU utilization are observations, not GPU kernel timings. Hash timing covers orchestration only. The sampler never changes entrypoints, environments, resource limits, arrays, cameras or gates. """ import datetime import json import subprocess import threading import time from collections import Counter class ExecutionProfile: def __init__(self, root, pipeline, interval=5.0): self.root = root self.pipeline = pipeline self.interval = interval self.stages = [] self.hashes = Counter() self.samples = 0 self.sample_seconds = 0.0 self.errors = Counter() self.phase = None self.stop_event = threading.Event() self.original_run = pipeline.run_container self.original_checksum = pipeline.checksum self.thread = None def start(self): self.started = time.monotonic() self.pipeline.run_container = self.run_container self.pipeline.checksum = self.checksum self.thread = threading.Thread(target=self.observe, daemon=True) self.thread.start() return self def checksum(self, path): started = time.monotonic() result = self.original_checksum(path) self.hashes["calls"] += 1 self.hashes["bytes"] += path.stat().st_size self.hashes["seconds"] += time.monotonic() - started return result def run_container(self, marker, phase, *args, **kwargs): record = json.loads(marker.read_text()) name = "ndc-infrastructure-" + record["key"][:16] + "-" + phase self.phase = (phase, name) started = time.monotonic() row = dict( phase=phase, started_utc=datetime.datetime.now(datetime.UTC).isoformat(), started_monotonic=started, resources=kwargs.get("resources") or dict(cpus=4, memory_gib=16), gpu=kwargs.get("gpu", True), passed=False, ) try: result = self.original_run(marker, phase, *args, **kwargs) row["passed"] = True return result finally: row["seconds"] = time.monotonic() - started self.stages.append(row) self.phase = None (self.root / "stage-profile.json").write_text(json.dumps(self.stages, indent=2)) def command(self, args): try: result = subprocess.run(args, capture_output=True, text=True, timeout=3) if result.returncode: self.errors[args[0] + ":exit"] += 1 return None return result.stdout.strip() except (OSError, subprocess.TimeoutExpired): self.errors[args[0] + ":unavailable"] += 1 return None def observe(self): # At most 720 samples and a bounded lifetime, even after a caller error. with (self.root / "resource-samples.jsonl").open("w") as output: while self.samples < 720 and not self.stop_event.wait(self.interval): phase = self.phase if phase is None: continue begin = time.monotonic() stats = self.command( ["docker", "stats", "--no-stream", "--format", "{{json .}}", phase[1]] ) gpu = self.command( [ "nvidia-smi", "--query-gpu=index,utilization.gpu,utilization.memory,memory.used,power.draw", "--format=csv,noheader,nounits", ] ) elapsed = time.monotonic() - begin output.write( json.dumps( dict( utc=datetime.datetime.now(datetime.UTC).isoformat(), since_start_seconds=begin - self.started, phase=phase[0], same_phase_at_completion=self.phase == phase, docker=stats, gpu_host_csv=gpu, observation_seconds=elapsed, ) ) + "\n" ) output.flush() self.samples += 1 self.sample_seconds += elapsed def stop(self): self.stop_event.set() if self.thread is not None: self.thread.join(timeout=10) self.pipeline.run_container = self.original_run self.pipeline.checksum = self.original_checksum report = dict( schema="missioncore.external-execution-profile/v1", stages=self.stages, orchestration_hashes=dict(self.hashes), samples=self.samples, observer_command_wall_seconds=self.sample_seconds, errors=dict(self.errors), sampler_stopped=self.thread is None or not self.thread.is_alive(), numeric_functions_wrapped=False, gpu_measurement_scope="host utilization; includes unrelated durable GPU services", sample_interval_seconds=self.interval, observer_wall_is_not_pipeline_overhead=True, ) (self.root / "execution-profile.json").write_text(json.dumps(report, indent=2)) return report