@alexgreensh/token-optimizer 5.13.77 → 5.13.78
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.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/package.json +1 -1
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +87 -203
- package/skills/token-optimizer/scripts/_measure/keepwarm_auto.py +42 -14
- package/skills/token-optimizer/scripts/_measure/keepwarm_rearm.py +89 -100
- package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +74 -76
- package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +8 -3
- package/skills/token-optimizer/scripts/hook_provenance.py +7 -5
- package/skills/token-optimizer/scripts/measure.py +2 -2
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
"name": "token-optimizer",
|
|
14
14
|
"source": "./",
|
|
15
15
|
"description": "Audit, fix, and monitor Claude Code context window usage. Find the ghost tokens.",
|
|
16
|
-
"version": "5.13.
|
|
16
|
+
"version": "5.13.78",
|
|
17
17
|
"author": {
|
|
18
18
|
"name": "Alex Greenshpun",
|
|
19
19
|
"url": "https://linkedin.com/in/alexgreensh"
|
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
"name": "token-optimizer-cowork",
|
|
56
56
|
"source": "./cowork/token-optimizer",
|
|
57
57
|
"description": "Token Optimizer for Claude Cowork \u2014 full skills + Cowork-native hooks (beta). Install THIS in Cowork; the standard token-optimizer entry is for desktop Claude Code.",
|
|
58
|
-
"version": "5.13.
|
|
58
|
+
"version": "5.13.78",
|
|
59
59
|
"author": {
|
|
60
60
|
"name": "Alex Greenshpun",
|
|
61
61
|
"url": "https://linkedin.com/in/alexgreensh"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alexgreensh/token-optimizer",
|
|
3
|
-
"version": "5.13.
|
|
3
|
+
"version": "5.13.78",
|
|
4
4
|
"description": "Token Optimizer for Claude Code cloud sessions: the real plugin, installed by your cloud environment's setup script.",
|
|
5
5
|
"license": "PolyForm-Noncommercial-1.0.0",
|
|
6
6
|
"author": "Alex Greenshpun (https://linkedin.com/in/alexgreensh)",
|
|
@@ -391,57 +391,29 @@ def _keepwarm_sidecar_path():
|
|
|
391
391
|
|
|
392
392
|
|
|
393
393
|
def _keepwarm_lock():
|
|
394
|
-
"""Serialize
|
|
394
|
+
"""Serialize pause mutations until the writer releases its fd."""
|
|
395
395
|
from . import keepwarm_rearm
|
|
396
396
|
_measure_facade = _compat.facade()
|
|
397
397
|
deadline = _measure_facade.current_deadline()
|
|
398
398
|
timeout = min(0.075, deadline.remaining()) if deadline is not None else 0.075
|
|
399
|
-
with keepwarm_rearm.
|
|
399
|
+
with keepwarm_rearm.state_lock(_measure_facade.SNAPSHOT_DIR, timeout) as acquired:
|
|
400
400
|
yield acquired
|
|
401
401
|
|
|
402
402
|
|
|
403
403
|
def _keepwarm_append_line(path, line):
|
|
404
|
-
"""Append
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
an existing one) so a group/other-readable sidecar can never exist, then
|
|
409
|
-
append. Returns True on success, False on any OSError. Used by the arm-writer
|
|
410
|
-
and the ping ledger; both serialize through the same lock so an
|
|
411
|
-
append can never tear against a concurrent compaction rewrite.
|
|
412
|
-
"""
|
|
413
|
-
_measure_facade = _compat.facade()
|
|
404
|
+
"""Append with the lock that owns this file."""
|
|
405
|
+
from . import mod_action_booking
|
|
406
|
+
facade = _compat.facade()
|
|
407
|
+
lock = mod_action_booking._lock(facade) if path == facade._keepwarm_ledger_path() else facade._keepwarm_lock()
|
|
414
408
|
try:
|
|
415
|
-
with
|
|
416
|
-
if not
|
|
417
|
-
return False
|
|
418
|
-
try:
|
|
419
|
-
_measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
|
|
420
|
-
except OSError:
|
|
421
|
-
return False
|
|
422
|
-
try:
|
|
423
|
-
# Open the append target with O_NOFOLLOW so a pre-planted symlink
|
|
424
|
-
# at this path (same-UID TOCTOU, security M3) cannot redirect our
|
|
425
|
-
# ledger/state JSON into a victim file: ELOOP -> hard skip. Create
|
|
426
|
-
# 0600 if absent. The single fd we write to is the file itself, so
|
|
427
|
-
# no separate chmod-then-open race remains.
|
|
428
|
-
flags = _measure_facade.os.O_APPEND | _measure_facade.os.O_CREAT | _measure_facade.os.O_WRONLY
|
|
429
|
-
if hasattr(_measure_facade.os, "O_NOFOLLOW"):
|
|
430
|
-
flags |= _measure_facade.os.O_NOFOLLOW
|
|
431
|
-
try:
|
|
432
|
-
fd = _measure_facade.os.open(str(path), flags, 0o600)
|
|
433
|
-
except OSError:
|
|
434
|
-
# ELOOP (symlink) or any open failure -> refuse to write.
|
|
435
|
-
return False
|
|
436
|
-
try:
|
|
437
|
-
with _measure_facade.os.fdopen(fd, "a", encoding="utf-8") as fh:
|
|
438
|
-
fh.write(line)
|
|
439
|
-
except OSError:
|
|
440
|
-
return False
|
|
441
|
-
except OSError:
|
|
409
|
+
with lock as held:
|
|
410
|
+
if not held:
|
|
442
411
|
return False
|
|
412
|
+
flags = facade.os.O_APPEND | facade.os.O_CREAT | facade.os.O_WRONLY | getattr(facade.os, 'O_NOFOLLOW', 0)
|
|
413
|
+
with facade.os.fdopen(facade.os.open(path, flags, 0o600), 'a', encoding='utf-8') as stream:
|
|
414
|
+
stream.write(line)
|
|
443
415
|
return True
|
|
444
|
-
except
|
|
416
|
+
except OSError:
|
|
445
417
|
return False
|
|
446
418
|
|
|
447
419
|
|
|
@@ -578,13 +550,16 @@ def write_keepwarm_arm_record(session_id, transcript_path, now=None, *, parent_p
|
|
|
578
550
|
tp = _measure_facade.Path(transcript_path)
|
|
579
551
|
now = _measure_facade.time.time() if now is None else now
|
|
580
552
|
snapshot = tp.stat()
|
|
553
|
+
import stat
|
|
554
|
+
if not stat.S_ISREG(snapshot.st_mode):
|
|
555
|
+
return None
|
|
581
556
|
turn = None
|
|
582
557
|
if parent_pid is not None:
|
|
583
558
|
turn = keepwarm_safety.terminal_turn(tp)
|
|
584
559
|
turn_epoch = _measure_facade._keepwarm_iso_to_epoch(turn["timestamp"]) if turn else None
|
|
585
560
|
if (turn_epoch is None or turn_epoch > now or not _measure_facade._keepwarm_valid_arg(session_id)
|
|
586
|
-
or "subagents" in tp.parts or keepwarm_safety.
|
|
587
|
-
_measure_facade.SNAPSHOT_DIR, session_id, turn_epoch)):
|
|
561
|
+
or "subagents" in tp.parts or keepwarm_safety.session_ended(
|
|
562
|
+
_measure_facade.SNAPSHOT_DIR, session_id, turn_epoch) is True):
|
|
588
563
|
return None
|
|
589
564
|
usage, model, ts = _measure_facade._keepwarm_last_usage(tp)
|
|
590
565
|
if not usage:
|
|
@@ -625,7 +600,7 @@ def write_keepwarm_arm_record(session_id, transcript_path, now=None, *, parent_p
|
|
|
625
600
|
}
|
|
626
601
|
if turn is not None:
|
|
627
602
|
record["terminal_turn"] = turn
|
|
628
|
-
return keepwarm_rearm.publish_arm(_measure_facade, record
|
|
603
|
+
return keepwarm_rearm.publish_arm(_measure_facade, record)
|
|
629
604
|
except Exception:
|
|
630
605
|
# Absolute backstop: nothing in the arm path may propagate to the hook.
|
|
631
606
|
return None
|
|
@@ -639,12 +614,13 @@ def _valid_keepwarm_record(rec):
|
|
|
639
614
|
if not isinstance(rec.get("session_id"), str) or not rec["session_id"] or not rec.get("transcript_path"):
|
|
640
615
|
return False
|
|
641
616
|
try:
|
|
642
|
-
return _measure_facade.math.isfinite(float(rec
|
|
617
|
+
return "ts" in rec and all(_measure_facade.math.isfinite(float(rec[key])) for key in
|
|
618
|
+
("ts", "last_turn_ts", "transcript_mtime") if key in rec)
|
|
643
619
|
except (TypeError, ValueError, OverflowError):
|
|
644
620
|
return False
|
|
645
621
|
|
|
646
622
|
|
|
647
|
-
def load_keepwarm_records(path=None):
|
|
623
|
+
def load_keepwarm_records(path=None, *, strict=False):
|
|
648
624
|
"""Load valid arm records from the sidecar; corrupt lines are skipped.
|
|
649
625
|
|
|
650
626
|
Returns a list of record dicts (possibly empty). Never raises: a missing file
|
|
@@ -656,8 +632,6 @@ def load_keepwarm_records(path=None):
|
|
|
656
632
|
path = _measure_facade._keepwarm_sidecar_path()
|
|
657
633
|
records = []
|
|
658
634
|
try:
|
|
659
|
-
if not _measure_facade.Path(path).exists():
|
|
660
|
-
return []
|
|
661
635
|
with open(path, "r", encoding="utf-8", errors="replace") as fh:
|
|
662
636
|
for line in fh:
|
|
663
637
|
line = line.strip()
|
|
@@ -669,7 +643,11 @@ def load_keepwarm_records(path=None):
|
|
|
669
643
|
continue
|
|
670
644
|
if _measure_facade._valid_keepwarm_record(rec):
|
|
671
645
|
records.append(rec)
|
|
646
|
+
except FileNotFoundError:
|
|
647
|
+
return []
|
|
672
648
|
except OSError:
|
|
649
|
+
if strict:
|
|
650
|
+
raise
|
|
673
651
|
return []
|
|
674
652
|
return records
|
|
675
653
|
|
|
@@ -712,12 +690,14 @@ def classify_keepwarm_record(rec, now=None):
|
|
|
712
690
|
from . import keepwarm_safety
|
|
713
691
|
owner = rec.get("owner")
|
|
714
692
|
mod_receipt = owner is None and rec.get("pings_fired") and (rec.get("manual_action_id") or rec.get("auto_warm"))
|
|
715
|
-
|
|
716
|
-
|
|
693
|
+
ended = keepwarm_safety.session_ended(_measure_facade.SNAPSHOT_DIR, rec.get("session_id"), arm_ts)
|
|
694
|
+
if ended is None:
|
|
695
|
+
return "unavailable"
|
|
696
|
+
if ended or (not mod_receipt and not keepwarm_safety.owner_alive(owner)):
|
|
717
697
|
return "gone"
|
|
718
698
|
if "terminal_turn" in rec:
|
|
719
699
|
turn = keepwarm_safety.terminal_turn(p)
|
|
720
|
-
return "
|
|
700
|
+
return "unavailable" if turn is None else ("still_paused" if turn == rec["terminal_turn"] else "resumed")
|
|
721
701
|
try:
|
|
722
702
|
armed_size = int(rec["byte_size"])
|
|
723
703
|
except (KeyError, TypeError, ValueError):
|
|
@@ -749,7 +729,10 @@ def compact_keepwarm_sidecar(path=None, now=None):
|
|
|
749
729
|
with _measure_facade._keepwarm_lock() as acquired:
|
|
750
730
|
if not acquired:
|
|
751
731
|
return (0, 0)
|
|
752
|
-
|
|
732
|
+
try:
|
|
733
|
+
records = _measure_facade.load_keepwarm_records(path, strict=True)
|
|
734
|
+
except OSError:
|
|
735
|
+
return 0, 0
|
|
753
736
|
# Account for corrupt/invalid lines as dropped for the caller's visibility.
|
|
754
737
|
try:
|
|
755
738
|
raw_lines = 0
|
|
@@ -763,31 +746,17 @@ def compact_keepwarm_sidecar(path=None, now=None):
|
|
|
763
746
|
dropped += len(records) - len(latest)
|
|
764
747
|
for rec in latest.values():
|
|
765
748
|
verdict = _measure_facade.classify_keepwarm_record(rec, now=now)
|
|
766
|
-
if verdict
|
|
749
|
+
if verdict in ("still_paused", "unavailable"):
|
|
767
750
|
kept.append(rec)
|
|
768
751
|
else:
|
|
769
752
|
dropped += 1
|
|
770
753
|
if not path.exists() and not kept:
|
|
771
754
|
return 0, dropped
|
|
772
755
|
try:
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
prefix=".keepwarm_state.", suffix=".tmp", dir=str(_measure_facade.SNAPSHOT_DIR))
|
|
776
|
-
try:
|
|
777
|
-
if hasattr(_measure_facade.os, "fchmod"):
|
|
778
|
-
_measure_facade.os.fchmod(fd, 0o600)
|
|
779
|
-
with _measure_facade.os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
780
|
-
for rec in kept:
|
|
781
|
-
fh.write(_measure_facade.json.dumps(rec) + "\n")
|
|
782
|
-
_measure_facade.os.replace(tmp_name, str(path))
|
|
783
|
-
except Exception:
|
|
784
|
-
try:
|
|
785
|
-
_measure_facade.os.unlink(tmp_name)
|
|
786
|
-
except OSError:
|
|
787
|
-
pass
|
|
788
|
-
raise
|
|
756
|
+
from codex_io import atomic_write
|
|
757
|
+
atomic_write(path, ''.join(_measure_facade.json.dumps(r) + "\n" for r in kept), replace_symlink=True)
|
|
789
758
|
except OSError:
|
|
790
|
-
|
|
759
|
+
return 0, 0
|
|
791
760
|
return len(kept), dropped
|
|
792
761
|
|
|
793
762
|
|
|
@@ -2224,71 +2193,11 @@ def _keepwarm_emit_tick_observability(now, allowed, reason, armed, fired,
|
|
|
2224
2193
|
|
|
2225
2194
|
|
|
2226
2195
|
def _keepwarm_tick_singleton():
|
|
2227
|
-
"""
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
"""
|
|
2233
|
-
_measure_facade = _compat.facade()
|
|
2234
|
-
held = False
|
|
2235
|
-
lock_path = _measure_facade.SNAPSHOT_DIR / _measure_facade._KEEPWARM_TICK_LOCK_NAME
|
|
2236
|
-
fd = None
|
|
2237
|
-
try:
|
|
2238
|
-
try:
|
|
2239
|
-
_measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
|
|
2240
|
-
except OSError:
|
|
2241
|
-
yield False
|
|
2242
|
-
return
|
|
2243
|
-
try:
|
|
2244
|
-
fd = _measure_facade.os.open(str(lock_path), _measure_facade.os.O_CREAT | _measure_facade.os.O_EXCL | _measure_facade.os.O_WRONLY, 0o600)
|
|
2245
|
-
except FileExistsError:
|
|
2246
|
-
# Reclaim if stale.
|
|
2247
|
-
now = _measure_facade.time.time()
|
|
2248
|
-
try:
|
|
2249
|
-
st = lock_path.stat()
|
|
2250
|
-
owner = None
|
|
2251
|
-
try:
|
|
2252
|
-
owner = int(lock_path.read_text(encoding="utf-8").strip() or 0)
|
|
2253
|
-
except (OSError, ValueError):
|
|
2254
|
-
owner = None
|
|
2255
|
-
alive = False
|
|
2256
|
-
if owner and owner > 0:
|
|
2257
|
-
alive = _measure_facade._pid_is_running(owner)
|
|
2258
|
-
if not alive and (now - st.st_mtime) > _measure_facade._KEEPWARM_STALE_LOCK_SECONDS:
|
|
2259
|
-
try:
|
|
2260
|
-
_measure_facade.os.unlink(str(lock_path))
|
|
2261
|
-
fd = _measure_facade.os.open(str(lock_path),
|
|
2262
|
-
_measure_facade.os.O_CREAT | _measure_facade.os.O_EXCL | _measure_facade.os.O_WRONLY, 0o600)
|
|
2263
|
-
except OSError:
|
|
2264
|
-
yield False
|
|
2265
|
-
return
|
|
2266
|
-
else:
|
|
2267
|
-
yield False
|
|
2268
|
-
return
|
|
2269
|
-
except OSError:
|
|
2270
|
-
yield False
|
|
2271
|
-
return
|
|
2272
|
-
except OSError:
|
|
2273
|
-
yield False
|
|
2274
|
-
return
|
|
2275
|
-
try:
|
|
2276
|
-
_measure_facade.os.write(fd, str(_measure_facade.os.getpid()).encode("ascii"))
|
|
2277
|
-
except OSError:
|
|
2278
|
-
pass
|
|
2279
|
-
held = True
|
|
2280
|
-
yield True
|
|
2281
|
-
finally:
|
|
2282
|
-
if fd is not None:
|
|
2283
|
-
try:
|
|
2284
|
-
_measure_facade.os.close(fd)
|
|
2285
|
-
except OSError:
|
|
2286
|
-
pass
|
|
2287
|
-
if held:
|
|
2288
|
-
try:
|
|
2289
|
-
_measure_facade.os.unlink(str(lock_path))
|
|
2290
|
-
except OSError:
|
|
2291
|
-
pass
|
|
2196
|
+
"""Only one scheduler runs per generation. Process exit releases its lock."""
|
|
2197
|
+
from . import keepwarm_rearm
|
|
2198
|
+
facade = _compat.facade()
|
|
2199
|
+
with keepwarm_rearm.os_lock(facade.SNAPSHOT_DIR / facade._KEEPWARM_TICK_LOCK_NAME, 0) as held:
|
|
2200
|
+
yield held
|
|
2292
2201
|
|
|
2293
2202
|
|
|
2294
2203
|
def keepwarm_tick(now=None, dry_run=None, env=None, runner=None,
|
|
@@ -2434,41 +2343,25 @@ def keepwarm_tick(now=None, dry_run=None, env=None, runner=None,
|
|
|
2434
2343
|
|
|
2435
2344
|
|
|
2436
2345
|
def _keepwarm_rewrite_records(records, now=None):
|
|
2437
|
-
"""
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
compact_keepwarm_sidecar's atomic rewrite. Never raises.
|
|
2441
|
-
"""
|
|
2442
|
-
_measure_facade = _compat.facade()
|
|
2443
|
-
if now is None:
|
|
2444
|
-
now = _measure_facade.time.time()
|
|
2445
|
-
path = _measure_facade._keepwarm_sidecar_path()
|
|
2346
|
+
"""Merge replayed ping counters with Stops published after the tick's read."""
|
|
2347
|
+
from codex_io import atomic_write
|
|
2348
|
+
facade = _compat.facade()
|
|
2446
2349
|
try:
|
|
2447
|
-
with
|
|
2448
|
-
if not
|
|
2350
|
+
with facade._keepwarm_lock() as held:
|
|
2351
|
+
if not held:
|
|
2449
2352
|
return
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
except Exception:
|
|
2463
|
-
try:
|
|
2464
|
-
_measure_facade.os.unlink(tmp_name)
|
|
2465
|
-
except OSError:
|
|
2466
|
-
pass
|
|
2467
|
-
raise
|
|
2468
|
-
except OSError:
|
|
2469
|
-
pass
|
|
2470
|
-
except Exception:
|
|
2471
|
-
pass
|
|
2353
|
+
current = {(r['session_id'], r['ts']): r for r in facade.load_keepwarm_records(strict=True)}
|
|
2354
|
+
for row in records:
|
|
2355
|
+
latest = current.get((row['session_id'], row['ts']))
|
|
2356
|
+
if latest is None:
|
|
2357
|
+
continue
|
|
2358
|
+
latest['pings_fired'] = sorted(set(latest.get('pings_fired', ())) | set(row.get('pings_fired', ())))
|
|
2359
|
+
if row.get('ping_failed'):
|
|
2360
|
+
latest['ping_failed'] = True
|
|
2361
|
+
atomic_write(facade._keepwarm_sidecar_path(), ''.join(facade.json.dumps(r) + "\n" for r in current.values()),
|
|
2362
|
+
replace_symlink=True)
|
|
2363
|
+
except (OSError, TypeError, ValueError):
|
|
2364
|
+
return
|
|
2472
2365
|
|
|
2473
2366
|
|
|
2474
2367
|
def keepwarm_resume_predictor(features):
|
|
@@ -3150,35 +3043,18 @@ def _keepwarm_compact_ledger(now=None, retain_days=None):
|
|
|
3150
3043
|
if now is None:
|
|
3151
3044
|
now = _measure_facade.time.time()
|
|
3152
3045
|
path = _measure_facade._keepwarm_ledger_path()
|
|
3046
|
+
from . import keepwarm_auto, mod_action_booking
|
|
3153
3047
|
try:
|
|
3154
|
-
|
|
3155
|
-
return (False, 0, 0)
|
|
3156
|
-
size = path.stat().st_size
|
|
3157
|
-
except OSError:
|
|
3158
|
-
return (False, 0, 0)
|
|
3159
|
-
rows = _measure_facade._keepwarm_load_ledger_rows(path)
|
|
3160
|
-
cutoff = float(now) - float(retain_days) * 86400.0
|
|
3161
|
-
kept = []
|
|
3162
|
-
dropped = 0
|
|
3163
|
-
has_old = False
|
|
3164
|
-
for r in rows:
|
|
3165
|
-
try:
|
|
3166
|
-
ts = float(r.get("ts", 0) or 0)
|
|
3167
|
-
except (TypeError, ValueError):
|
|
3168
|
-
ts = 0.0
|
|
3169
|
-
if ts < cutoff:
|
|
3170
|
-
dropped += 1
|
|
3171
|
-
has_old = True
|
|
3172
|
-
else:
|
|
3173
|
-
kept.append(r)
|
|
3174
|
-
# Only rewrite when something would actually change (size cap breached OR old
|
|
3175
|
-
# rows present). A clean, in-window, small ledger is left untouched.
|
|
3176
|
-
if not has_old and size <= _measure_facade._KEEPWARM_LEDGER_MAX_BYTES:
|
|
3177
|
-
return (False, len(kept), 0)
|
|
3178
|
-
try:
|
|
3179
|
-
with _measure_facade._keepwarm_lock() as acquired:
|
|
3048
|
+
with mod_action_booking._lock(_measure_facade) as acquired:
|
|
3180
3049
|
if not acquired:
|
|
3181
3050
|
return (False, 0, 0)
|
|
3051
|
+
size = path.stat().st_size
|
|
3052
|
+
rows = keepwarm_auto.read_ledger(path)
|
|
3053
|
+
cutoff = float(now) - float(retain_days) * 86400.0
|
|
3054
|
+
kept = [row for row in rows if float(row.get("ts", 0)) >= cutoff]
|
|
3055
|
+
dropped = len(rows) - len(kept)
|
|
3056
|
+
if not dropped and size <= _measure_facade._KEEPWARM_LEDGER_MAX_BYTES:
|
|
3057
|
+
return False, len(kept), 0
|
|
3182
3058
|
try:
|
|
3183
3059
|
_measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
|
|
3184
3060
|
fd, tmp_name = _measure_facade.tempfile.mkstemp(
|
|
@@ -3202,7 +3078,7 @@ def _keepwarm_compact_ledger(now=None, retain_days=None):
|
|
|
3202
3078
|
except OSError:
|
|
3203
3079
|
return (False, len(kept), 0)
|
|
3204
3080
|
except Exception:
|
|
3205
|
-
return (False,
|
|
3081
|
+
return (False, 0, 0)
|
|
3206
3082
|
return (True, len(kept), dropped)
|
|
3207
3083
|
|
|
3208
3084
|
|
|
@@ -3361,18 +3237,26 @@ def keepwarm_detect_realized(now=None, records=None, parse_fn=None):
|
|
|
3361
3237
|
records = _measure_facade.load_keepwarm_records()
|
|
3362
3238
|
out = {"realized": 0, "loss": 0, "skipped": 0, "errors": 0, "booked_usd": 0.0}
|
|
3363
3239
|
try:
|
|
3364
|
-
|
|
3365
|
-
|
|
3366
|
-
|
|
3240
|
+
rows = _measure_facade._keepwarm_load_ledger_rows()
|
|
3241
|
+
booked = _measure_facade._keepwarm_booked_pause_keys(rows)
|
|
3242
|
+
proved = {}
|
|
3243
|
+
for row in rows:
|
|
3244
|
+
if row.get('source') == 'keepwarm-headless' and row.get('status') == 'ok' and row.get('proof') is True:
|
|
3245
|
+
proved.setdefault(row.get('pause_key'), []).append(row['ts'])
|
|
3246
|
+
except (TypeError, ValueError, KeyError, OSError):
|
|
3247
|
+
return out
|
|
3367
3248
|
for rec in {(r.get("session_id"), r.get("ts")): r for r in records}.values():
|
|
3368
3249
|
try:
|
|
3369
|
-
|
|
3370
|
-
n_pings = len(pings) if isinstance(pings, list) else 0
|
|
3371
|
-
if n_pings < 1 or rec.get("ping_failed"):
|
|
3372
|
-
continue
|
|
3373
|
-
sid = rec.get("session_id")
|
|
3374
|
-
arm_ts = rec.get("ts")
|
|
3250
|
+
sid, arm_ts = rec.get("session_id"), rec.get("ts")
|
|
3375
3251
|
pause_key = _measure_facade._keepwarm_pause_key(sid, arm_ts)
|
|
3252
|
+
pings = rec.get("pings_fired") or []
|
|
3253
|
+
# A proven outcome is durable even if the pause lock was busy when its receipt arrived.
|
|
3254
|
+
if len(proved.get(pause_key, ())) > len(pings):
|
|
3255
|
+
pings = proved[pause_key]
|
|
3256
|
+
rec = dict(rec, auto_warm=True, pings_fired=pings)
|
|
3257
|
+
n_pings = len(pings)
|
|
3258
|
+
if not n_pings or rec.get("ping_failed"):
|
|
3259
|
+
continue
|
|
3376
3260
|
if pause_key in booked:
|
|
3377
3261
|
continue
|
|
3378
3262
|
try:
|
|
@@ -68,19 +68,23 @@ def prune_markers(facade, now):
|
|
|
68
68
|
removed = 0
|
|
69
69
|
if not facade.SNAPSHOT_DIR.is_dir():
|
|
70
70
|
return removed
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
if
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
71
|
+
from itertools import chain
|
|
72
|
+
from .keepwarm_rearm import state_lock
|
|
73
|
+
with state_lock(facade.SNAPSHOT_DIR, 0) as held:
|
|
74
|
+
if not held:
|
|
75
|
+
return 0
|
|
76
|
+
for path in chain(facade.SNAPSHOT_DIR.iterdir(), (facade.SNAPSHOT_DIR / 'kw2-ends').glob('kw2-ended-*')):
|
|
77
|
+
if not path.name.startswith(('kw2-ended-', 'kw2-owner-', 'kw2-stop-')):
|
|
78
|
+
continue
|
|
79
|
+
try:
|
|
80
|
+
info = path.lstat()
|
|
81
|
+
if stat.S_ISREG(info.st_mode) and info.st_mtime < now - 14 * DAY:
|
|
82
|
+
path.unlink()
|
|
83
|
+
removed += 1
|
|
84
|
+
if removed == 200:
|
|
85
|
+
break
|
|
86
|
+
except OSError:
|
|
87
|
+
continue
|
|
84
88
|
return removed
|
|
85
89
|
|
|
86
90
|
|
|
@@ -107,8 +111,28 @@ def _auto_rows(rows):
|
|
|
107
111
|
and row.get('action') == 'warm' and row.get('auto') is True]
|
|
108
112
|
|
|
109
113
|
|
|
114
|
+
def accounting_error(exc):
|
|
115
|
+
return 'ledger-locked' if getattr(exc, 'winerror', None) in (32, 33) else 'accounting-unavailable'
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def retry_accounting_read(read, *args):
|
|
119
|
+
"""Windows share and byte-range conflicts can clear when another handle closes."""
|
|
120
|
+
import time
|
|
121
|
+
for attempt in range(3):
|
|
122
|
+
try:
|
|
123
|
+
return read(*args)
|
|
124
|
+
except OSError as exc:
|
|
125
|
+
if accounting_error(exc) != 'ledger-locked' or attempt == 2:
|
|
126
|
+
raise
|
|
127
|
+
time.sleep(.01)
|
|
128
|
+
|
|
129
|
+
|
|
110
130
|
def read_ledger(path, *, strict=True):
|
|
111
131
|
"""An absent ledger is empty. Spending requires a complete, readable ledger."""
|
|
132
|
+
return retry_accounting_read(_read_ledger, path, strict)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _read_ledger(path, strict):
|
|
112
136
|
rows = []
|
|
113
137
|
try:
|
|
114
138
|
stream = open(path, encoding='utf-8', errors='strict' if strict else 'replace')
|
|
@@ -232,7 +256,11 @@ def decide(facade, session_id, context_tokens, idle_seconds, model, lifetime,
|
|
|
232
256
|
return stop('meters-unknown')
|
|
233
257
|
if not math.isfinite(idle_seconds) or idle_seconds < 0:
|
|
234
258
|
return out
|
|
235
|
-
|
|
259
|
+
if rows is None:
|
|
260
|
+
try:
|
|
261
|
+
rows = read_ledger(facade._keepwarm_ledger_path())
|
|
262
|
+
except (OSError, ValueError) as exc:
|
|
263
|
+
return stop(accounting_error(exc))
|
|
236
264
|
for row in _auto_rows(rows):
|
|
237
265
|
stamp = float(row['ts'])
|
|
238
266
|
if not math.isfinite(stamp) or stamp > now:
|
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
"""Publish and watch successive pauses in the same terminal session."""
|
|
2
2
|
from contextlib import contextmanager
|
|
3
|
-
import errno
|
|
4
3
|
import json
|
|
5
4
|
import os
|
|
6
|
-
import stat
|
|
7
5
|
import sys
|
|
8
6
|
import tempfile
|
|
9
7
|
import time
|
|
@@ -41,87 +39,53 @@ def _displaced_legacy_writer(lease):
|
|
|
41
39
|
return False
|
|
42
40
|
|
|
43
41
|
|
|
44
|
-
def _acquire_writer(fd, timeout):
|
|
45
|
-
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
|
46
|
-
return None
|
|
47
|
-
until = time.monotonic() + timeout
|
|
48
|
-
while True:
|
|
49
|
-
try:
|
|
50
|
-
if os.name == 'nt':
|
|
51
|
-
import msvcrt
|
|
52
|
-
msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
|
|
53
|
-
else:
|
|
54
|
-
import fcntl
|
|
55
|
-
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
56
|
-
return True
|
|
57
|
-
except OSError as exc:
|
|
58
|
-
if exc.errno not in (errno.EAGAIN, errno.EWOULDBLOCK) and not (
|
|
59
|
-
os.name == 'nt' and exc.errno == errno.EACCES):
|
|
60
|
-
raise
|
|
61
|
-
remaining = until - time.monotonic()
|
|
62
|
-
if remaining <= 0:
|
|
63
|
-
return False
|
|
64
|
-
time.sleep(min(0.01, remaining))
|
|
65
|
-
|
|
66
|
-
|
|
67
42
|
@contextmanager
|
|
68
|
-
def
|
|
69
|
-
"""
|
|
70
|
-
|
|
71
|
-
flags = os.O_RDWR | os.O_CREAT | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_NONBLOCK', 0)
|
|
43
|
+
def os_lock(path, timeout):
|
|
44
|
+
"""One persistent inode. False means busy, None means unusable storage."""
|
|
45
|
+
from hook_provenance import _acquire
|
|
72
46
|
try:
|
|
73
47
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
74
|
-
fd =
|
|
48
|
+
fd = _acquire(path, timeout, busy=False, nofollow=True)
|
|
75
49
|
except OSError:
|
|
76
|
-
|
|
50
|
+
fd = None
|
|
51
|
+
if fd is None or fd is False:
|
|
52
|
+
yield fd
|
|
77
53
|
return
|
|
78
54
|
try:
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
55
|
+
yield True
|
|
56
|
+
finally:
|
|
57
|
+
os.close(fd)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def state_lock(directory, timeout=.075):
|
|
61
|
+
return os_lock(directory / '.keepwarm-pauses-v2.lock', timeout)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@contextmanager
|
|
65
|
+
def writer_lock(facade, timeout):
|
|
66
|
+
"""The shared spending protocol used by 5.13.76 and 5.13.77."""
|
|
67
|
+
from hook_runtime import LeaseLock
|
|
68
|
+
|
|
69
|
+
path = facade.SNAPSHOT_DIR / facade._KEEPWARM_LOCK_NAME
|
|
70
|
+
until = time.monotonic() + timeout
|
|
71
|
+
with os_lock(path, timeout) as held:
|
|
84
72
|
if not held:
|
|
85
73
|
yield held
|
|
86
74
|
return
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
from hook_runtime import LeaseLock
|
|
91
|
-
|
|
92
|
-
lease = LeaseLock(path.with_name(path.name + '.lease'),
|
|
93
|
-
acquire_timeout=max(0, until - time.monotonic()),
|
|
94
|
-
lease_seconds=sys.float_info.max, cohort_throttle=False,
|
|
95
|
-
reclaim_released=True, may_reclaim_active=lambda owner: not _legacy_writer_alive(owner))
|
|
75
|
+
lease = LeaseLock(path.with_name(path.name + '.lease'), acquire_timeout=max(0, until - time.monotonic()),
|
|
76
|
+
cohort_throttle=False, reclaim_released=True,
|
|
77
|
+
may_reclaim_active=lambda owner: not _legacy_writer_alive(owner))
|
|
96
78
|
with lease as leased:
|
|
97
79
|
try:
|
|
98
80
|
available = leased and not _displaced_legacy_writer(lease)
|
|
99
81
|
except OSError:
|
|
100
82
|
available = None
|
|
101
|
-
yield None if lease.storage_error else
|
|
102
|
-
finally:
|
|
103
|
-
# Keep the inode in place. Closing the descriptor releases the OS lock.
|
|
104
|
-
os.close(fd)
|
|
83
|
+
yield lease if available else (None if lease.storage_error or available is None else False)
|
|
105
84
|
|
|
106
85
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
from .keepwarm_safety import terminal_turn
|
|
111
|
-
|
|
112
|
-
delay = 0.05
|
|
113
|
-
while True:
|
|
114
|
-
with facade._keepwarm_lock() as held:
|
|
115
|
-
if held is not False or turn is None or facade.current_deadline() is not None:
|
|
116
|
-
yield held
|
|
117
|
-
return
|
|
118
|
-
if expires is None or facade.time.time() >= expires:
|
|
119
|
-
break
|
|
120
|
-
time.sleep(delay)
|
|
121
|
-
if terminal_turn(transcript) != turn:
|
|
122
|
-
break
|
|
123
|
-
delay = min(1, delay * 2)
|
|
124
|
-
yield False
|
|
86
|
+
def verify_spend(lease):
|
|
87
|
+
if hasattr(lease, '_owner_path') and not lease.path.samefile(lease._owner_path):
|
|
88
|
+
raise OSError('reservation lease changed')
|
|
125
89
|
|
|
126
90
|
|
|
127
91
|
def publish_exclusive(path, content):
|
|
@@ -132,7 +96,11 @@ def publish_exclusive(path, content):
|
|
|
132
96
|
stream.write(content)
|
|
133
97
|
os.link(temporary, path)
|
|
134
98
|
finally:
|
|
135
|
-
|
|
99
|
+
from hook_runtime import LeaseLock
|
|
100
|
+
try:
|
|
101
|
+
LeaseLock._retry_sharing_violation(lambda: os.unlink(temporary), attempts=3)
|
|
102
|
+
except OSError:
|
|
103
|
+
pass # The published claim is already complete.
|
|
136
104
|
|
|
137
105
|
|
|
138
106
|
def _commit_arm(facade, record):
|
|
@@ -140,8 +108,8 @@ def _commit_arm(facade, record):
|
|
|
140
108
|
from . import keepwarm_safety
|
|
141
109
|
from .mod_action_booking import _append
|
|
142
110
|
|
|
143
|
-
for existing in reversed(facade.load_keepwarm_records()):
|
|
144
|
-
if existing.get('session_id') != record['session_id'] or existing.get('owner') != record
|
|
111
|
+
for existing in reversed(facade.load_keepwarm_records(strict=True)):
|
|
112
|
+
if existing.get('session_id') != record['session_id'] or existing.get('owner') != record.get('owner'):
|
|
145
113
|
continue
|
|
146
114
|
if keepwarm_safety.same_pause(existing, record):
|
|
147
115
|
if 'terminal_turn' not in record or 'terminal_turn' in existing:
|
|
@@ -152,43 +120,64 @@ def _commit_arm(facade, record):
|
|
|
152
120
|
return record
|
|
153
121
|
|
|
154
122
|
|
|
155
|
-
def
|
|
123
|
+
def _publish_stop(facade, record, path, now):
|
|
156
124
|
from .keepwarm_auto import CACHE_LIFETIME
|
|
157
|
-
from .keepwarm_safety import terminal_turn
|
|
125
|
+
from .keepwarm_safety import session_ended, terminal_turn
|
|
126
|
+
|
|
127
|
+
result = None
|
|
128
|
+
if now < record['last_turn_ts'] + CACHE_LIFETIME:
|
|
129
|
+
turn = terminal_turn(facade.Path(record['transcript_path']))
|
|
130
|
+
ended = session_ended(facade.SNAPSHOT_DIR, record['session_id'], record['ts'])
|
|
131
|
+
if ended is None or (not ended and turn is None):
|
|
132
|
+
return None # Retry an unreadable marker or incomplete transcript.
|
|
133
|
+
if not ended and turn == record['terminal_turn']:
|
|
134
|
+
result = _commit_arm(facade, record)
|
|
135
|
+
try:
|
|
136
|
+
path.unlink(missing_ok=True)
|
|
137
|
+
except OSError:
|
|
138
|
+
pass # The tick can acknowledge an already committed Stop.
|
|
139
|
+
return result
|
|
158
140
|
|
|
159
|
-
|
|
160
|
-
|
|
141
|
+
|
|
142
|
+
def publish_arm(facade, record):
|
|
161
143
|
facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
144
|
+
pending = None
|
|
145
|
+
if 'terminal_turn' in record:
|
|
146
|
+
fd, name = tempfile.mkstemp(prefix='kw2-stop-', dir=facade.SNAPSHOT_DIR)
|
|
147
|
+
pending = facade.Path(name)
|
|
148
|
+
with os.fdopen(fd, 'w', encoding='utf-8') as stream:
|
|
149
|
+
json.dump(record, stream, allow_nan=False)
|
|
150
|
+
with facade._keepwarm_lock() as held:
|
|
151
|
+
if held:
|
|
152
|
+
if pending is not None:
|
|
153
|
+
return _publish_stop(facade, record, pending, facade.time.time())
|
|
154
|
+
return _commit_arm(facade, record)
|
|
173
155
|
|
|
174
156
|
|
|
175
157
|
def recover_pending(facade, now):
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
158
|
+
with facade._keepwarm_lock() as held:
|
|
159
|
+
if not held:
|
|
160
|
+
return
|
|
161
|
+
marker = facade.SNAPSHOT_DIR / '.kw2-imported'
|
|
162
|
+
if not marker.exists():
|
|
163
|
+
legacy = facade.SNAPSHOT_DIR / 'keepwarm_state.jsonl'
|
|
164
|
+
from .mod_action_booking import _append
|
|
183
165
|
try:
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
166
|
+
imported = {(r['session_id'], r['ts']) for r in facade.load_keepwarm_records(strict=True)}
|
|
167
|
+
paths = [legacy, *(p for p in facade.SNAPSHOT_DIR.glob('keepwarm-pending-stop-*') if not p.is_symlink())]
|
|
168
|
+
rows = {(r['session_id'], r['ts']): r for p in paths for r in facade.load_keepwarm_records(p, strict=True)}
|
|
169
|
+
for key, row in rows.items():
|
|
170
|
+
if key not in imported and now - float(row['ts']) <= facade._KEEPWARM_MAX_AGE_SECONDS:
|
|
171
|
+
_append(facade._keepwarm_sidecar_path(), row)
|
|
172
|
+
marker.touch(mode=0o600)
|
|
173
|
+
except OSError:
|
|
174
|
+
pass # Retry migration independently of current Stops.
|
|
175
|
+
for path in facade.SNAPSHOT_DIR.glob('kw2-stop-*'):
|
|
176
|
+
try:
|
|
177
|
+
if not path.is_symlink():
|
|
178
|
+
row = json.loads(path.read_bytes())
|
|
179
|
+
if facade._valid_keepwarm_record(row):
|
|
180
|
+
_publish_stop(facade, row, path, now)
|
|
192
181
|
except (OSError, KeyError, ValueError, TypeError):
|
|
193
182
|
continue
|
|
194
183
|
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
"""Fail-closed liveness checks for paused Claude sessions."""
|
|
2
2
|
import hashlib
|
|
3
3
|
import json
|
|
4
|
+
import math
|
|
4
5
|
import os
|
|
5
6
|
from pathlib import Path
|
|
6
7
|
import re
|
|
7
8
|
import shlex
|
|
8
9
|
import shutil
|
|
9
|
-
import stat
|
|
10
10
|
import subprocess
|
|
11
11
|
import sys
|
|
12
12
|
import time
|
|
@@ -148,20 +148,7 @@ _NO_OWNER_TTL = 300.0
|
|
|
148
148
|
|
|
149
149
|
def _owner_cache_path(directory, session_id):
|
|
150
150
|
name = hashlib.sha256(str(session_id).encode('utf-8')).hexdigest()
|
|
151
|
-
return Path(directory) / ('
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
def _pid_exists(pid):
|
|
155
|
-
"""Check whether a process may still be running."""
|
|
156
|
-
if os.name != 'posix':
|
|
157
|
-
return False
|
|
158
|
-
try:
|
|
159
|
-
os.kill(int(pid), 0)
|
|
160
|
-
except PermissionError:
|
|
161
|
-
return True
|
|
162
|
-
except (OSError, ValueError, TypeError):
|
|
163
|
-
return False
|
|
164
|
-
return True
|
|
151
|
+
return Path(directory) / ('kw2-owner-' + name)
|
|
165
152
|
|
|
166
153
|
|
|
167
154
|
def session_owner(directory, session_id, now=None, *, parent_pid=None, parent_start=None):
|
|
@@ -197,10 +184,10 @@ def session_owner(directory, session_id, now=None, *, parent_pid=None, parent_st
|
|
|
197
184
|
eligible = owner_eligible(process['pid'])
|
|
198
185
|
if path is not None:
|
|
199
186
|
try:
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
187
|
+
from codex_io import atomic_write_json
|
|
188
|
+
with keepwarm_rearm.state_lock(path.parent, 0) as held:
|
|
189
|
+
if held:
|
|
190
|
+
atomic_write_json(path, {'process': process, 'eligible': eligible, 'ts': now}, replace_symlink=True)
|
|
204
191
|
except OSError:
|
|
205
192
|
pass
|
|
206
193
|
return process if eligible else None
|
|
@@ -215,36 +202,56 @@ def owner_alive(owner, lookup=process_info, eligibility=owner_eligible):
|
|
|
215
202
|
|
|
216
203
|
def _end_path(directory, session_id):
|
|
217
204
|
name = hashlib.sha256(str(session_id).encode('utf-8')).hexdigest()
|
|
218
|
-
return Path(directory) / ('
|
|
205
|
+
return Path(directory) / ('kw2-ended-' + name)
|
|
219
206
|
|
|
220
207
|
|
|
221
208
|
def mark_ended(directory, session_id):
|
|
222
209
|
if not session_id:
|
|
223
210
|
return False
|
|
224
211
|
try:
|
|
225
|
-
|
|
212
|
+
from codex_io import atomic_write
|
|
226
213
|
path = _end_path(directory, session_id)
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
214
|
+
stamp = time.time()
|
|
215
|
+
with keepwarm_rearm.state_lock(path.parent, 0) as held:
|
|
216
|
+
if held:
|
|
217
|
+
atomic_write(path, str(stamp), replace_symlink=True)
|
|
218
|
+
else:
|
|
219
|
+
# Immutable input, like a staged Stop. A busy writer cannot lose SessionEnd.
|
|
220
|
+
event = path.parent / 'kw2-ends' / (path.name + '.' + os.urandom(8).hex())
|
|
221
|
+
atomic_write(event, str(stamp), replace_symlink=True)
|
|
233
222
|
return True
|
|
234
223
|
except OSError:
|
|
235
224
|
return False
|
|
236
225
|
|
|
237
226
|
|
|
238
|
-
def
|
|
227
|
+
def session_ended(directory, session_id, armed_at):
|
|
228
|
+
path = _end_path(directory, session_id)
|
|
229
|
+
# Imported pauses can still receive SessionEnd from the old hooks.
|
|
230
|
+
pending = path.parent / 'kw2-ends'
|
|
239
231
|
try:
|
|
240
|
-
|
|
241
|
-
if path.is_symlink():
|
|
242
|
-
return True
|
|
243
|
-
return float(path.read_text(encoding='utf-8')) >= float(armed_at)
|
|
232
|
+
events = [pending / name for name in os.listdir(pending) if name.startswith(path.name + '.')]
|
|
244
233
|
except FileNotFoundError:
|
|
245
|
-
|
|
246
|
-
except
|
|
247
|
-
return
|
|
234
|
+
events = []
|
|
235
|
+
except OSError:
|
|
236
|
+
return None
|
|
237
|
+
for marker in (path, path.with_name(path.name.replace('kw2-ended-', 'keepwarm-ended-')), *events):
|
|
238
|
+
try:
|
|
239
|
+
if marker.is_symlink():
|
|
240
|
+
return None
|
|
241
|
+
stamp = float(marker.read_text(encoding='utf-8'))
|
|
242
|
+
if not math.isfinite(stamp):
|
|
243
|
+
return None
|
|
244
|
+
if stamp >= float(armed_at):
|
|
245
|
+
return True
|
|
246
|
+
except FileNotFoundError:
|
|
247
|
+
continue
|
|
248
|
+
except (OSError, ValueError, TypeError):
|
|
249
|
+
return None
|
|
250
|
+
return False
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def ended_since(directory, session_id, armed_at):
|
|
254
|
+
return session_ended(directory, session_id, armed_at) is not False
|
|
248
255
|
|
|
249
256
|
|
|
250
257
|
def terminal_turn(path):
|
|
@@ -342,22 +349,27 @@ def _headless_preference_disabled(facade, env):
|
|
|
342
349
|
|
|
343
350
|
|
|
344
351
|
def _headless_latch_reason(facade):
|
|
352
|
+
from .keepwarm_auto import accounting_error, retry_accounting_read
|
|
353
|
+
from .lease_candidate_cleanup import owner_is_gone
|
|
345
354
|
try:
|
|
346
355
|
path = _headless_latch(facade)
|
|
347
356
|
if path.is_symlink():
|
|
348
357
|
return 'headless-proof'
|
|
349
|
-
|
|
350
|
-
|
|
358
|
+
def read():
|
|
359
|
+
with path.open(encoding='utf-8') as stream:
|
|
360
|
+
return stream.read(128).split()
|
|
361
|
+
state = retry_accounting_read(read)
|
|
351
362
|
if state and state[0] == 'pending':
|
|
352
|
-
if len(state) == 3 and state[2].isdecimal()
|
|
363
|
+
pid = int(state[2]) if len(state) == 3 and state[2].isdecimal() else 0
|
|
364
|
+
if os.name == 'posix' and 1 < pid < 2**31 and not owner_is_gone(pid):
|
|
353
365
|
return 'headless-busy'
|
|
354
366
|
if 0 <= facade.time.time() - path.stat().st_mtime < 200:
|
|
355
367
|
return 'headless-busy'
|
|
356
368
|
return 'headless-proof'
|
|
357
369
|
except FileNotFoundError:
|
|
358
370
|
return None
|
|
359
|
-
except OSError:
|
|
360
|
-
return 'accounting-unavailable'
|
|
371
|
+
except OSError as exc:
|
|
372
|
+
return 'headless-busy' if accounting_error(exc) == 'ledger-locked' else 'accounting-unavailable'
|
|
361
373
|
except UnicodeError:
|
|
362
374
|
return 'headless-proof'
|
|
363
375
|
|
|
@@ -452,7 +464,7 @@ def _pending_attempt(rows, sid, now, timeout=600):
|
|
|
452
464
|
def fire_headless(facade, record, *, now, env=None, runner=None, live=None, meters=None):
|
|
453
465
|
"""Reserve once under the shared lock, then run one bounded fork and prove it."""
|
|
454
466
|
from .mod_action_booking import _append, _lock
|
|
455
|
-
from .keepwarm_auto import read_ledger
|
|
467
|
+
from .keepwarm_auto import accounting_error, read_ledger
|
|
456
468
|
|
|
457
469
|
sid, model = record['session_id'], record['model']
|
|
458
470
|
context = record['prefix_proxy']
|
|
@@ -474,9 +486,10 @@ def fire_headless(facade, record, *, now, env=None, runner=None, live=None, mete
|
|
|
474
486
|
if meters is None:
|
|
475
487
|
meters = _headless_meters(facade, now)
|
|
476
488
|
try:
|
|
489
|
+
# Stale 5.13.76 readers can exceed the daily cap by multiple pings during upgrade overlap.
|
|
477
490
|
rows = read_ledger(facade._keepwarm_ledger_path())
|
|
478
|
-
except (OSError, ValueError):
|
|
479
|
-
return {'fired': False, 'reason':
|
|
491
|
+
except (OSError, ValueError) as exc:
|
|
492
|
+
return {'fired': False, 'reason': accounting_error(exc)}
|
|
480
493
|
decision = _headless_decision(facade, record, now, env, meters, rows)
|
|
481
494
|
if decision['action'] != 'ping':
|
|
482
495
|
return {'fired': False, 'reason': decision['reason']}
|
|
@@ -509,6 +522,7 @@ def fire_headless(facade, record, *, now, env=None, runner=None, live=None, mete
|
|
|
509
522
|
try:
|
|
510
523
|
_append(facade._keepwarm_ledger_path(), {**common, 'status': 'firing',
|
|
511
524
|
'ts': now, 'est_cost_usd': fallback})
|
|
525
|
+
keepwarm_rearm.verify_spend(held)
|
|
512
526
|
reason = _headless_preference_disabled(facade, env) if live() else 'session-changed'
|
|
513
527
|
if reason:
|
|
514
528
|
_append(facade._keepwarm_ledger_path(), {**common, 'status': 'cancelled', 'ts': now})
|
|
@@ -531,9 +545,9 @@ def fire_headless(facade, record, *, now, env=None, runner=None, live=None, mete
|
|
|
531
545
|
continue
|
|
532
546
|
_append(facade._keepwarm_ledger_path(), {**common, **outcome, 'ts': max(now, facade.time.time())})
|
|
533
547
|
recorded = True
|
|
534
|
-
if outcome['proof']:
|
|
535
|
-
_track_proven_ping(facade, record, now)
|
|
536
548
|
break
|
|
549
|
+
if recorded and outcome['proof']:
|
|
550
|
+
_track_proven_ping(facade, record, now)
|
|
537
551
|
finally:
|
|
538
552
|
# The pending marker excludes other headless pings until we settle it.
|
|
539
553
|
# If the ledger stays locked, the reservation still counts at fallback cost.
|
|
@@ -552,13 +566,12 @@ def _track_proven_ping(facade, record, now):
|
|
|
552
566
|
"""Append a replacement arm under the shared lock, only after proven usage."""
|
|
553
567
|
from .mod_action_booking import _append
|
|
554
568
|
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
_append(facade._keepwarm_sidecar_path(), updated)
|
|
569
|
+
with facade._keepwarm_lock() as held:
|
|
570
|
+
if held:
|
|
571
|
+
found = next((r for r in reversed(facade.load_keepwarm_records()) if same_pause(r, record)
|
|
572
|
+
and r['session_id'] == record['session_id']), record)
|
|
573
|
+
_append(facade._keepwarm_sidecar_path(), dict(found, auto_warm=True,
|
|
574
|
+
pings_fired=[*(found.get('pings_fired') or []), now]))
|
|
562
575
|
|
|
563
576
|
|
|
564
577
|
def _headless_meters(facade, now):
|
|
@@ -709,26 +722,13 @@ def stop_flush_args(facade, args, hook_input):
|
|
|
709
722
|
or 'agent_id' in hook_input or 'agent_type' in hook_input
|
|
710
723
|
or str(hook_input.get('hook_event_name', 'Stop')).lower() != 'stop'
|
|
711
724
|
or not facade._keepwarm_valid_arg(sid)
|
|
712
|
-
or '--transcript-path' not in args
|
|
713
|
-
or headless_disabled(facade) not in (None, 'headless-busy')):
|
|
725
|
+
or '--transcript-path' not in args or 'subagents' in Path(transcript).parts):
|
|
714
726
|
return args
|
|
715
727
|
parent_pid = int(os.environ.get(HOOK_PARENT_PID_ENV, '0'))
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
from .cold_guard import _bounded_last_usage, _TAIL_BYTES
|
|
721
|
-
from .keepwarm_auto import MIN_CONTEXT
|
|
722
|
-
|
|
723
|
-
usage, _, _ = _bounded_last_usage(path)
|
|
724
|
-
# A large tool result can hide the usage row from this bounded read.
|
|
725
|
-
# The existing worker checks the full turn before writing an arm.
|
|
726
|
-
incomplete = usage is None and snapshot.st_size > _TAIL_BYTES
|
|
727
|
-
if incomplete or (usage and facade._keepwarm_prefix_proxy(usage) >= MIN_CONTEXT):
|
|
728
|
-
parent_pid, parent_start = _stop_parent(facade, parent_pid, os.environ.get('TOKEN_OPTIMIZER_HOOK_PARENT_START'))
|
|
729
|
-
if parent_start:
|
|
730
|
-
args += ['--keepwarm-parent-pid', str(parent_pid), '--keepwarm-parent-start', parent_start,
|
|
731
|
-
'--keepwarm-stop-at', str(now)]
|
|
728
|
+
parent_pid, parent_start = _stop_parent(facade, parent_pid, os.environ.get('TOKEN_OPTIMIZER_HOOK_PARENT_START'))
|
|
729
|
+
if parent_pid > 1 and parent_start:
|
|
730
|
+
args += ['--keepwarm-parent-pid', str(parent_pid), '--keepwarm-parent-start', parent_start,
|
|
731
|
+
'--keepwarm-stop-at', str(now)]
|
|
732
732
|
except Exception:
|
|
733
733
|
pass
|
|
734
734
|
return args
|
|
@@ -777,11 +777,10 @@ def watch_armed_terminal(facade, sid):
|
|
|
777
777
|
"""Reuse the flush process, with one watcher per terminal session."""
|
|
778
778
|
import fcntl
|
|
779
779
|
filename = hashlib.sha256(sid.encode('utf-8')).hexdigest()
|
|
780
|
-
path = facade.SNAPSHOT_DIR / ('
|
|
780
|
+
path = facade.SNAPSHOT_DIR / ('kw2-watch-' + filename)
|
|
781
781
|
fd = os.open(str(path), os.O_CREAT | os.O_WRONLY | getattr(os, 'O_NOFOLLOW', 0), 0o600)
|
|
782
782
|
try:
|
|
783
783
|
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
784
|
-
os.utime(fd)
|
|
785
784
|
except BaseException:
|
|
786
785
|
os.close(fd)
|
|
787
786
|
raise
|
|
@@ -796,7 +795,8 @@ def _watch_delay(facade, record, fd):
|
|
|
796
795
|
disabled = headless_disabled(facade)
|
|
797
796
|
if disabled not in (None, 'headless-busy') or not record:
|
|
798
797
|
return None
|
|
799
|
-
|
|
798
|
+
ended = session_ended(facade.SNAPSHOT_DIR, record['session_id'], record['ts'])
|
|
799
|
+
if ended or not owner_alive(record['owner']):
|
|
800
800
|
return None
|
|
801
801
|
rows = facade._keepwarm_load_ledger_rows()
|
|
802
802
|
if (now - record['last_turn_ts'] > policy.CACHE_LIFETIME * policy.MAX_PER_PAUSE
|
|
@@ -804,9 +804,7 @@ def _watch_delay(facade, record, fd):
|
|
|
804
804
|
if _pending_attempt(rows, record['session_id'], now, facade._KEEPWARM_PING_TIMEOUT_SECONDS):
|
|
805
805
|
return 5
|
|
806
806
|
return None
|
|
807
|
-
if
|
|
808
|
-
os.utime(fd)
|
|
809
|
-
if facade.classify_keepwarm_record(record, now=now) != 'still_paused':
|
|
807
|
+
if ended is None or facade.classify_keepwarm_record(record, now=now) != 'still_paused':
|
|
810
808
|
return 30
|
|
811
809
|
if disabled == 'headless-busy':
|
|
812
810
|
return 5
|
|
@@ -69,7 +69,10 @@ def _prepare(facade, event, sid, ident, when):
|
|
|
69
69
|
if not acquired:
|
|
70
70
|
return {'ok': False, 'reason': 'ledger-locked'}
|
|
71
71
|
from . import keepwarm_auto, keepwarm_safety
|
|
72
|
-
|
|
72
|
+
try:
|
|
73
|
+
rows = keepwarm_auto.read_ledger(facade._keepwarm_ledger_path())
|
|
74
|
+
except (ValueError, OSError) as exc:
|
|
75
|
+
return {'ok': False, 'reason': keepwarm_auto.accounting_error(exc)}
|
|
73
76
|
existing = [r for r in rows if r.get('action_id') == ident]
|
|
74
77
|
if existing:
|
|
75
78
|
return {'ok': False, 'reason': 'attempt-already-reserved' if _compatible(existing, sid) else 'identity-conflict'}
|
|
@@ -96,6 +99,8 @@ def _prepare(facade, event, sid, ident, when):
|
|
|
96
99
|
_append(facade._keepwarm_ledger_path(), {'status': 'firing', 'source': 'claude-code-mod',
|
|
97
100
|
'action': 'warm', 'action_id': ident, 'attempt_key': ident, 'session_id': sid,
|
|
98
101
|
'ts': when, 'est_cost_usd': estimate, 'snapshot': snapshot, **flags})
|
|
102
|
+
from .keepwarm_rearm import verify_spend
|
|
103
|
+
verify_spend(acquired)
|
|
99
104
|
return {'ok': True, 'duplicate': False}
|
|
100
105
|
|
|
101
106
|
|
|
@@ -165,8 +170,8 @@ def record(facade, event):
|
|
|
165
170
|
return {'ok': False, 'reason': 'invalid-usage'}
|
|
166
171
|
# Old callers can submit an already answered attempt; new mod calls reserve first.
|
|
167
172
|
facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
|
|
168
|
-
with _lock(facade) as acquired:
|
|
169
|
-
if not acquired:
|
|
173
|
+
with _lock(facade) as acquired, facade._keepwarm_lock() as state:
|
|
174
|
+
if not acquired or not state:
|
|
170
175
|
return {'ok': False, 'reason': 'ledger-locked'}
|
|
171
176
|
existing = [r for r in facade._keepwarm_load_ledger_rows() if r.get('action_id') == ident]
|
|
172
177
|
if existing and not _compatible(existing, sid):
|
|
@@ -349,16 +349,17 @@ def _exclusive(lock_path, timeout=2.0):
|
|
|
349
349
|
os.close(fd)
|
|
350
350
|
|
|
351
351
|
|
|
352
|
-
def _acquire(lock_path, timeout):
|
|
353
|
-
"""
|
|
352
|
+
def _acquire(lock_path, timeout, *, busy=None, nofollow=False):
|
|
353
|
+
"""Return a locked fd, busy on contention, or None for unusable storage."""
|
|
354
354
|
flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0)
|
|
355
355
|
try:
|
|
356
356
|
if os.path.lexists(str(lock_path)) and not stat.S_ISREG(os.stat(str(lock_path)).st_mode):
|
|
357
357
|
return None
|
|
358
|
-
fd = os.open(str(lock_path), flags, 0o600)
|
|
358
|
+
fd = os.open(str(lock_path), flags | (getattr(os, "O_NOFOLLOW", 0) if nofollow else 0), 0o600)
|
|
359
359
|
except OSError:
|
|
360
360
|
return None
|
|
361
361
|
try:
|
|
362
|
+
failure = None
|
|
362
363
|
usable = stat.S_ISREG(os.fstat(fd).st_mode) and (fcntl is not None or msvcrt is not None)
|
|
363
364
|
deadline = time.monotonic() + timeout
|
|
364
365
|
while usable:
|
|
@@ -366,15 +367,16 @@ def _acquire(lock_path, timeout):
|
|
|
366
367
|
if got:
|
|
367
368
|
return fd
|
|
368
369
|
if got is None or time.monotonic() >= deadline:
|
|
370
|
+
failure = busy if got is False else None
|
|
369
371
|
break
|
|
370
372
|
time.sleep(0.01)
|
|
371
373
|
except OSError:
|
|
372
|
-
|
|
374
|
+
failure = None
|
|
373
375
|
except BaseException:
|
|
374
376
|
os.close(fd)
|
|
375
377
|
raise
|
|
376
378
|
os.close(fd)
|
|
377
|
-
return
|
|
379
|
+
return failure
|
|
378
380
|
|
|
379
381
|
|
|
380
382
|
def _update(path, mutate):
|
|
@@ -2447,7 +2447,7 @@ _cache_ttl_waste_cached = _measure_compat.bind(_measure_providers['cache_policy'
|
|
|
2447
2447
|
# cache_health.json / cohort_tripwire.json sites above. NOT compression_log.py
|
|
2448
2448
|
# (that is a SQLite writer despite its name).
|
|
2449
2449
|
|
|
2450
|
-
_KEEPWARM_SIDECAR_NAME = "
|
|
2450
|
+
_KEEPWARM_SIDECAR_NAME = "keepwarm_pauses_v2.jsonl"
|
|
2451
2451
|
_KEEPWARM_LOCK_NAME = ".keepwarm_state.lock"
|
|
2452
2452
|
# Records older than this (by their arm ts) are dropped on compaction regardless of
|
|
2453
2453
|
# state: an arm that never resumed and never got pinged is dead weight after 14d.
|
|
@@ -2746,7 +2746,7 @@ _KEEPWARM_IDLE_RECHECK_SECONDS = 120
|
|
|
2746
2746
|
# Per-session ping lock filename prefix in SNAPSHOT_DIR.
|
|
2747
2747
|
_KEEPWARM_PING_LOCK_PREFIX = ".keepwarm_ping."
|
|
2748
2748
|
# Whole-tick single-instance lock filename.
|
|
2749
|
-
_KEEPWARM_TICK_LOCK_NAME = ".
|
|
2749
|
+
_KEEPWARM_TICK_LOCK_NAME = ".keepwarm-tick-v2.lock"
|
|
2750
2750
|
# Ping-spend / outcome ledger sidecar (operational accounting only; realized
|
|
2751
2751
|
# savings live in the SQLite path, NOT here).
|
|
2752
2752
|
_KEEPWARM_LEDGER_NAME = "keepwarm_ledger.jsonl"
|