@alexgreensh/token-optimizer 5.13.69 → 5.13.70
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/PRIVACY.md +4 -0
- package/hooks/hooks.json +11 -1
- package/hooks/module_runner.py +4 -1
- package/hooks/posttooluse_runner.py +44 -48
- package/hooks/sessionstart_runner.py +24 -5
- package/hooks/stop_runner.py +6 -6
- package/package.json +1 -1
- package/skills/token-optimizer/assets/dashboard.html +399 -509
- package/skills/token-optimizer/assets/savings_story.js +661 -0
- package/skills/token-optimizer/pricing/prices.json +1 -0
- package/skills/token-optimizer/references/implementation-playbook.md +3 -0
- package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
- package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
- package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
- package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
- package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
- package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
- package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
- package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
- package/skills/token-optimizer/scripts/_measure/cli.py +12 -8
- package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
- package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
- package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
- package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
- package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
- package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
- package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
- package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
- package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
- package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
- package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
- package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
- package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
- package/skills/token-optimizer/scripts/_measure/daemon.py +53 -74
- package/skills/token-optimizer/scripts/_measure/dashboard.py +87 -151
- package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
- package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
- package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
- package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
- package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
- package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
- package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
- package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
- package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
- package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
- package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
- package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
- package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
- package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
- package/skills/token-optimizer/scripts/_measure/lifecycle.py +54 -162
- package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
- package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
- package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
- package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
- package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
- package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
- package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
- package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
- package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
- package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
- package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
- package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
- package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
- package/skills/token-optimizer/scripts/_measure/savings.py +431 -863
- package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
- package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
- package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
- package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
- package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
- package/skills/token-optimizer/scripts/_measure/sessions.py +96 -196
- package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
- package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
- package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
- package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
- package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
- package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
- package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
- package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
- package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
- package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
- package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
- package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
- package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
- package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
- package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
- package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
- package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
- package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
- package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
- package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
- package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
- package/skills/token-optimizer/scripts/antigravity_install.py +2 -0
- package/skills/token-optimizer/scripts/archive_result.py +15 -19
- package/skills/token-optimizer/scripts/archive_verify.py +165 -0
- package/skills/token-optimizer/scripts/bash_compress.py +14 -43
- package/skills/token-optimizer/scripts/bash_compress_hook.py +132 -2
- package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
- package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
- package/skills/token-optimizer/scripts/codemap.py +274 -0
- package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
- package/skills/token-optimizer/scripts/codemap_index.py +656 -0
- package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
- package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
- package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
- package/skills/token-optimizer/scripts/codex_session.py +16 -216
- package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
- package/skills/token-optimizer/scripts/context_intel.py +5 -3
- package/skills/token-optimizer/scripts/copilot_install.py +2 -0
- package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
- package/skills/token-optimizer/scripts/cursor_install.py +12 -0
- package/skills/token-optimizer/scripts/cursor_quality.py +16 -64
- package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
- package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
- package/skills/token-optimizer/scripts/devin_source.py +8 -3
- package/skills/token-optimizer/scripts/devin_verify.py +7 -1
- package/skills/token-optimizer/scripts/grok_install.py +2 -0
- package/skills/token-optimizer/scripts/heal_report.py +7 -6
- package/skills/token-optimizer/scripts/hermes_doctor.py +9 -1
- package/skills/token-optimizer/scripts/hermes_install.py +7 -1
- package/skills/token-optimizer/scripts/hermes_session.py +14 -136
- package/skills/token-optimizer/scripts/hint_paths.py +21 -0
- package/skills/token-optimizer/scripts/holdout.py +136 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
- package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
- package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
- package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
- package/skills/token-optimizer/scripts/measure.py +34 -76
- package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
- package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
- package/skills/token-optimizer/scripts/read_cache.py +99 -100
- package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
- package/skills/token-optimizer/scripts/session_store.py +49 -99
- package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
- package/skills/token-optimizer/scripts/settings_backup.py +379 -0
- package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
- package/skills/token-optimizer/scripts/statusline.js +1 -1
- package/skills/token-optimizer/scripts/structural.py +25 -0
- package/skills/token-optimizer/scripts/structure_map.py +4 -26
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"""Fail-closed liveness checks for paused Claude sessions."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import re
|
|
7
|
+
import shlex
|
|
8
|
+
import shutil
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
import time
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def process_info(pid):
|
|
15
|
+
try:
|
|
16
|
+
proc = subprocess.run(['ps', '-p', str(int(pid)), '-o', 'ppid=', '-o', 'lstart=', '-o', 'comm='],
|
|
17
|
+
capture_output=True, text=True, timeout=1, check=True)
|
|
18
|
+
parts = proc.stdout.strip().split(None, 6)
|
|
19
|
+
if len(parts) != 7:
|
|
20
|
+
return None
|
|
21
|
+
return {'ppid': int(parts[0]), 'start': ' '.join(parts[1:6]), 'command': parts[6]}
|
|
22
|
+
except (OSError, ValueError, subprocess.SubprocessError):
|
|
23
|
+
return None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def interactive_parent(argv, tty, descriptors, ancestors):
|
|
27
|
+
"""Require real terminal I/O and reject explicit print or known delegates."""
|
|
28
|
+
if not tty or len(descriptors) != 2:
|
|
29
|
+
return False
|
|
30
|
+
if not all(path.startswith(('/dev/tty', '/dev/pts/')) for path in descriptors):
|
|
31
|
+
return False
|
|
32
|
+
for arg in argv[1:]:
|
|
33
|
+
if arg == '--':
|
|
34
|
+
break
|
|
35
|
+
if arg == '--print' or arg.startswith('--print=') or (arg.startswith('-') and not arg.startswith('--') and 'p' in arg[1:]):
|
|
36
|
+
return False
|
|
37
|
+
return not any('outsourcerer' in command.lower() or 'osrc-' in command.lower() for command in ancestors)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def is_claude_command(command):
|
|
41
|
+
path = Path(str(command))
|
|
42
|
+
return (path.name.lower() == 'claude' or
|
|
43
|
+
(path.parent.name == 'versions' and path.parent.parent.name == 'claude' and
|
|
44
|
+
bool(re.fullmatch(r'\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?', path.name))))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _ps_command(pid):
|
|
48
|
+
proc = subprocess.run(['ps', '-p', str(int(pid)), '-o', 'tty=', '-o', 'args='],
|
|
49
|
+
capture_output=True, text=True, timeout=1, check=True)
|
|
50
|
+
tty, args = proc.stdout.strip().split(None, 1)
|
|
51
|
+
return tty, shlex.split(args)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _terminal_descriptors(pid):
|
|
55
|
+
if sys.platform.startswith('linux'):
|
|
56
|
+
return [os.readlink('/proc/%s/fd/%s' % (pid, fd)) for fd in (0, 1)]
|
|
57
|
+
if sys.platform == 'darwin':
|
|
58
|
+
proc = subprocess.run(['/usr/sbin/lsof', '-nP', '-a', '-p', str(int(pid)), '-d', '0,1', '-Ffn'],
|
|
59
|
+
capture_output=True, text=True, timeout=2, check=True)
|
|
60
|
+
found, descriptor = {}, None
|
|
61
|
+
for line in proc.stdout.splitlines():
|
|
62
|
+
if line.startswith('f'):
|
|
63
|
+
descriptor = line[1:]
|
|
64
|
+
elif line.startswith('n') and descriptor in ('0', '1'):
|
|
65
|
+
found[descriptor] = line[1:]
|
|
66
|
+
return [found.get('0', ''), found.get('1', '')]
|
|
67
|
+
return []
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def tmux_parent_allowed(panes, ancestry):
|
|
71
|
+
"""Reject identifiable delegate sessions and unknown pane ancestry."""
|
|
72
|
+
names = []
|
|
73
|
+
for line in panes.splitlines():
|
|
74
|
+
try:
|
|
75
|
+
pane_pid, name = line.split('\t', 1)
|
|
76
|
+
if int(pane_pid) in ancestry:
|
|
77
|
+
names.append(name.lower())
|
|
78
|
+
except (ValueError, TypeError):
|
|
79
|
+
continue
|
|
80
|
+
return bool(names) and not any(name.startswith(('outsourcerer-', 'osrc-')) for name in names)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def owner_eligible(pid):
|
|
84
|
+
try:
|
|
85
|
+
tty, argv = _ps_command(pid)
|
|
86
|
+
ancestors, ancestry, has_tmux = [], {pid}, False
|
|
87
|
+
info = process_info(pid)
|
|
88
|
+
for _ in range(16):
|
|
89
|
+
if not info or info['ppid'] <= 1:
|
|
90
|
+
break
|
|
91
|
+
parent = info['ppid']
|
|
92
|
+
_, args = _ps_command(parent)
|
|
93
|
+
ancestors.append(' '.join(args))
|
|
94
|
+
info = process_info(parent)
|
|
95
|
+
if not info:
|
|
96
|
+
return False
|
|
97
|
+
ancestry.add(parent)
|
|
98
|
+
has_tmux = has_tmux or Path(info['command']).name.lower().startswith('tmux')
|
|
99
|
+
if has_tmux:
|
|
100
|
+
binary = shutil.which('tmux') or next((path for path in ('/opt/homebrew/bin/tmux', '/usr/local/bin/tmux', '/usr/bin/tmux') if os.path.isfile(path)), None)
|
|
101
|
+
if not binary:
|
|
102
|
+
return False
|
|
103
|
+
panes = subprocess.run([binary, 'list-panes', '-a', '-F', '#{pane_pid}\t#{session_name}'],
|
|
104
|
+
capture_output=True, text=True, timeout=2, check=True).stdout
|
|
105
|
+
if not tmux_parent_allowed(panes, ancestry):
|
|
106
|
+
return False
|
|
107
|
+
return interactive_parent(argv, tty, _terminal_descriptors(pid), ancestors)
|
|
108
|
+
except (OSError, ValueError, subprocess.SubprocessError):
|
|
109
|
+
return False
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def find_owner(pid=None, lookup=process_info, eligibility=owner_eligible):
|
|
113
|
+
pid = os.getppid() if pid is None else pid
|
|
114
|
+
for _ in range(16):
|
|
115
|
+
if pid <= 1:
|
|
116
|
+
break
|
|
117
|
+
info = lookup(pid)
|
|
118
|
+
if not info:
|
|
119
|
+
break
|
|
120
|
+
if is_claude_command(info['command']):
|
|
121
|
+
return {'pid': pid, 'start': info['start']} if eligibility(pid) else None
|
|
122
|
+
pid = info['ppid']
|
|
123
|
+
return None
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
_NO_OWNER_TTL = 300.0
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _owner_cache_path(directory, session_id):
|
|
130
|
+
name = hashlib.sha256(str(session_id).encode('utf-8')).hexdigest()
|
|
131
|
+
return Path(directory) / ('keepwarm-owner-' + name)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _pid_exists(pid):
|
|
135
|
+
"""Subprocess-free liveness; the tick re-verifies identity with owner_alive."""
|
|
136
|
+
if os.name != 'posix':
|
|
137
|
+
return False
|
|
138
|
+
try:
|
|
139
|
+
os.kill(int(pid), 0)
|
|
140
|
+
except PermissionError:
|
|
141
|
+
return True
|
|
142
|
+
except (OSError, ValueError, TypeError):
|
|
143
|
+
return False
|
|
144
|
+
return True
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def session_owner(directory, session_id, now=None):
|
|
148
|
+
"""find_owner once per session, not once per Stop hook.
|
|
149
|
+
|
|
150
|
+
The owning Claude process is constant for a session, but find_owner walks the
|
|
151
|
+
process table with several `ps`/`lsof` children. A positive answer is reused
|
|
152
|
+
while the pid still exists; a negative one for _NO_OWNER_TTL seconds, so an
|
|
153
|
+
ineligible session does not re-run the walk on every turn. Fail closed: any
|
|
154
|
+
cache problem falls through to a fresh lookup.
|
|
155
|
+
"""
|
|
156
|
+
now = time.time() if now is None else now
|
|
157
|
+
path = _owner_cache_path(directory, session_id) if session_id else None
|
|
158
|
+
if path is not None:
|
|
159
|
+
try:
|
|
160
|
+
cached = json.loads(path.read_text(encoding='utf-8'))
|
|
161
|
+
owner = cached.get('owner')
|
|
162
|
+
if isinstance(owner, dict) and owner.get('pid') and owner.get('start'):
|
|
163
|
+
if _pid_exists(owner['pid']):
|
|
164
|
+
return owner
|
|
165
|
+
elif owner is None and 0 <= now - float(cached.get('ts')) < _NO_OWNER_TTL:
|
|
166
|
+
return None
|
|
167
|
+
except (OSError, ValueError, TypeError, AttributeError):
|
|
168
|
+
pass
|
|
169
|
+
owner = find_owner()
|
|
170
|
+
if path is not None:
|
|
171
|
+
try:
|
|
172
|
+
Path(directory).mkdir(parents=True, exist_ok=True)
|
|
173
|
+
fd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, 'O_NOFOLLOW', 0), 0o600)
|
|
174
|
+
with os.fdopen(fd, 'w', encoding='utf-8') as stream:
|
|
175
|
+
json.dump({'owner': owner, 'ts': now}, stream)
|
|
176
|
+
except OSError:
|
|
177
|
+
pass
|
|
178
|
+
return owner
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def owner_alive(owner, lookup=process_info, eligibility=owner_eligible):
|
|
182
|
+
if not isinstance(owner, dict) or not owner.get('pid') or not owner.get('start'):
|
|
183
|
+
return False
|
|
184
|
+
info = lookup(owner['pid'])
|
|
185
|
+
return bool(info and is_claude_command(info['command']) and info['start'] == owner['start'] and eligibility(owner['pid']))
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _end_path(directory, session_id):
|
|
189
|
+
name = hashlib.sha256(str(session_id).encode('utf-8')).hexdigest()
|
|
190
|
+
return Path(directory) / ('keepwarm-ended-' + name)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def mark_ended(directory, session_id):
|
|
194
|
+
if not session_id:
|
|
195
|
+
return False
|
|
196
|
+
try:
|
|
197
|
+
Path(directory).mkdir(parents=True, exist_ok=True)
|
|
198
|
+
path = _end_path(directory, session_id)
|
|
199
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, 'O_NOFOLLOW', 0)
|
|
200
|
+
fd = os.open(str(path), flags, 0o600)
|
|
201
|
+
with os.fdopen(fd, 'w', encoding='utf-8') as stream:
|
|
202
|
+
if hasattr(os, 'fchmod'):
|
|
203
|
+
os.fchmod(stream.fileno(), 0o600)
|
|
204
|
+
stream.write(str(time.time()))
|
|
205
|
+
return True
|
|
206
|
+
except OSError:
|
|
207
|
+
return False
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def ended_since(directory, session_id, armed_at):
|
|
211
|
+
try:
|
|
212
|
+
path = _end_path(directory, session_id)
|
|
213
|
+
if path.is_symlink():
|
|
214
|
+
return True
|
|
215
|
+
return float(path.read_text(encoding='utf-8')) >= float(armed_at)
|
|
216
|
+
except FileNotFoundError:
|
|
217
|
+
return False
|
|
218
|
+
except (OSError, ValueError, TypeError):
|
|
219
|
+
return True
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def compacted_since(record):
|
|
223
|
+
"""Fail closed if the post-arm transcript is missing, truncated or too large."""
|
|
224
|
+
try:
|
|
225
|
+
path = Path(record['transcript_path'])
|
|
226
|
+
offset = int(record['byte_size'])
|
|
227
|
+
if offset < 0 or path.stat().st_size < offset or path.stat().st_size - offset > 5 * 1024 * 1024:
|
|
228
|
+
return True
|
|
229
|
+
with path.open('rb') as stream:
|
|
230
|
+
stream.seek(offset)
|
|
231
|
+
tail = stream.read()
|
|
232
|
+
return b'compact_boundary' in tail or b'isCompactSummary' in tail
|
|
233
|
+
except (KeyError, OSError, TypeError, ValueError):
|
|
234
|
+
return True
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def reconcile_attempts(record, rows):
|
|
238
|
+
"""Recover attempt caps from the append-only ledger after a tick crash."""
|
|
239
|
+
session = str(record.get('session_id') or '')
|
|
240
|
+
start = float(record.get('ts') or 0)
|
|
241
|
+
relevant = [row for row in rows if str(row.get('session_id') or '') == session
|
|
242
|
+
and float(row.get('ts') or 0) >= start]
|
|
243
|
+
attempts = [float(row['ts']) for row in relevant if row.get('status') == 'firing']
|
|
244
|
+
outcomes = [row for row in relevant if row.get('status') in ('ok', 'error', 'timeout')]
|
|
245
|
+
changed = False
|
|
246
|
+
if len(attempts) > len(record.get('pings_fired') or []):
|
|
247
|
+
record['pings_fired'] = sorted(attempts)
|
|
248
|
+
changed = True
|
|
249
|
+
prefix = int(record.get('prefix_proxy') or 0)
|
|
250
|
+
unsafe = any(row.get('status') != 'ok' or int(row.get('cache_read') or 0) < prefix * 0.5
|
|
251
|
+
or int(row.get('cache_write') or 0) >= prefix * 0.5 for row in outcomes)
|
|
252
|
+
if attempts and (len(outcomes) < len(attempts) or unsafe):
|
|
253
|
+
if not record.get('ping_failed'):
|
|
254
|
+
record['ping_failed'] = True
|
|
255
|
+
changed = True
|
|
256
|
+
return changed
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
"""Recover historical lean-resume receivers from delivered hook attachments."""
|
|
2
|
+
import json
|
|
3
|
+
import hashlib
|
|
4
|
+
import re
|
|
5
|
+
import time
|
|
6
|
+
from collections import defaultdict
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from . import upgrade_drain_control
|
|
10
|
+
|
|
11
|
+
_MARK = re.compile(r'Cold-resume lean \(session ([0-9a-fA-F]{8})(?=[, )])')
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _stat_matches(path, size, mtime):
|
|
15
|
+
try:
|
|
16
|
+
s = Path(path).stat()
|
|
17
|
+
return s.st_size == size and s.st_mtime_ns == mtime
|
|
18
|
+
except OSError:
|
|
19
|
+
return False
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _generation(conn, include_sessions=True):
|
|
23
|
+
events = conn.execute("SELECT id,timestamp,COALESCE(session_uuid,session_id),detail FROM savings_events WHERE event_type='resume_lean' ORDER BY id").fetchall()
|
|
24
|
+
sessions = conn.execute('SELECT session_uuid,jsonl_path FROM session_log WHERE session_uuid IS NOT NULL AND jsonl_path IS NOT NULL ORDER BY id').fetchall()
|
|
25
|
+
return hashlib.sha256(repr(('receiver_scan_v3', events, sessions if include_sessions else [])).encode()).hexdigest()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# A marker is delivered within three minutes of its event; a day of slack keeps
|
|
29
|
+
# the comparison safe across time zones and clock skew.
|
|
30
|
+
_MARGIN_S = 86400 + 180
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _epoch(stamp):
|
|
34
|
+
"""Seconds for an event or file time, or None. Naive stamps are local time."""
|
|
35
|
+
try:
|
|
36
|
+
return datetime.fromisoformat(str(stamp).replace('Z', '+00:00')).timestamp()
|
|
37
|
+
except (TypeError, ValueError, OverflowError, OSError):
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _session_rows(conn):
|
|
42
|
+
"""(session_uuid, path, start day or None), oldest row first."""
|
|
43
|
+
cols = {row[1] for row in conn.execute('PRAGMA table_info(session_log)')}
|
|
44
|
+
days = [c for c in ('first_activity_day', 'date') if c in cols]
|
|
45
|
+
day = ('MIN(' + ','.join("COALESCE(NULLIF(%s,''),'9999')" % c for c in days) + ')') if len(days) == 2 else (days[0] if days else 'NULL')
|
|
46
|
+
out = []
|
|
47
|
+
for sid, path, start in conn.execute('SELECT session_uuid,jsonl_path,' + day + ' FROM session_log WHERE session_uuid IS NOT NULL AND jsonl_path IS NOT NULL ORDER BY id'):
|
|
48
|
+
start = str(start)[:10] if start else None
|
|
49
|
+
out.append((sid, path, start if start and start[:1].isdigit() and start < '9999' else None))
|
|
50
|
+
return out
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _could_hold(start_day, mtime_s, event_epoch):
|
|
54
|
+
"""Whether a transcript that began on `start_day` and was last written at
|
|
55
|
+
`mtime_s` can contain the delivery of an event at `event_epoch`."""
|
|
56
|
+
if event_epoch is None:
|
|
57
|
+
return True
|
|
58
|
+
if mtime_s < event_epoch - _MARGIN_S:
|
|
59
|
+
return False
|
|
60
|
+
begin = _epoch(start_day) if start_day else None
|
|
61
|
+
return begin is None or begin <= event_epoch + _MARGIN_S
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _coverage(conn):
|
|
65
|
+
"""{generation: highest event id its scans looked for}."""
|
|
66
|
+
conn.execute('CREATE TABLE IF NOT EXISTS lean_receiver_generations (generation TEXT PRIMARY KEY, max_event_id INTEGER)')
|
|
67
|
+
return dict(conn.execute('SELECT generation,max_event_id FROM lean_receiver_generations').fetchall())
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def collect(conn, to_utc, max_files=8, deadline_seconds=None):
|
|
71
|
+
started = time.monotonic()
|
|
72
|
+
conn.execute('CREATE TABLE IF NOT EXISTS lean_receiver_candidates (event_id INTEGER, receiver TEXT, path TEXT, size INTEGER, mtime_ns INTEGER, PRIMARY KEY(event_id,receiver,path,size,mtime_ns))')
|
|
73
|
+
conn.execute('CREATE TABLE IF NOT EXISTS lean_receiver_scans (path TEXT, size INTEGER, mtime_ns INTEGER, generation TEXT, PRIMARY KEY(path,size,mtime_ns,generation))')
|
|
74
|
+
conn.execute('CREATE TABLE IF NOT EXISTS lean_receiver_state (id INTEGER PRIMARY KEY, complete INTEGER, generation TEXT)')
|
|
75
|
+
generation = _generation(conn)
|
|
76
|
+
event_generation = _generation(conn, include_sessions=False)
|
|
77
|
+
targets = defaultdict(list)
|
|
78
|
+
newest = conn.execute("SELECT COALESCE(MAX(id),0) FROM savings_events WHERE event_type='resume_lean'").fetchone()[0]
|
|
79
|
+
covered = _coverage(conn)
|
|
80
|
+
conn.execute('INSERT OR REPLACE INTO lean_receiver_generations VALUES (?,?)', (event_generation, newest))
|
|
81
|
+
pending_events = []
|
|
82
|
+
for ident, stamp, sid, detail in conn.execute("SELECT id,timestamp,COALESCE(session_uuid,session_id),detail FROM savings_events WHERE event_type='resume_lean'"):
|
|
83
|
+
dt = to_utc(stamp)
|
|
84
|
+
if sid and dt and 'receiver=' not in (detail or ''):
|
|
85
|
+
targets[sid[:8].lower()].append((ident, sid, dt))
|
|
86
|
+
pending_events.append((ident, _epoch(stamp)))
|
|
87
|
+
if not targets:
|
|
88
|
+
conn.execute('INSERT OR REPLACE INTO lean_receiver_state VALUES (1, 1, ?)', (generation,))
|
|
89
|
+
conn.commit()
|
|
90
|
+
return {'scanned': 0, 'matches': 0, 'pending': 0, 'unavailable': 0}
|
|
91
|
+
sessions, starts = {}, {}
|
|
92
|
+
for sid, path, start in _session_rows(conn):
|
|
93
|
+
sessions[path], starts[path] = sid, start
|
|
94
|
+
out = {'scanned': 0, 'matches': 0, 'pending': 0, 'unavailable': 0}
|
|
95
|
+
for path, receiver in sessions.items():
|
|
96
|
+
try:
|
|
97
|
+
st = Path(path).stat()
|
|
98
|
+
except OSError:
|
|
99
|
+
out['unavailable'] += 1
|
|
100
|
+
continue
|
|
101
|
+
proof = (path, st.st_size, st.st_mtime_ns)
|
|
102
|
+
if conn.execute('SELECT 1 FROM lean_receiver_scans WHERE path=? AND size=? AND mtime_ns=? AND generation=?', (*proof, event_generation)).fetchone():
|
|
103
|
+
continue
|
|
104
|
+
# An unchanged file already searched for every event up to id N only
|
|
105
|
+
# needs reading again when a later event could have been delivered in it.
|
|
106
|
+
seen = max([covered.get(g, -1) for (g,) in conn.execute('SELECT generation FROM lean_receiver_scans WHERE path=? AND size=? AND mtime_ns=?', proof)] or [-1])
|
|
107
|
+
if seen >= 0 and not any(ident > seen and _could_hold(starts.get(path), st.st_mtime, when) for ident, when in pending_events):
|
|
108
|
+
conn.execute('INSERT OR IGNORE INTO lean_receiver_scans VALUES (?,?,?,?)', (*proof, event_generation))
|
|
109
|
+
continue
|
|
110
|
+
if (max_files is not None and out['scanned'] >= max_files) or (deadline_seconds is not None and time.monotonic() - started >= deadline_seconds):
|
|
111
|
+
out['pending'] += 1
|
|
112
|
+
continue
|
|
113
|
+
out['scanned'] += 1
|
|
114
|
+
found = set()
|
|
115
|
+
try:
|
|
116
|
+
with open(path, 'r', encoding='utf-8', errors='replace') as stream:
|
|
117
|
+
for line in stream:
|
|
118
|
+
if 'Cold-resume lean (session ' not in line:
|
|
119
|
+
continue
|
|
120
|
+
try:
|
|
121
|
+
obj = json.loads(line)
|
|
122
|
+
when = datetime.fromisoformat(obj.get('timestamp', '').replace('Z', '+00:00')).astimezone(timezone.utc).replace(tzinfo=None)
|
|
123
|
+
except (ValueError, TypeError):
|
|
124
|
+
continue
|
|
125
|
+
att = obj.get('attachment') or {}
|
|
126
|
+
if obj.get('type') != 'attachment' or obj.get('isSidechain') or att.get('type') != 'hook_additional_context':
|
|
127
|
+
continue
|
|
128
|
+
for match in _MARK.finditer(json.dumps(att)):
|
|
129
|
+
possible = [(ident, target) for ident, target, stamp in targets.get(match.group(1).lower(), ())
|
|
130
|
+
if receiver != target and abs((when - stamp).total_seconds()) <= 180]
|
|
131
|
+
if len(possible) == 1:
|
|
132
|
+
found.add((possible[0][0], receiver, path, st.st_size, st.st_mtime_ns))
|
|
133
|
+
except OSError:
|
|
134
|
+
out['unavailable'] += 1
|
|
135
|
+
continue
|
|
136
|
+
if not _stat_matches(*proof):
|
|
137
|
+
out['pending'] += 1
|
|
138
|
+
continue
|
|
139
|
+
for item in found:
|
|
140
|
+
r = conn.execute('INSERT OR IGNORE INTO lean_receiver_candidates VALUES (?,?,?,?,?)', item)
|
|
141
|
+
out['matches'] += max(0, r.rowcount)
|
|
142
|
+
conn.execute('INSERT OR IGNORE INTO lean_receiver_scans VALUES (?,?,?,?)', (*proof, event_generation))
|
|
143
|
+
upgrade_drain_control.commit_drain_session(conn)
|
|
144
|
+
conn.execute('INSERT OR REPLACE INTO lean_receiver_state VALUES (1, ?, ?)', (int(out['pending'] == 0), generation))
|
|
145
|
+
conn.commit()
|
|
146
|
+
return out
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _delivered(path, size, mtime):
|
|
150
|
+
"""A transcript only grows, so a marker found in it earlier is still there."""
|
|
151
|
+
try:
|
|
152
|
+
s = Path(path).stat()
|
|
153
|
+
return s.st_size >= size and s.st_mtime_ns >= mtime
|
|
154
|
+
except OSError:
|
|
155
|
+
return False
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
# Unsearched transcripts read on the spot per call, so a session indexed since
|
|
159
|
+
# the last collect pass does not hold recent events back until the next one.
|
|
160
|
+
_INLINE_FILES = 16
|
|
161
|
+
_INLINE_BYTES = 256 * 1024 * 1024
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _deliveries(path):
|
|
165
|
+
"""[(session prefix, epoch seconds)] of every lean-resume marker delivered in
|
|
166
|
+
a transcript, or None when it cannot be read."""
|
|
167
|
+
out = []
|
|
168
|
+
try:
|
|
169
|
+
with open(path, 'r', encoding='utf-8', errors='replace') as stream:
|
|
170
|
+
for line in stream:
|
|
171
|
+
if 'Cold-resume lean (session ' not in line:
|
|
172
|
+
continue
|
|
173
|
+
try:
|
|
174
|
+
obj = json.loads(line)
|
|
175
|
+
except ValueError:
|
|
176
|
+
continue
|
|
177
|
+
att = obj.get('attachment') or {}
|
|
178
|
+
if obj.get('type') != 'attachment' or obj.get('isSidechain') or att.get('type') != 'hook_additional_context':
|
|
179
|
+
continue
|
|
180
|
+
when = _epoch(obj.get('timestamp'))
|
|
181
|
+
if when is not None:
|
|
182
|
+
out.extend((match.group(1).lower(), when) for match in _MARK.finditer(json.dumps(att)))
|
|
183
|
+
except OSError:
|
|
184
|
+
return None
|
|
185
|
+
return out
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def resolved(conn):
|
|
189
|
+
"""{event id: receiver session} for events with exactly one proven receiver.
|
|
190
|
+
|
|
191
|
+
An event is held back only while a transcript that could contain a second
|
|
192
|
+
delivery of it has not been searched: a file never scanned that was active
|
|
193
|
+
around the event, or lines appended after the last scan to a file that was.
|
|
194
|
+
A session that began later, or text appended long after the event, cannot
|
|
195
|
+
hold that delivery, so it never takes back a receiver already proven.
|
|
196
|
+
"""
|
|
197
|
+
try:
|
|
198
|
+
candidates = defaultdict(set)
|
|
199
|
+
for ident, receiver, path, size, mtime in conn.execute('SELECT event_id,receiver,path,size,mtime_ns FROM lean_receiver_candidates'):
|
|
200
|
+
if _delivered(path, size, mtime):
|
|
201
|
+
candidates[ident].add(receiver)
|
|
202
|
+
single = {ident: next(iter(r)) for ident, r in candidates.items() if len(r) == 1}
|
|
203
|
+
if not single:
|
|
204
|
+
return {}
|
|
205
|
+
events, prefixes = {}, {}
|
|
206
|
+
for ident, stamp, sid in conn.execute(
|
|
207
|
+
"SELECT id,timestamp,COALESCE(session_uuid,session_id) FROM savings_events WHERE event_type='resume_lean'"):
|
|
208
|
+
if ident in single:
|
|
209
|
+
events[ident], prefixes[ident] = _epoch(stamp), str(sid or '')[:8].lower()
|
|
210
|
+
single = {ident: receiver for ident, receiver in single.items() if ident in events}
|
|
211
|
+
if not single:
|
|
212
|
+
return {}
|
|
213
|
+
covered = _coverage(conn)
|
|
214
|
+
scans = defaultdict(list)
|
|
215
|
+
for path, size, mtime, generation in conn.execute('SELECT path,size,mtime_ns,generation FROM lean_receiver_scans'):
|
|
216
|
+
if generation in covered:
|
|
217
|
+
scans[path].append((size, mtime, covered[generation]))
|
|
218
|
+
need = max(single)
|
|
219
|
+
unsearched = [] # (start day, mtime seconds, exact cover id, [(older scan mtime seconds, cover id)], path, receiver, size)
|
|
220
|
+
for sid, path, start in _session_rows(conn):
|
|
221
|
+
try:
|
|
222
|
+
st = Path(path).stat()
|
|
223
|
+
except OSError:
|
|
224
|
+
continue
|
|
225
|
+
exact = max([top for size, mtime, top in scans.get(path, ()) if size == st.st_size and mtime == st.st_mtime_ns] or [-1])
|
|
226
|
+
if exact >= need:
|
|
227
|
+
continue
|
|
228
|
+
older = [(mtime / 1e9, top) for size, mtime, top in scans.get(path, ()) if size <= st.st_size and mtime < st.st_mtime_ns]
|
|
229
|
+
unsearched.append((start, st.st_mtime, exact, older, path, sid, st.st_size))
|
|
230
|
+
out, read, budget = {}, {}, [_INLINE_FILES, _INLINE_BYTES]
|
|
231
|
+
|
|
232
|
+
def second_delivery(path, size, sid, ident, when):
|
|
233
|
+
"""True when this unsearched transcript holds, or may hold, a delivery
|
|
234
|
+
of the event to a different session. Reads it once, within a budget."""
|
|
235
|
+
if path not in read:
|
|
236
|
+
if budget[0] <= 0 or size > budget[1]:
|
|
237
|
+
return True # over budget: stay conservative until collect scans it
|
|
238
|
+
budget[0] -= 1
|
|
239
|
+
budget[1] -= size
|
|
240
|
+
read[path] = _deliveries(path)
|
|
241
|
+
found = read[path]
|
|
242
|
+
if found is None or when is None:
|
|
243
|
+
return True
|
|
244
|
+
return sid != single[ident] and any(
|
|
245
|
+
prefix == prefixes[ident] and abs(stamp - when) <= _MARGIN_S for prefix, stamp in found)
|
|
246
|
+
|
|
247
|
+
for ident, receiver in single.items():
|
|
248
|
+
when = events[ident]
|
|
249
|
+
for start, mtime_s, exact, older, path, sid, size in unsearched:
|
|
250
|
+
if exact >= ident or not _could_hold(start, mtime_s, when):
|
|
251
|
+
continue
|
|
252
|
+
if when is not None and any(top >= ident and when < seen - _MARGIN_S for seen, top in older):
|
|
253
|
+
continue # only lines written well after the event are unread
|
|
254
|
+
if second_delivery(path, size, sid, ident, when):
|
|
255
|
+
break
|
|
256
|
+
else:
|
|
257
|
+
out[ident] = receiver
|
|
258
|
+
return out
|
|
259
|
+
except Exception:
|
|
260
|
+
return {}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Find a session-specific counterfactual auto-compaction threshold.
|
|
2
|
+
|
|
3
|
+
``resolve(model, largest)`` (optional) returns the user's effective compaction
|
|
4
|
+
settings for a model as ``{"tokens", "model_window"}`` (env >
|
|
5
|
+
modelSettings.autoCompactWindow > autoCompactWindow > model default, see
|
|
6
|
+
_measure/audit._resolve_compact_window). Without it, a context-size heuristic
|
|
7
|
+
stands in: 1M window when the session passed 200K, else 200K.
|
|
8
|
+
"""
|
|
9
|
+
import json
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _scan(path, prompt_tokens):
|
|
13
|
+
observed = []
|
|
14
|
+
largest = 0
|
|
15
|
+
model = None
|
|
16
|
+
with open(path, encoding="utf-8", errors="replace") as stream:
|
|
17
|
+
for line in stream:
|
|
18
|
+
try:
|
|
19
|
+
record = json.loads(line)
|
|
20
|
+
except (ValueError, TypeError):
|
|
21
|
+
continue
|
|
22
|
+
if not isinstance(record, dict) or record.get("isSidechain"):
|
|
23
|
+
continue
|
|
24
|
+
meta = record.get("compactMetadata")
|
|
25
|
+
if (record.get("type") == "system" and record.get("subtype") == "compact_boundary"
|
|
26
|
+
and isinstance(meta, dict) and meta.get("trigger") == "auto"):
|
|
27
|
+
value = meta.get("preTokens")
|
|
28
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool) and value > 0:
|
|
29
|
+
observed.append(value)
|
|
30
|
+
elif record.get("type") == "assistant":
|
|
31
|
+
message = record.get("message")
|
|
32
|
+
usage = message.get("usage") if isinstance(message, dict) else None
|
|
33
|
+
if isinstance(usage, dict):
|
|
34
|
+
largest = max(largest, prompt_tokens(usage))
|
|
35
|
+
model = message.get("model") or model
|
|
36
|
+
return observed, largest, model
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _resolved(largest, model, resolve, key):
|
|
40
|
+
if resolve is not None:
|
|
41
|
+
try:
|
|
42
|
+
value = (resolve(model, largest) or {}).get(key)
|
|
43
|
+
if isinstance(value, (int, float)) and value > 0:
|
|
44
|
+
return int(value)
|
|
45
|
+
except Exception:
|
|
46
|
+
pass
|
|
47
|
+
return 967000 if largest > 200000 else 167000
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def threshold(path, prompt_tokens, resolve=None):
|
|
51
|
+
try:
|
|
52
|
+
observed, largest, model = _scan(path, prompt_tokens)
|
|
53
|
+
except OSError:
|
|
54
|
+
return None, None
|
|
55
|
+
if observed:
|
|
56
|
+
return min(observed), "observed_auto"
|
|
57
|
+
return _resolved(largest, model, resolve, "tokens"), "fallback"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def window_limit(path, prompt_tokens, resolve=None):
|
|
61
|
+
"""Hard ceiling: the session model's context window, ignoring observed compactions."""
|
|
62
|
+
try:
|
|
63
|
+
_observed, largest, model = _scan(path, prompt_tokens)
|
|
64
|
+
except OSError:
|
|
65
|
+
return None
|
|
66
|
+
return _resolved(largest, model, resolve, "model_window")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def window_for(context_tokens, model=None, resolve=None):
|
|
70
|
+
"""Context-window ceiling for a session that reached ``context_tokens``."""
|
|
71
|
+
return _resolved(int(context_tokens or 0), model, resolve, "model_window")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def compaction_window(context_tokens, model=None, resolve=None):
|
|
75
|
+
"""The user's effective auto-compaction point for a session's model."""
|
|
76
|
+
return _resolved(int(context_tokens or 0), model, resolve, "tokens")
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Reap old candidates belonging to the two root-level lease locks."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
import stat
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
_NAME = re.compile(r"^\.\.(?:archive-cleanup\.lease|cohort_tripwire\.lock\.lease)\.candidate-[0-9a-f]{32}$")
|
|
9
|
+
_AGE = 24 * 60 * 60
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def owner_is_gone(pid):
|
|
13
|
+
"""Treat an unknown liveness result as alive, including on Windows."""
|
|
14
|
+
if pid <= 0:
|
|
15
|
+
return False
|
|
16
|
+
if os.name == "nt":
|
|
17
|
+
try:
|
|
18
|
+
import ctypes
|
|
19
|
+
from ctypes import wintypes
|
|
20
|
+
kernel = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
21
|
+
kernel.OpenProcess.restype = wintypes.HANDLE
|
|
22
|
+
kernel.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD)
|
|
23
|
+
kernel.GetExitCodeProcess.argtypes = (wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD))
|
|
24
|
+
kernel.GetExitCodeProcess.restype = wintypes.BOOL
|
|
25
|
+
kernel.CloseHandle.argtypes = (wintypes.HANDLE,)
|
|
26
|
+
kernel.CloseHandle.restype = wintypes.BOOL
|
|
27
|
+
handle = kernel.OpenProcess(0x1000, False, pid)
|
|
28
|
+
if not handle:
|
|
29
|
+
return ctypes.get_last_error() == 87
|
|
30
|
+
try:
|
|
31
|
+
code = wintypes.DWORD()
|
|
32
|
+
if not kernel.GetExitCodeProcess(handle, ctypes.byref(code)):
|
|
33
|
+
return False
|
|
34
|
+
return code.value != 259
|
|
35
|
+
finally:
|
|
36
|
+
kernel.CloseHandle(handle)
|
|
37
|
+
except Exception:
|
|
38
|
+
return False
|
|
39
|
+
try:
|
|
40
|
+
os.kill(pid, 0)
|
|
41
|
+
except ProcessLookupError:
|
|
42
|
+
return True
|
|
43
|
+
except OSError:
|
|
44
|
+
pass
|
|
45
|
+
return False
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def sweep(directory, now=None, max_files=2000):
|
|
49
|
+
cutoff = (time.time() if now is None else now) - _AGE
|
|
50
|
+
removed = 0
|
|
51
|
+
try:
|
|
52
|
+
with os.scandir(directory) as entries:
|
|
53
|
+
for index, entry in enumerate(entries):
|
|
54
|
+
if index >= max_files:
|
|
55
|
+
break
|
|
56
|
+
if not _NAME.fullmatch(entry.name):
|
|
57
|
+
continue
|
|
58
|
+
try:
|
|
59
|
+
info = entry.stat(follow_symlinks=False)
|
|
60
|
+
if not stat.S_ISREG(info.st_mode) or info.st_mtime >= cutoff:
|
|
61
|
+
continue
|
|
62
|
+
# A long-paused owner still needs its candidate to release.
|
|
63
|
+
try:
|
|
64
|
+
with open(entry.path, encoding="utf-8") as f:
|
|
65
|
+
owner = json.loads(f.read(4096))
|
|
66
|
+
pid = int(owner.get("pid", 0))
|
|
67
|
+
if pid > 0 and not owner_is_gone(pid):
|
|
68
|
+
continue
|
|
69
|
+
except OSError:
|
|
70
|
+
continue
|
|
71
|
+
except (ValueError, TypeError, AttributeError):
|
|
72
|
+
pass
|
|
73
|
+
current = entry.stat(follow_symlinks=False)
|
|
74
|
+
if not os.path.samestat(info, current) or current.st_mtime != info.st_mtime:
|
|
75
|
+
continue
|
|
76
|
+
os.unlink(entry.path)
|
|
77
|
+
removed += 1
|
|
78
|
+
except OSError:
|
|
79
|
+
continue
|
|
80
|
+
except OSError:
|
|
81
|
+
pass
|
|
82
|
+
return removed
|