letitloop 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- letitloop-0.2.0.dist-info/METADATA +232 -0
- letitloop-0.2.0.dist-info/RECORD +175 -0
- letitloop-0.2.0.dist-info/WHEEL +5 -0
- letitloop-0.2.0.dist-info/entry_points.txt +4 -0
- letitloop-0.2.0.dist-info/licenses/LICENSE +21 -0
- letitloop-0.2.0.dist-info/top_level.txt +1 -0
- orchestrator/SKILL.md +292 -0
- orchestrator/__init__.py +151 -0
- orchestrator/anti_ouroboros.py +78 -0
- orchestrator/approval.py +139 -0
- orchestrator/ast_node_splicer.py +130 -0
- orchestrator/ast_splicer.py +94 -0
- orchestrator/audit.py +88 -0
- orchestrator/budget.py +195 -0
- orchestrator/checkpoint.py +248 -0
- orchestrator/cli.py +1971 -0
- orchestrator/codebase_introspector.py +66 -0
- orchestrator/component_slicer.py +185 -0
- orchestrator/config.py +152 -0
- orchestrator/contract.py +404 -0
- orchestrator/dag_validator.py +172 -0
- orchestrator/elasticity_governor.py +80 -0
- orchestrator/env_doctor.py +166 -0
- orchestrator/errors.py +211 -0
- orchestrator/events.py +120 -0
- orchestrator/evidence.py +203 -0
- orchestrator/exceptions.py +37 -0
- orchestrator/experimental/arena_arbiter.py +260 -0
- orchestrator/experimental/fuzz_engine.py +206 -0
- orchestrator/experimental/mutation_tester.py +382 -0
- orchestrator/failure.py +226 -0
- orchestrator/fast_sandbox.py +126 -0
- orchestrator/feasibility_gate.py +115 -0
- orchestrator/feedback.py +302 -0
- orchestrator/fixtures/__init__.py +0 -0
- orchestrator/fixtures/example_contract.json +50 -0
- orchestrator/fixtures/generated/evidence-cli-run-test-step-1.json +47 -0
- orchestrator/fixtures/generated/evidence-cli-run-test-step-2.json +47 -0
- orchestrator/fixtures/generated/evidence-inject-test-a.json +47 -0
- orchestrator/fixtures/generated/evidence-inject-test-b.json +47 -0
- orchestrator/fixtures/generated/evidence-inject-test-c.json +47 -0
- orchestrator/fixtures/generated/evidence-json-test-a.json +47 -0
- orchestrator/fixtures/generated/evidence-json-test-b.json +47 -0
- orchestrator/fixtures/generated/fail-report-fail-task-1.json +47 -0
- orchestrator/fixtures/generated/fail-report-json-task-1.json +47 -0
- orchestrator/fixtures/generated/fail-report-success-task-1.json +47 -0
- orchestrator/fixtures/generated/fuzz-engine-design.json +63 -0
- orchestrator/fixtures/generated/fuzz-engine-impl.json +62 -0
- orchestrator/fixtures/generated/fuzz-engine-tests.json +62 -0
- orchestrator/fixtures/generated/fuzz-engine-verify.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-1.json +63 -0
- orchestrator/fixtures/generated/goal-orch-step-2.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-3.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-4.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-5.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-6.json +63 -0
- orchestrator/fixtures/generated/implement-a-thread-safe-token-bucket-rat-task-1.json +53 -0
- orchestrator/fixtures/generated/orchestrator-checkpoint-rollback-3.json +63 -0
- orchestrator/fixtures/generated/orchestrator-checkpoint-rollback.json +62 -0
- orchestrator/fixtures/generated/orchestrator-live-telemetry-2.json +62 -0
- orchestrator/fixtures/generated/orchestrator-live-telemetry.json +62 -0
- orchestrator/fixtures/generated/orchestrator-spec-synthesis-1.json +62 -0
- orchestrator/fixtures/generated/orchestrator-spec-synthesis.json +62 -0
- orchestrator/fixtures/generated/orchestrator-test-verification-4.json +62 -0
- orchestrator/fixtures/generated/orchestrator-test-verification.json +62 -0
- orchestrator/fixtures/generated/perf-step-1.json +61 -0
- orchestrator/fixtures/generated/perf-step-2.json +62 -0
- orchestrator/fixtures/generated/perf-step-3.json +62 -0
- orchestrator/fixtures/generated/perf-step-4.json +62 -0
- orchestrator/fixtures/generated/perf-step-5.json +63 -0
- orchestrator/fixtures/generated/phase2-proof-two-step-step-1.json +47 -0
- orchestrator/fixtures/generated/phase2-proof-two-step-step-2.json +47 -0
- orchestrator/fixtures/generated/planner-spec-synthesis-impl.json +59 -0
- orchestrator/fixtures/generated/self-evolution-ast-formatter.json +69 -0
- orchestrator/fixtures/generated/self-evolution-checkpoint-rollback.json +70 -0
- orchestrator/fixtures/generated/self-evolution-spec-synthesis.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-1.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-2.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-3.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-4.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-5.json +65 -0
- orchestrator/fixtures/generated/self-evolution-telemetry.json +70 -0
- orchestrator/fixtures/generated/self-evolution-tests.json +71 -0
- orchestrator/fixtures/generated/spec-telemetry-research-design.json +64 -0
- orchestrator/fixtures/generated/spec-telemetry-step-1.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-2.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-3.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-4.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-5.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-verification.json +58 -0
- orchestrator/fixtures/generated/token-bucket-impl.json +69 -0
- orchestrator/fixtures/generated/token-bucket-step-1.json +70 -0
- orchestrator/fixtures/generated/token-bucket-step-2.json +70 -0
- orchestrator/fixtures/generated/token-bucket-step-3.json +60 -0
- orchestrator/fixtures/generated/token-bucket-tests.json +70 -0
- orchestrator/fixtures/generated/token-bucket-verify.json +61 -0
- orchestrator/fixtures/generated/trace-ux-tests-step-1.json +64 -0
- orchestrator/fixtures/generated/trace-ux-tests-step-2.json +64 -0
- orchestrator/fixtures/generated/trace-ux-tests-step-3.json +62 -0
- orchestrator/fixtures/generated/tui-live-telemetry-impl.json +59 -0
- orchestrator/fixtures/phase1_proof_escalation_contract.json +41 -0
- orchestrator/fixtures/phase1_proof_happy_path_contract.json +83 -0
- orchestrator/fixtures/phase1_proof_qc_contract.json +41 -0
- orchestrator/fixtures/phase1_proof_repair_contract.json +41 -0
- orchestrator/fixtures/phase2_proof_two_step_goal.json +15 -0
- orchestrator/fixtures/run_proofs.py +299 -0
- orchestrator/fixtures/test_normalizer.py +16 -0
- orchestrator/generator.py +239 -0
- orchestrator/goal.py +245 -0
- orchestrator/handoff.py +86 -0
- orchestrator/hybrid_worker.py +840 -0
- orchestrator/impossibility.py +162 -0
- orchestrator/limits.py +60 -0
- orchestrator/live_evolution_engine.py +247 -0
- orchestrator/llm.py +291 -0
- orchestrator/local_tool_calling.py +285 -0
- orchestrator/lock.py +404 -0
- orchestrator/mcp_client.py +571 -0
- orchestrator/mcp_server.py +344 -0
- orchestrator/memory_bridge.py +182 -0
- orchestrator/metrics.py +159 -0
- orchestrator/micro_epoch.py +42 -0
- orchestrator/models.py +350 -0
- orchestrator/parsing.py +237 -0
- orchestrator/patch_applier.py +154 -0
- orchestrator/plan_preview.py +138 -0
- orchestrator/plan_quality.py +357 -0
- orchestrator/planner.py +532 -0
- orchestrator/preferences.py +115 -0
- orchestrator/preflight.py +141 -0
- orchestrator/process_guard.py +357 -0
- orchestrator/prometheus_exporter.py +207 -0
- orchestrator/prompts.py +275 -0
- orchestrator/proposal_ledger.py +194 -0
- orchestrator/provenance.py +263 -0
- orchestrator/provider_scheduler.py +394 -0
- orchestrator/qc/__init__.py +153 -0
- orchestrator/qc/aggregator.py +330 -0
- orchestrator/qc/parsing.py +287 -0
- orchestrator/qc/personas.py +242 -0
- orchestrator/qc/runner.py +569 -0
- orchestrator/qc_overrule.py +87 -0
- orchestrator/qc_review.py +282 -0
- orchestrator/quality_lenses.py +314 -0
- orchestrator/quality_plan.py +449 -0
- orchestrator/quality_plane.py +103 -0
- orchestrator/reconcile.py +191 -0
- orchestrator/replanner.py +433 -0
- orchestrator/research.py +176 -0
- orchestrator/review_artifact.py +672 -0
- orchestrator/safety.py +271 -0
- orchestrator/schemas.py +230 -0
- orchestrator/scope.py +466 -0
- orchestrator/sensory_radar.py +79 -0
- orchestrator/skill_installer.py +140 -0
- orchestrator/sse_server.py +160 -0
- orchestrator/state.py +871 -0
- orchestrator/subprocess_helper.py +131 -0
- orchestrator/supervisor/__init__.py +184 -0
- orchestrator/supervisor/_shared.py +164 -0
- orchestrator/supervisor/cleanup.py +185 -0
- orchestrator/supervisor/core.py +1680 -0
- orchestrator/supervisor/recovery.py +367 -0
- orchestrator/supervisor/reporting.py +251 -0
- orchestrator/surgical_extractor.py +119 -0
- orchestrator/telemetry.py +61 -0
- orchestrator/templates.py +268 -0
- orchestrator/token_gate.py +245 -0
- orchestrator/tui.py +649 -0
- orchestrator/verifier.py +1103 -0
- orchestrator/webhooks.py +168 -0
- orchestrator/worker.py +469 -0
- orchestrator/worker_adapters.py +815 -0
- orchestrator/worker_pool.py +121 -0
- orchestrator/worktree.py +364 -0
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Preflight checks: required files, commands, output allow-list, secrets/ports."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import shlex
|
|
6
|
+
|
|
7
|
+
CHECK_KINDS = {"required_files", "required_commands", "output_allow_list", "required_secrets", "local_ports"}
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _check_required_file(path):
|
|
11
|
+
if not os.path.isfile(path):
|
|
12
|
+
return False, f"required file not found: {path}"
|
|
13
|
+
return True, None
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _check_command(name):
|
|
17
|
+
import shutil
|
|
18
|
+
|
|
19
|
+
resolved = shutil.which(name)
|
|
20
|
+
if resolved:
|
|
21
|
+
return True, None
|
|
22
|
+
return False, f"command not found: {name}"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _check_output_allowed(path, allowed_paths, denied_paths, workspace_root):
|
|
26
|
+
from .contract import check_path_allowed
|
|
27
|
+
|
|
28
|
+
ok, err = check_path_allowed(path, allowed_paths, denied_paths, workspace_root)
|
|
29
|
+
if not ok:
|
|
30
|
+
return False, err
|
|
31
|
+
return True, None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def run_preflight(contract, workspace_root, run_dir):
|
|
35
|
+
"""Run all preflight checks defined implicitly from contract structure.
|
|
36
|
+
|
|
37
|
+
Checks:
|
|
38
|
+
- All input files exist
|
|
39
|
+
- All output paths are within allow-list
|
|
40
|
+
- Required commands from acceptance checks are available
|
|
41
|
+
- Declared secrets report unsupported
|
|
42
|
+
- Declared local ports report unsupported
|
|
43
|
+
|
|
44
|
+
Returns (passed: bool, results: list[dict], evidence_path: str|None).
|
|
45
|
+
|
|
46
|
+
Results list contains dicts with keys: check_id, kind, passed, message.
|
|
47
|
+
"""
|
|
48
|
+
results = []
|
|
49
|
+
evidence = {
|
|
50
|
+
"preflight_checks": [],
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
allow = contract.allowed_paths()
|
|
54
|
+
deny = contract.denied_paths()
|
|
55
|
+
|
|
56
|
+
for inp in contract.inputs:
|
|
57
|
+
if isinstance(inp, str):
|
|
58
|
+
inp = {"path": inp}
|
|
59
|
+
if isinstance(inp, dict) and "path" in inp:
|
|
60
|
+
path = inp["path"]
|
|
61
|
+
full_path = os.path.join(workspace_root, path) if not os.path.isabs(path) else path
|
|
62
|
+
ok, msg = _check_required_file(full_path)
|
|
63
|
+
results.append(
|
|
64
|
+
{
|
|
65
|
+
"check_id": f"input_file:{path}",
|
|
66
|
+
"kind": "required_files",
|
|
67
|
+
"passed": ok,
|
|
68
|
+
"message": msg or f"input file exists: {path}",
|
|
69
|
+
}
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
for out in contract.outputs:
|
|
73
|
+
if isinstance(out, str):
|
|
74
|
+
out = {"path": out}
|
|
75
|
+
if isinstance(out, dict) and "path" in out:
|
|
76
|
+
path = out["path"]
|
|
77
|
+
ok, msg = _check_output_allowed(path, allow, deny, workspace_root)
|
|
78
|
+
results.append(
|
|
79
|
+
{
|
|
80
|
+
"check_id": f"output_allowed:{path}",
|
|
81
|
+
"kind": "output_allow_list",
|
|
82
|
+
"passed": ok,
|
|
83
|
+
"message": msg or f"output path allowed: {path}",
|
|
84
|
+
}
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
for check in contract.acceptance_checks:
|
|
88
|
+
if check["kind"] == "command":
|
|
89
|
+
cmd_ident = check.get("command", "")
|
|
90
|
+
try:
|
|
91
|
+
cmd_parts = shlex.split(cmd_ident)
|
|
92
|
+
except ValueError:
|
|
93
|
+
results.append(
|
|
94
|
+
{
|
|
95
|
+
"check_id": f"command:{cmd_ident}",
|
|
96
|
+
"kind": "required_commands",
|
|
97
|
+
"passed": False,
|
|
98
|
+
"message": f"malformed command string: {cmd_ident!r}",
|
|
99
|
+
}
|
|
100
|
+
)
|
|
101
|
+
continue
|
|
102
|
+
cmd_name = cmd_parts[0] if cmd_parts else cmd_ident
|
|
103
|
+
ok, msg = _check_command(cmd_name)
|
|
104
|
+
results.append(
|
|
105
|
+
{
|
|
106
|
+
"check_id": f"command:{cmd_name}",
|
|
107
|
+
"kind": "required_commands",
|
|
108
|
+
"passed": ok,
|
|
109
|
+
"message": msg or f"command available: {cmd_name}",
|
|
110
|
+
}
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
results.append(
|
|
114
|
+
{
|
|
115
|
+
"check_id": "secrets",
|
|
116
|
+
"kind": "required_secrets",
|
|
117
|
+
"passed": True,
|
|
118
|
+
"message": "secret injection unsupported in Phase 1 (skipping)",
|
|
119
|
+
}
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
results.append(
|
|
123
|
+
{
|
|
124
|
+
"check_id": "local_ports",
|
|
125
|
+
"kind": "local_ports",
|
|
126
|
+
"passed": True,
|
|
127
|
+
"message": "local port checking unsupported in Phase 1 (skipping)",
|
|
128
|
+
}
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
evidence["preflight_checks"] = results
|
|
132
|
+
all_passed = all(r["passed"] for r in results)
|
|
133
|
+
|
|
134
|
+
evidence_path = None
|
|
135
|
+
if run_dir:
|
|
136
|
+
os.makedirs(run_dir, exist_ok=True)
|
|
137
|
+
evidence_path = os.path.join(run_dir, "preflight_evidence.json")
|
|
138
|
+
with open(evidence_path, "w", encoding="utf-8") as f:
|
|
139
|
+
json.dump(evidence, f, indent=2, ensure_ascii=False)
|
|
140
|
+
|
|
141
|
+
return all_passed, results, evidence_path
|
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
"""Cross-platform process-tree orphan protection for worker and verifier subprocesses.
|
|
2
|
+
|
|
3
|
+
Guarantees that child AND grandchild processes spawned during contract execution are
|
|
4
|
+
terminated when a timeout fires, when the supervisor exits, or on SIGINT/SIGTERM.
|
|
5
|
+
|
|
6
|
+
Strategy:
|
|
7
|
+
- Windows: children are assigned to a kernel Job Object with
|
|
8
|
+
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE so descendants die atomically even if the
|
|
9
|
+
direct child refuses to die; ``taskkill /F /T`` is used for explicit tree kills.
|
|
10
|
+
- POSIX: children are started with ``start_new_session=True`` so the whole tree
|
|
11
|
+
shares a process group that can be signalled with ``os.killpg(SIGKILL)``.
|
|
12
|
+
|
|
13
|
+
Stdlib-only (ctypes on Windows); no psutil/pywin32 dependency.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import atexit
|
|
19
|
+
import errno
|
|
20
|
+
import os
|
|
21
|
+
import signal
|
|
22
|
+
import subprocess # nosec B404
|
|
23
|
+
import threading
|
|
24
|
+
import time
|
|
25
|
+
from typing import Any, Dict, Iterable, List, Optional
|
|
26
|
+
|
|
27
|
+
IS_WINDOWS = os.name == "nt"
|
|
28
|
+
|
|
29
|
+
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000
|
|
30
|
+
_JOB_OBJECT_EXTENDED_LIMIT_INFO_CLASS = 9
|
|
31
|
+
_PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
|
|
32
|
+
_STILL_ACTIVE = 259
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# ---------------------------------------------------------------------------
|
|
36
|
+
# Low-level platform primitives
|
|
37
|
+
# ---------------------------------------------------------------------------
|
|
38
|
+
|
|
39
|
+
if IS_WINDOWS:
|
|
40
|
+
import ctypes
|
|
41
|
+
from ctypes import wintypes
|
|
42
|
+
|
|
43
|
+
class JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure):
|
|
44
|
+
_fields_ = [
|
|
45
|
+
("PerProcessUserTimeLimit", ctypes.c_int64),
|
|
46
|
+
("PerJobUserTimeLimit", ctypes.c_int64),
|
|
47
|
+
("LimitFlags", wintypes.DWORD),
|
|
48
|
+
("MinimumWorkingSetSize", ctypes.c_size_t),
|
|
49
|
+
("MaximumWorkingSetSize", ctypes.c_size_t),
|
|
50
|
+
("ActiveProcessLimit", wintypes.DWORD),
|
|
51
|
+
("Affinity", ctypes.c_size_t),
|
|
52
|
+
("PriorityClass", wintypes.DWORD),
|
|
53
|
+
("SchedulingClass", wintypes.DWORD),
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
class IO_COUNTERS(ctypes.Structure):
|
|
57
|
+
_fields_ = [
|
|
58
|
+
("ReadOperationCount", ctypes.c_uint64),
|
|
59
|
+
("WriteOperationCount", ctypes.c_uint64),
|
|
60
|
+
("OtherOperationCount", ctypes.c_uint64),
|
|
61
|
+
("ReadTransferCount", ctypes.c_uint64),
|
|
62
|
+
("WriteTransferCount", ctypes.c_uint64),
|
|
63
|
+
("OtherTransferCount", ctypes.c_uint64),
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
class JOBOBJECT_EXTENDED_LIMIT_INFORMATION(ctypes.Structure):
|
|
67
|
+
_fields_ = [
|
|
68
|
+
("BasicLimitInformation", JOBOBJECT_BASIC_LIMIT_INFORMATION),
|
|
69
|
+
("IoInfo", IO_COUNTERS),
|
|
70
|
+
("ProcessMemoryLimit", ctypes.c_size_t),
|
|
71
|
+
("JobMemoryLimit", ctypes.c_size_t),
|
|
72
|
+
("PeakProcessMemoryUsed", ctypes.c_size_t),
|
|
73
|
+
("PeakJobMemoryUsed", ctypes.c_size_t),
|
|
74
|
+
]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def pid_alive(pid: int) -> bool:
|
|
78
|
+
"""Return True when *pid* refers to a live process (safe liveness probe)."""
|
|
79
|
+
if pid is None or pid <= 0:
|
|
80
|
+
return False
|
|
81
|
+
if IS_WINDOWS:
|
|
82
|
+
kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
|
|
83
|
+
handle = kernel32.OpenProcess(_PROCESS_QUERY_LIMITED_INFORMATION, False, int(pid))
|
|
84
|
+
if not handle:
|
|
85
|
+
return False
|
|
86
|
+
try:
|
|
87
|
+
exit_code = wintypes.DWORD()
|
|
88
|
+
if not kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)):
|
|
89
|
+
return False
|
|
90
|
+
return exit_code.value == _STILL_ACTIVE
|
|
91
|
+
finally:
|
|
92
|
+
kernel32.CloseHandle(handle)
|
|
93
|
+
try:
|
|
94
|
+
reaped_pid, _ = os.waitpid(pid, os.WNOHANG)
|
|
95
|
+
if reaped_pid == pid:
|
|
96
|
+
return False
|
|
97
|
+
except (ChildProcessError, OSError):
|
|
98
|
+
pass
|
|
99
|
+
try:
|
|
100
|
+
os.kill(pid, 0)
|
|
101
|
+
except OSError as exc:
|
|
102
|
+
return exc.errno == errno.EPERM
|
|
103
|
+
return True
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _windows_new_job_object() -> Optional[Any]:
|
|
107
|
+
"""Create a kill-on-close Job Object; returns the handle or None on failure."""
|
|
108
|
+
kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
|
|
109
|
+
job = kernel32.CreateJobObjectW(None, None)
|
|
110
|
+
if not job:
|
|
111
|
+
return None
|
|
112
|
+
info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION()
|
|
113
|
+
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
|
114
|
+
if not kernel32.SetInformationJobObject(
|
|
115
|
+
job,
|
|
116
|
+
_JOB_OBJECT_EXTENDED_LIMIT_INFO_CLASS,
|
|
117
|
+
ctypes.byref(info),
|
|
118
|
+
ctypes.sizeof(info),
|
|
119
|
+
):
|
|
120
|
+
kernel32.CloseHandle(job)
|
|
121
|
+
return None
|
|
122
|
+
return job
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _windows_assign_to_job(job_handle: Any, proc: subprocess.Popen) -> bool:
|
|
126
|
+
kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
|
|
127
|
+
try:
|
|
128
|
+
return bool(kernel32.AssignProcessToJobObject(job_handle, int(proc._handle))) # noqa: SLF001
|
|
129
|
+
except Exception:
|
|
130
|
+
return False
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def containment_kwargs() -> Dict[str, Any]:
|
|
134
|
+
"""Pre-spawn kwargs giving the child its own process group/session on POSIX."""
|
|
135
|
+
if IS_WINDOWS:
|
|
136
|
+
return {}
|
|
137
|
+
return {"start_new_session": True}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def attach_containment(proc: subprocess.Popen) -> Optional[Any]:
|
|
141
|
+
"""Post-spawn OS containment for a child (Windows Job Object assignment)."""
|
|
142
|
+
if IS_WINDOWS:
|
|
143
|
+
job = _windows_new_job_object()
|
|
144
|
+
if job is not None and not _windows_assign_to_job(job, proc):
|
|
145
|
+
kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
|
|
146
|
+
kernel32.CloseHandle(job)
|
|
147
|
+
return None
|
|
148
|
+
return job
|
|
149
|
+
return None
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def close_job_handle(job_handle: Any) -> None:
|
|
153
|
+
"""Close a Job Object handle, triggering KILL_ON_JOB_CLOSE reaping. Never raises."""
|
|
154
|
+
if job_handle is None:
|
|
155
|
+
return
|
|
156
|
+
if IS_WINDOWS:
|
|
157
|
+
try:
|
|
158
|
+
ctypes.windll.kernel32.CloseHandle(job_handle) # type: ignore[attr-defined]
|
|
159
|
+
except Exception:
|
|
160
|
+
pass
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def kill_process_tree(pid: int) -> None:
|
|
164
|
+
"""Terminate *pid* and all of its descendants. Never raises."""
|
|
165
|
+
if pid is None or pid <= 0:
|
|
166
|
+
return
|
|
167
|
+
if IS_WINDOWS:
|
|
168
|
+
try:
|
|
169
|
+
subprocess.run( # nosec B603 B607
|
|
170
|
+
["taskkill", "/F", "/T", "/PID", str(pid)],
|
|
171
|
+
capture_output=True,
|
|
172
|
+
timeout=10,
|
|
173
|
+
check=False,
|
|
174
|
+
)
|
|
175
|
+
except Exception:
|
|
176
|
+
kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
|
|
177
|
+
PROCESS_TERMINATE = 0x0001
|
|
178
|
+
handle = kernel32.OpenProcess(PROCESS_TERMINATE, False, int(pid))
|
|
179
|
+
if handle:
|
|
180
|
+
try:
|
|
181
|
+
kernel32.TerminateProcess(handle, 137)
|
|
182
|
+
finally:
|
|
183
|
+
kernel32.CloseHandle(handle)
|
|
184
|
+
return
|
|
185
|
+
# POSIX: prefer killing the whole group (children share it via setsid).
|
|
186
|
+
try:
|
|
187
|
+
pgid = os.getpgid(pid)
|
|
188
|
+
except OSError:
|
|
189
|
+
pgid = None
|
|
190
|
+
try:
|
|
191
|
+
if pgid is not None and pgid != os.getpgrp():
|
|
192
|
+
os.killpg(pgid, signal.SIGKILL)
|
|
193
|
+
else:
|
|
194
|
+
os.kill(pid, signal.SIGKILL)
|
|
195
|
+
except OSError:
|
|
196
|
+
pass
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
# ---------------------------------------------------------------------------
|
|
200
|
+
# ProcessGuard registry
|
|
201
|
+
# ---------------------------------------------------------------------------
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
class ProcessGuard:
|
|
205
|
+
"""Registry of supervised subprocesses with guaranteed tree cleanup."""
|
|
206
|
+
|
|
207
|
+
def __init__(self) -> None:
|
|
208
|
+
self._lock = threading.Lock()
|
|
209
|
+
self._procs: List[subprocess.Popen] = []
|
|
210
|
+
self._jobs: List[Any] = []
|
|
211
|
+
|
|
212
|
+
def _prune_exited_locked(self) -> None:
|
|
213
|
+
"""Drop already-exited children from the registry (caller holds the lock)."""
|
|
214
|
+
alive = []
|
|
215
|
+
for proc in self._procs:
|
|
216
|
+
try:
|
|
217
|
+
if proc.poll() is None:
|
|
218
|
+
alive.append(proc)
|
|
219
|
+
except Exception:
|
|
220
|
+
alive.append(proc)
|
|
221
|
+
self._procs = alive
|
|
222
|
+
|
|
223
|
+
def register(self, proc: subprocess.Popen, job_handle: Optional[Any] = None) -> subprocess.Popen:
|
|
224
|
+
with self._lock:
|
|
225
|
+
self._prune_exited_locked()
|
|
226
|
+
self._procs.append(proc)
|
|
227
|
+
if job_handle is not None:
|
|
228
|
+
self._jobs.append(job_handle)
|
|
229
|
+
return proc
|
|
230
|
+
|
|
231
|
+
def unregister(self, proc: subprocess.Popen) -> None:
|
|
232
|
+
with self._lock:
|
|
233
|
+
if proc in self._procs:
|
|
234
|
+
self._procs.remove(proc)
|
|
235
|
+
|
|
236
|
+
def spawn(self, args: Iterable[str], **kwargs: Any) -> subprocess.Popen:
|
|
237
|
+
"""Popen with full OS containment (session leader on POSIX, job object on Windows)."""
|
|
238
|
+
popen_kwargs = dict(kwargs)
|
|
239
|
+
popen_kwargs.update(containment_kwargs())
|
|
240
|
+
proc = subprocess.Popen(list(args), **popen_kwargs) # nosec B603
|
|
241
|
+
job = attach_containment(proc)
|
|
242
|
+
self.register(proc, job)
|
|
243
|
+
return proc
|
|
244
|
+
|
|
245
|
+
def sweep(self, timeout: float = 5.0) -> None:
|
|
246
|
+
"""Kill every registered process tree and reap what we can."""
|
|
247
|
+
with self._lock:
|
|
248
|
+
procs = list(self._procs)
|
|
249
|
+
jobs = list(self._jobs)
|
|
250
|
+
self._procs.clear()
|
|
251
|
+
self._jobs.clear()
|
|
252
|
+
for proc in procs:
|
|
253
|
+
if proc.poll() is None:
|
|
254
|
+
kill_process_tree(proc.pid)
|
|
255
|
+
deadline = time.time() + timeout
|
|
256
|
+
for proc in procs:
|
|
257
|
+
remaining = max(0.05, deadline - time.time())
|
|
258
|
+
try:
|
|
259
|
+
proc.wait(timeout=remaining)
|
|
260
|
+
except Exception:
|
|
261
|
+
pass
|
|
262
|
+
if IS_WINDOWS:
|
|
263
|
+
kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
|
|
264
|
+
for job in jobs:
|
|
265
|
+
# Closing the kill-on-close handle makes the kernel reap survivors.
|
|
266
|
+
kernel32.CloseHandle(job)
|
|
267
|
+
|
|
268
|
+
def __enter__(self) -> "ProcessGuard":
|
|
269
|
+
return self
|
|
270
|
+
|
|
271
|
+
def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
|
|
272
|
+
self.sweep()
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
DEFAULT_GUARD = ProcessGuard()
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
# ---------------------------------------------------------------------------
|
|
279
|
+
# Signal / exit hooks
|
|
280
|
+
# ---------------------------------------------------------------------------
|
|
281
|
+
|
|
282
|
+
_installed_lock = threading.Lock()
|
|
283
|
+
_installed = False
|
|
284
|
+
_previous_handlers: Dict[int, Any] = {}
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _make_signal_handler(guard: ProcessGuard, signum: int):
|
|
288
|
+
def handler(received_signum, frame): # type: ignore[no-untyped-def]
|
|
289
|
+
guard.sweep()
|
|
290
|
+
previous = _previous_handlers.get(signum)
|
|
291
|
+
if callable(previous) and previous not in (signal.SIG_DFL, signal.SIG_IGN):
|
|
292
|
+
previous(received_signum, frame)
|
|
293
|
+
return
|
|
294
|
+
if received_signum == signal.SIGINT:
|
|
295
|
+
raise KeyboardInterrupt
|
|
296
|
+
# SIGTERM and friends: mimic default termination.
|
|
297
|
+
signal.signal(received_signum, signal.SIG_DFL)
|
|
298
|
+
os.kill(os.getpid(), received_signum)
|
|
299
|
+
|
|
300
|
+
return handler
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _atexit_sweep(guard: ProcessGuard) -> None:
|
|
304
|
+
try:
|
|
305
|
+
guard.sweep(timeout=2.0)
|
|
306
|
+
except Exception:
|
|
307
|
+
pass
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def install_signal_handlers(guard: ProcessGuard = None) -> bool: # type: ignore[assignment]
|
|
311
|
+
"""Register atexit + SIGINT/SIGTERM(+SIGHUP) sweeps. Idempotent. True when installed now."""
|
|
312
|
+
global _installed
|
|
313
|
+
guard = guard or DEFAULT_GUARD
|
|
314
|
+
with _installed_lock:
|
|
315
|
+
if _installed:
|
|
316
|
+
return False
|
|
317
|
+
signals = [signal.SIGINT, signal.SIGTERM]
|
|
318
|
+
if hasattr(signal, "SIGHUP"):
|
|
319
|
+
signals.append(signal.SIGHUP)
|
|
320
|
+
for signum in signals:
|
|
321
|
+
try:
|
|
322
|
+
_previous_handlers[signum] = signal.getsignal(signum)
|
|
323
|
+
signal.signal(signum, _make_signal_handler(guard, signum))
|
|
324
|
+
except (ValueError, OSError):
|
|
325
|
+
# Not the main thread of the main interpreter; skip this signal.
|
|
326
|
+
_previous_handlers.pop(signum, None)
|
|
327
|
+
atexit.register(_atexit_sweep, guard)
|
|
328
|
+
_installed = True
|
|
329
|
+
return True
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def uninstall_signal_handlers() -> None:
|
|
333
|
+
"""Restore handlers captured by install_signal_handlers (test support)."""
|
|
334
|
+
global _installed
|
|
335
|
+
with _installed_lock:
|
|
336
|
+
if not _installed:
|
|
337
|
+
return
|
|
338
|
+
for signum, previous in _previous_handlers.items():
|
|
339
|
+
try:
|
|
340
|
+
signal.signal(signum, previous)
|
|
341
|
+
except (ValueError, OSError):
|
|
342
|
+
pass
|
|
343
|
+
_previous_handlers.clear()
|
|
344
|
+
_installed = False
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
__all__ = [
|
|
348
|
+
"DEFAULT_GUARD",
|
|
349
|
+
"ProcessGuard",
|
|
350
|
+
"attach_containment",
|
|
351
|
+
"close_job_handle",
|
|
352
|
+
"containment_kwargs",
|
|
353
|
+
"install_signal_handlers",
|
|
354
|
+
"kill_process_tree",
|
|
355
|
+
"pid_alive",
|
|
356
|
+
"uninstall_signal_handlers",
|
|
357
|
+
]
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""Prometheus text-format exporter over the runtime metrics layer (stdlib only).
|
|
2
|
+
|
|
3
|
+
Renders a MetricsCollector as Prometheus exposition text without requiring
|
|
4
|
+
prometheus-client. An optional OpenTelemetry tracing bridge is exported
|
|
5
|
+
(init_otel_tracing / start_span); it degrades to silent no-ops when the
|
|
6
|
+
opentelemetry packages are not installed and is never auto-enabled.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import contextlib
|
|
12
|
+
import os
|
|
13
|
+
import tempfile
|
|
14
|
+
from typing import Any, Dict, Iterator, List, Optional
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
from opentelemetry import trace as _otel_trace
|
|
18
|
+
except ImportError:
|
|
19
|
+
_otel_trace = None
|
|
20
|
+
|
|
21
|
+
_tracer: Any = None
|
|
22
|
+
|
|
23
|
+
BUCKETS: tuple = (0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0)
|
|
24
|
+
|
|
25
|
+
_DURATION = "letitloop_contract_duration_seconds"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _escape_label(value: str) -> str:
|
|
29
|
+
return value.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _render_labels(extra_labels: Optional[Dict[str, str]], **base: str) -> str:
|
|
33
|
+
labels: Dict[str, str] = {k: str(v) for k, v in base.items() if v}
|
|
34
|
+
if extra_labels:
|
|
35
|
+
labels.update({str(k): str(v) for k, v in extra_labels.items()})
|
|
36
|
+
if not labels:
|
|
37
|
+
return ""
|
|
38
|
+
inner = ",".join(f'{key}="{_escape_label(val)}"' for key, val in sorted(labels.items()))
|
|
39
|
+
return "{" + inner + "}"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _format_value(value: float) -> str:
|
|
43
|
+
value = float(value)
|
|
44
|
+
if value.is_integer():
|
|
45
|
+
return str(int(value))
|
|
46
|
+
return repr(value)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _record_field(record: Any, name: str) -> Any:
|
|
50
|
+
if isinstance(record, dict):
|
|
51
|
+
return record.get(name)
|
|
52
|
+
return getattr(record, name, None)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _histogram_section(records: List[Any], extra_labels: Optional[Dict[str, str]]) -> List[str]:
|
|
56
|
+
lines = [
|
|
57
|
+
f"# HELP {_DURATION} Contract phase durations in seconds.",
|
|
58
|
+
f"# TYPE {_DURATION} histogram",
|
|
59
|
+
]
|
|
60
|
+
groups: Dict[str, List[float]] = {}
|
|
61
|
+
for record in records:
|
|
62
|
+
phase = _record_field(record, "phase") or ""
|
|
63
|
+
elapsed = _record_field(record, "elapsed_sec")
|
|
64
|
+
if elapsed is None:
|
|
65
|
+
continue
|
|
66
|
+
groups.setdefault(str(phase), []).append(float(elapsed))
|
|
67
|
+
if not groups:
|
|
68
|
+
# No phase data: omit the family entirely (an unlabeled zero series
|
|
69
|
+
# would be format-valid but semantically ambiguous for scrapers).
|
|
70
|
+
return []
|
|
71
|
+
for phase in sorted(groups):
|
|
72
|
+
values = groups[phase]
|
|
73
|
+
for bound in BUCKETS:
|
|
74
|
+
count = sum(1 for v in values if v <= bound)
|
|
75
|
+
labels = _render_labels(extra_labels, phase=phase, le=_format_value(bound))
|
|
76
|
+
lines.append(f"{_DURATION}_bucket{labels} {count}")
|
|
77
|
+
inf_labels = _render_labels(extra_labels, phase=phase, le="+Inf")
|
|
78
|
+
lines.append(f"{_DURATION}_bucket{inf_labels} {len(values)}")
|
|
79
|
+
base_labels = _render_labels(extra_labels, phase=phase)
|
|
80
|
+
lines.append(f"{_DURATION}_sum{base_labels} {_format_value(sum(values))}")
|
|
81
|
+
lines.append(f"{_DURATION}_count{base_labels} {len(values)}")
|
|
82
|
+
return lines
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _contract_statuses(collector: Any) -> Dict[str, int]:
|
|
86
|
+
by_status = getattr(collector, "contracts_by_status", None)
|
|
87
|
+
if isinstance(by_status, dict) and by_status:
|
|
88
|
+
out: Dict[str, int] = {}
|
|
89
|
+
for key, value in by_status.items():
|
|
90
|
+
status = str(key)
|
|
91
|
+
out[status] = out.get(status, 0) + int(value)
|
|
92
|
+
return out
|
|
93
|
+
derived: Dict[str, int] = {}
|
|
94
|
+
attempts = getattr(collector, "attempts", None)
|
|
95
|
+
if isinstance(attempts, dict):
|
|
96
|
+
for info in attempts.values():
|
|
97
|
+
if isinstance(info, dict) and info.get("status") is not None:
|
|
98
|
+
status = str(info["status"])
|
|
99
|
+
derived[status] = derived.get(status, 0) + 1
|
|
100
|
+
return derived
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _contracts_section(collector: Any, extra_labels: Optional[Dict[str, str]]) -> List[str]:
|
|
104
|
+
statuses = _contract_statuses(collector)
|
|
105
|
+
if not statuses:
|
|
106
|
+
return []
|
|
107
|
+
lines = [
|
|
108
|
+
"# HELP letitloop_contracts_total Contracts by terminal status.",
|
|
109
|
+
"# TYPE letitloop_contracts_total counter",
|
|
110
|
+
]
|
|
111
|
+
for status in sorted(statuses):
|
|
112
|
+
labels = _render_labels(extra_labels, status=status)
|
|
113
|
+
lines.append(f"letitloop_contracts_total{labels} {int(statuses[status])}")
|
|
114
|
+
return lines
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _budget_section(collector: Any, extra_labels: Optional[Dict[str, str]]) -> List[str]:
|
|
118
|
+
usage = getattr(collector, "token_usage", None) or {}
|
|
119
|
+
prompt = int(usage.get("prompt", 0))
|
|
120
|
+
completion = int(usage.get("completion", 0))
|
|
121
|
+
return [
|
|
122
|
+
"# HELP letitloop_budget_tokens_total LLM tokens consumed by type.",
|
|
123
|
+
"# TYPE letitloop_budget_tokens_total counter",
|
|
124
|
+
f"letitloop_budget_tokens_total{_render_labels(extra_labels, type='prompt')} {prompt}",
|
|
125
|
+
f"letitloop_budget_tokens_total{_render_labels(extra_labels, type='completion')} {completion}",
|
|
126
|
+
]
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _escalations_section(collector: Any, extra_labels: Optional[Dict[str, str]]) -> List[str]:
|
|
130
|
+
counters = getattr(collector, "counters", None) or {}
|
|
131
|
+
escalations = int(counters.get("three_strike_escalations", 0))
|
|
132
|
+
return [
|
|
133
|
+
"# HELP letitloop_three_strike_escalations_total Three-strike escalation events.",
|
|
134
|
+
"# TYPE letitloop_three_strike_escalations_total counter",
|
|
135
|
+
f"letitloop_three_strike_escalations_total{_render_labels(extra_labels)} {escalations}",
|
|
136
|
+
]
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def render_prometheus(collector: Any, extra_labels: Optional[Dict[str, str]] = None) -> str:
|
|
140
|
+
"""Render collector state as Prometheus exposition text."""
|
|
141
|
+
records = list(getattr(collector, "phases", None) or [])
|
|
142
|
+
sections = [
|
|
143
|
+
_histogram_section(records, extra_labels),
|
|
144
|
+
_contracts_section(collector, extra_labels),
|
|
145
|
+
_budget_section(collector, extra_labels),
|
|
146
|
+
_escalations_section(collector, extra_labels),
|
|
147
|
+
]
|
|
148
|
+
body = "\n".join("\n".join(section) for section in sections if section)
|
|
149
|
+
return body + "\n"
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def write_prometheus_file(collector: Any, path: str) -> None:
|
|
153
|
+
"""Atomically write exposition text to path (tmp file + os.replace)."""
|
|
154
|
+
text = render_prometheus(collector)
|
|
155
|
+
parent = os.path.dirname(path)
|
|
156
|
+
os.makedirs(parent, exist_ok=True)
|
|
157
|
+
fd, tmp_path = tempfile.mkstemp(dir=parent or ".", prefix=".prom_", suffix=".tmp")
|
|
158
|
+
try:
|
|
159
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
160
|
+
handle.write(text)
|
|
161
|
+
os.replace(tmp_path, path)
|
|
162
|
+
except Exception:
|
|
163
|
+
with contextlib.suppress(OSError):
|
|
164
|
+
os.unlink(tmp_path)
|
|
165
|
+
raise
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def init_otel_tracing(endpoint: Optional[str] = None) -> Any:
|
|
169
|
+
"""Best-effort OpenTelemetry tracer setup.
|
|
170
|
+
|
|
171
|
+
Returns a tracer, or None when opentelemetry is unavailable. The optional
|
|
172
|
+
OTLP HTTP exporter is attached when endpoint is given and installed;
|
|
173
|
+
any failure degrades silently to a provider without an exporter.
|
|
174
|
+
"""
|
|
175
|
+
global _tracer
|
|
176
|
+
if _otel_trace is None:
|
|
177
|
+
return None
|
|
178
|
+
if _tracer is not None:
|
|
179
|
+
return _tracer
|
|
180
|
+
try:
|
|
181
|
+
from opentelemetry.sdk.trace import TracerProvider
|
|
182
|
+
|
|
183
|
+
provider = TracerProvider()
|
|
184
|
+
if endpoint:
|
|
185
|
+
try:
|
|
186
|
+
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
|
187
|
+
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
|
188
|
+
|
|
189
|
+
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint=endpoint)))
|
|
190
|
+
except ImportError:
|
|
191
|
+
pass
|
|
192
|
+
_otel_trace.set_tracer_provider(provider)
|
|
193
|
+
_tracer = provider.get_tracer("letitloop")
|
|
194
|
+
except Exception:
|
|
195
|
+
return None
|
|
196
|
+
return _tracer
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
@contextlib.contextmanager
|
|
200
|
+
def start_span(name: str, attributes: Optional[Dict[str, Any]] = None) -> Iterator[Any]:
|
|
201
|
+
"""Context manager yielding an OTel span, or None as a no-op when tracing is off."""
|
|
202
|
+
tracer = _tracer
|
|
203
|
+
if tracer is None or _otel_trace is None:
|
|
204
|
+
yield None
|
|
205
|
+
return
|
|
206
|
+
with tracer.start_as_current_span(name, attributes=dict(attributes or {})) as span:
|
|
207
|
+
yield span
|