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
orchestrator/lock.py
ADDED
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
"""Lock file — prevents concurrent execution of the same goal."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import socket
|
|
7
|
+
import sys
|
|
8
|
+
import time
|
|
9
|
+
from datetime import datetime, timezone
|
|
10
|
+
from typing import Optional
|
|
11
|
+
|
|
12
|
+
LOCK_FILENAME = ".goal.lock"
|
|
13
|
+
STALE_TIMEOUT_SEC = 300 # 5 minutes
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class LockError(Exception):
|
|
17
|
+
"""Raised when lock cannot be acquired."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class LockHeldError(LockError):
|
|
21
|
+
"""Raised when another process holds the lock."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class LockStaleError(LockHeldError):
|
|
25
|
+
"""Raised when lock is held but appears stale."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class FileLock:
|
|
29
|
+
"""Cross-process file lock (best-effort) for concurrent ledger writes.
|
|
30
|
+
|
|
31
|
+
Uses an exclusive lock file with O_CREAT|O_EXCL and a bounded wait loop.
|
|
32
|
+
On Windows there is no flock(); the atomic-create + stale-PID check is the
|
|
33
|
+
pragmatic portable approach. Raises LockHeldError if not acquired within
|
|
34
|
+
`timeout_sec`.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(self, path: str, timeout_sec: float = 30.0, poll_sec: float = 0.1):
|
|
38
|
+
self.path = path
|
|
39
|
+
self.timeout_sec = timeout_sec
|
|
40
|
+
self.poll_sec = poll_sec
|
|
41
|
+
self._acquired = False
|
|
42
|
+
|
|
43
|
+
def acquire(self) -> None:
|
|
44
|
+
deadline = time.monotonic() + self.timeout_sec
|
|
45
|
+
while True:
|
|
46
|
+
try:
|
|
47
|
+
fd = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
|
|
48
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
49
|
+
json.dump(
|
|
50
|
+
{
|
|
51
|
+
"pid": os.getpid(),
|
|
52
|
+
"hostname": socket.gethostname(),
|
|
53
|
+
"created_at": datetime.now(timezone.utc).isoformat(),
|
|
54
|
+
},
|
|
55
|
+
f,
|
|
56
|
+
)
|
|
57
|
+
self._acquired = True
|
|
58
|
+
return
|
|
59
|
+
except FileExistsError:
|
|
60
|
+
if time.monotonic() >= deadline:
|
|
61
|
+
raise LockHeldError(f"File lock not acquired within {self.timeout_sec}s: {self.path}")
|
|
62
|
+
time.sleep(self.poll_sec)
|
|
63
|
+
|
|
64
|
+
def release(self) -> None:
|
|
65
|
+
if not self._acquired:
|
|
66
|
+
return
|
|
67
|
+
try:
|
|
68
|
+
os.remove(self.path)
|
|
69
|
+
except OSError:
|
|
70
|
+
pass
|
|
71
|
+
self._acquired = False
|
|
72
|
+
|
|
73
|
+
def __enter__(self) -> "FileLock":
|
|
74
|
+
self.acquire()
|
|
75
|
+
return self
|
|
76
|
+
|
|
77
|
+
def __exit__(self, *exc) -> None:
|
|
78
|
+
self.release()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _process_start_token(pid: int) -> Optional[str]:
|
|
82
|
+
"""Return a stable PID start-time token.
|
|
83
|
+
|
|
84
|
+
The token is deliberately opaque. It is compared only with a token
|
|
85
|
+
produced by the same platform implementation. Returning None means
|
|
86
|
+
that the platform cannot establish process identity.
|
|
87
|
+
"""
|
|
88
|
+
if not isinstance(pid, int) or pid <= 0:
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
if sys.platform == "win32":
|
|
92
|
+
try:
|
|
93
|
+
import ctypes
|
|
94
|
+
from ctypes import wintypes
|
|
95
|
+
|
|
96
|
+
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
|
|
97
|
+
handle = ctypes.windll.kernel32.OpenProcess(
|
|
98
|
+
PROCESS_QUERY_LIMITED_INFORMATION,
|
|
99
|
+
False,
|
|
100
|
+
pid,
|
|
101
|
+
)
|
|
102
|
+
if not handle:
|
|
103
|
+
return None
|
|
104
|
+
try:
|
|
105
|
+
creation = wintypes.FILETIME()
|
|
106
|
+
exit_time = wintypes.FILETIME()
|
|
107
|
+
kernel_time = wintypes.FILETIME()
|
|
108
|
+
user_time = wintypes.FILETIME()
|
|
109
|
+
ok = ctypes.windll.kernel32.GetProcessTimes(
|
|
110
|
+
handle,
|
|
111
|
+
ctypes.byref(creation),
|
|
112
|
+
ctypes.byref(exit_time),
|
|
113
|
+
ctypes.byref(kernel_time),
|
|
114
|
+
ctypes.byref(user_time),
|
|
115
|
+
)
|
|
116
|
+
if not ok:
|
|
117
|
+
return None
|
|
118
|
+
value = (int(creation.dwHighDateTime) << 32) | int(creation.dwLowDateTime)
|
|
119
|
+
return f"win:{value}"
|
|
120
|
+
finally:
|
|
121
|
+
ctypes.windll.kernel32.CloseHandle(handle)
|
|
122
|
+
except (AttributeError, OSError, TypeError, ValueError):
|
|
123
|
+
return None
|
|
124
|
+
|
|
125
|
+
if sys.platform == "darwin":
|
|
126
|
+
try:
|
|
127
|
+
import subprocess
|
|
128
|
+
|
|
129
|
+
out = subprocess.check_output(
|
|
130
|
+
["ps", "-p", str(pid), "-o", "lstart="],
|
|
131
|
+
stderr=subprocess.DEVNULL,
|
|
132
|
+
text=True,
|
|
133
|
+
timeout=1,
|
|
134
|
+
).strip()
|
|
135
|
+
if out:
|
|
136
|
+
return f"mac:{out}"
|
|
137
|
+
except (subprocess.SubprocessError, OSError, ValueError):
|
|
138
|
+
pass
|
|
139
|
+
|
|
140
|
+
proc_stat = f"/proc/{pid}/stat"
|
|
141
|
+
try:
|
|
142
|
+
with open(proc_stat, "r", encoding="utf-8") as f:
|
|
143
|
+
line = f.read()
|
|
144
|
+
closing_paren = line.rfind(")")
|
|
145
|
+
if closing_paren >= 0:
|
|
146
|
+
fields = line[closing_paren + 2 :].split()
|
|
147
|
+
# The suffix begins at field 3; starttime is field 22.
|
|
148
|
+
if len(fields) > 19:
|
|
149
|
+
return f"proc:{fields[19]}"
|
|
150
|
+
except (FileNotFoundError, OSError, UnicodeDecodeError):
|
|
151
|
+
pass
|
|
152
|
+
|
|
153
|
+
try:
|
|
154
|
+
import psutil
|
|
155
|
+
|
|
156
|
+
return f"psutil:{psutil.Process(pid).create_time():.6f}"
|
|
157
|
+
except (ImportError, OSError, ValueError, TypeError):
|
|
158
|
+
return None
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _pid_alive(pid: int, expected_start_token: Optional[str] = None) -> bool:
|
|
162
|
+
if not pid or pid <= 0:
|
|
163
|
+
return False
|
|
164
|
+
|
|
165
|
+
if expected_start_token is not None:
|
|
166
|
+
actual_start_token = _process_start_token(pid)
|
|
167
|
+
return actual_start_token is not None and actual_start_token == expected_start_token
|
|
168
|
+
|
|
169
|
+
if sys.platform == "win32":
|
|
170
|
+
try:
|
|
171
|
+
import ctypes
|
|
172
|
+
|
|
173
|
+
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
|
|
174
|
+
ERROR_ACCESS_DENIED = 5
|
|
175
|
+
handle = ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
|
|
176
|
+
if not handle:
|
|
177
|
+
# If access is denied, the process exists and is alive
|
|
178
|
+
err = ctypes.GetLastError()
|
|
179
|
+
return err == ERROR_ACCESS_DENIED
|
|
180
|
+
ctypes.windll.kernel32.CloseHandle(handle)
|
|
181
|
+
return True
|
|
182
|
+
except (AttributeError, OSError, TypeError, ValueError):
|
|
183
|
+
return False
|
|
184
|
+
|
|
185
|
+
try:
|
|
186
|
+
os.kill(pid, 0)
|
|
187
|
+
except ProcessLookupError:
|
|
188
|
+
return False
|
|
189
|
+
except PermissionError:
|
|
190
|
+
return True
|
|
191
|
+
except OSError:
|
|
192
|
+
return False
|
|
193
|
+
return True
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _lock_path(run_dir: str) -> str:
|
|
197
|
+
return os.path.join(run_dir, LOCK_FILENAME)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _read_lock(run_dir: str) -> Optional[dict]:
|
|
201
|
+
path = _lock_path(run_dir)
|
|
202
|
+
if not os.path.isfile(path):
|
|
203
|
+
return None
|
|
204
|
+
try:
|
|
205
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
206
|
+
return json.load(f)
|
|
207
|
+
except (json.JSONDecodeError, OSError):
|
|
208
|
+
return None
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _build_lock_payload(goal_id: str) -> dict:
|
|
212
|
+
now_iso = datetime.now(timezone.utc).isoformat()
|
|
213
|
+
cmd_str = " ".join(sys.argv) if hasattr(sys, "argv") else ""
|
|
214
|
+
cmdline_hash = hashlib.sha256(cmd_str.encode("utf-8", errors="replace")).hexdigest()[:8]
|
|
215
|
+
payload = {
|
|
216
|
+
"goal_id": goal_id,
|
|
217
|
+
"pid": os.getpid(),
|
|
218
|
+
"hostname": socket.gethostname(),
|
|
219
|
+
"created_at": now_iso,
|
|
220
|
+
"heartbeat": now_iso,
|
|
221
|
+
"cmdline_hash": cmdline_hash,
|
|
222
|
+
}
|
|
223
|
+
start_token = _process_start_token(os.getpid())
|
|
224
|
+
if start_token is not None:
|
|
225
|
+
payload["process_start_token"] = start_token
|
|
226
|
+
return payload
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _write_lock(run_dir: str, goal_id: str) -> dict:
|
|
230
|
+
os.makedirs(run_dir, exist_ok=True)
|
|
231
|
+
lock_data = _build_lock_payload(goal_id)
|
|
232
|
+
path = _lock_path(run_dir)
|
|
233
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
234
|
+
json.dump(lock_data, f, indent=2)
|
|
235
|
+
return lock_data
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _remove_lock(run_dir: str) -> None:
|
|
239
|
+
path = _lock_path(run_dir)
|
|
240
|
+
try:
|
|
241
|
+
os.remove(path)
|
|
242
|
+
except (FileNotFoundError, OSError):
|
|
243
|
+
pass
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _lock_is_stale(run_dir: str) -> bool:
|
|
247
|
+
lock = _read_lock(run_dir)
|
|
248
|
+
if lock is None:
|
|
249
|
+
return False
|
|
250
|
+
lock_pid = lock.get("pid")
|
|
251
|
+
lock_host = lock.get("hostname")
|
|
252
|
+
if lock_host == socket.gethostname() and lock_pid:
|
|
253
|
+
expected_token = lock.get("process_start_token")
|
|
254
|
+
if expected_token is not None:
|
|
255
|
+
if not _pid_alive(lock_pid, expected_token):
|
|
256
|
+
return True
|
|
257
|
+
elif not _pid_alive(lock_pid):
|
|
258
|
+
return True
|
|
259
|
+
|
|
260
|
+
# Heartbeat is the authoritative activity signal. created_at is used
|
|
261
|
+
# only for legacy locks that have no heartbeat.
|
|
262
|
+
reference = lock.get("heartbeat") or lock.get("created_at")
|
|
263
|
+
if not reference:
|
|
264
|
+
return True
|
|
265
|
+
try:
|
|
266
|
+
ref_dt = datetime.fromisoformat(reference)
|
|
267
|
+
age = (datetime.now(timezone.utc) - ref_dt).total_seconds()
|
|
268
|
+
return age > STALE_TIMEOUT_SEC
|
|
269
|
+
except (ValueError, TypeError):
|
|
270
|
+
return True
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def touch_lock_heartbeat(run_dir: str) -> None:
|
|
274
|
+
lock = _read_lock(run_dir)
|
|
275
|
+
if lock and lock.get("pid") == os.getpid():
|
|
276
|
+
lock["heartbeat"] = datetime.now(timezone.utc).isoformat()
|
|
277
|
+
path = _lock_path(run_dir)
|
|
278
|
+
tmp_path = path + f".tmp.{os.getpid()}_{time.time_ns()}"
|
|
279
|
+
try:
|
|
280
|
+
with open(tmp_path, "w", encoding="utf-8") as f:
|
|
281
|
+
json.dump(lock, f, indent=2)
|
|
282
|
+
os.replace(tmp_path, path)
|
|
283
|
+
except OSError:
|
|
284
|
+
if os.path.exists(tmp_path):
|
|
285
|
+
try:
|
|
286
|
+
os.remove(tmp_path)
|
|
287
|
+
except OSError:
|
|
288
|
+
pass
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def acquire_lock(goal_id: str, run_dir: str, force: bool = False) -> dict:
|
|
292
|
+
"""Acquire execution lock for a goal.
|
|
293
|
+
|
|
294
|
+
Uses atomic file creation (O_CREAT|O_EXCL) to prevent TOCTOU races.
|
|
295
|
+
Falls back to read-then-decide if the lock file already exists.
|
|
296
|
+
|
|
297
|
+
Args:
|
|
298
|
+
goal_id: Unique goal identifier.
|
|
299
|
+
run_dir: Run directory where lock file lives.
|
|
300
|
+
force: If True, force-acquire by removing stale or existing lock.
|
|
301
|
+
|
|
302
|
+
Returns:
|
|
303
|
+
Lock data dict.
|
|
304
|
+
|
|
305
|
+
Raises:
|
|
306
|
+
LockHeldError: Another process holds a non-stale lock.
|
|
307
|
+
"""
|
|
308
|
+
os.makedirs(run_dir, exist_ok=True)
|
|
309
|
+
lock_path = _lock_path(run_dir)
|
|
310
|
+
lock_data = _build_lock_payload(goal_id)
|
|
311
|
+
|
|
312
|
+
try:
|
|
313
|
+
fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
|
|
314
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
315
|
+
json.dump(lock_data, f, indent=2)
|
|
316
|
+
return lock_data
|
|
317
|
+
except FileExistsError:
|
|
318
|
+
pass
|
|
319
|
+
|
|
320
|
+
existing = _read_lock(run_dir)
|
|
321
|
+
if existing is None:
|
|
322
|
+
_remove_lock(run_dir)
|
|
323
|
+
return acquire_lock(goal_id, run_dir, force=False)
|
|
324
|
+
if force:
|
|
325
|
+
_remove_lock(run_dir)
|
|
326
|
+
return acquire_lock(goal_id, run_dir, force=False)
|
|
327
|
+
if _lock_is_stale(run_dir):
|
|
328
|
+
raise LockStaleError(
|
|
329
|
+
f"Lock for goal '{goal_id}' is stale (held by PID {existing.get('pid', '?')} "
|
|
330
|
+
f"since {existing.get('created_at', '?')}). Use force=True to override."
|
|
331
|
+
)
|
|
332
|
+
raise LockHeldError(
|
|
333
|
+
f"Goal '{goal_id}' is already locked by PID {existing.get('pid', '?')} "
|
|
334
|
+
f"on {existing.get('hostname', '?')} (since {existing.get('created_at', '?')}). "
|
|
335
|
+
"Wait for it to complete or use force=True."
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _read_lock_snapshot(run_dir: str):
|
|
340
|
+
"""Return (raw_bytes, parsed_lock), or (None, None) if unavailable."""
|
|
341
|
+
path = _lock_path(run_dir)
|
|
342
|
+
try:
|
|
343
|
+
with open(path, "rb") as f:
|
|
344
|
+
raw = f.read()
|
|
345
|
+
return raw, json.loads(raw.decode("utf-8"))
|
|
346
|
+
except (FileNotFoundError, OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
347
|
+
return None, None
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def release_lock(run_dir: str) -> bool:
|
|
351
|
+
"""Release the current process's lock without deleting a replacement lock.
|
|
352
|
+
|
|
353
|
+
acquire_lock() returns the lock-data dict written to the lock file. Callers
|
|
354
|
+
may retain that dict as an ownership token, although release_lock() also
|
|
355
|
+
protects itself by comparing the lock bytes immediately before unlinking.
|
|
356
|
+
|
|
357
|
+
Returns True if this process's unchanged lock was released, otherwise False.
|
|
358
|
+
"""
|
|
359
|
+
path = _lock_path(run_dir)
|
|
360
|
+
first_raw, lock = _read_lock_snapshot(run_dir)
|
|
361
|
+
if first_raw is None or lock is None:
|
|
362
|
+
return False
|
|
363
|
+
|
|
364
|
+
lock_pid = lock.get("pid")
|
|
365
|
+
if lock_pid is not None and lock_pid != os.getpid():
|
|
366
|
+
return False
|
|
367
|
+
|
|
368
|
+
second_raw, current_lock = _read_lock_snapshot(run_dir)
|
|
369
|
+
if second_raw is None or current_lock is None or second_raw != first_raw or current_lock != lock:
|
|
370
|
+
return False
|
|
371
|
+
|
|
372
|
+
try:
|
|
373
|
+
os.remove(path)
|
|
374
|
+
except FileNotFoundError:
|
|
375
|
+
return False
|
|
376
|
+
except OSError:
|
|
377
|
+
return False
|
|
378
|
+
return True
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def is_locked(run_dir: str) -> bool:
|
|
382
|
+
"""Check if a lock exists (regardless of staleness)."""
|
|
383
|
+
return _read_lock(run_dir) is not None
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def is_locked_by_other(run_dir: str) -> bool:
|
|
387
|
+
"""Check if another process (PID+hostname) holds the lock."""
|
|
388
|
+
lock = _read_lock(run_dir)
|
|
389
|
+
if lock is None:
|
|
390
|
+
return False
|
|
391
|
+
lock_pid = lock.get("pid")
|
|
392
|
+
lock_host = lock.get("hostname")
|
|
393
|
+
if lock_pid is None:
|
|
394
|
+
return False
|
|
395
|
+
if lock_pid != os.getpid():
|
|
396
|
+
return True
|
|
397
|
+
if lock_host and lock_host != socket.gethostname():
|
|
398
|
+
return True
|
|
399
|
+
return False
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def lock_info(run_dir: str) -> Optional[dict]:
|
|
403
|
+
"""Return lock info dict, or None if not locked."""
|
|
404
|
+
return _read_lock(run_dir)
|