@alexgreensh/token-optimizer 5.13.76 → 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.
@@ -68,18 +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
- for path in facade.SNAPSHOT_DIR.iterdir():
72
- if not path.name.startswith(('keepwarm-ended-', 'keepwarm-owner-')):
73
- continue
74
- try:
75
- info = path.lstat()
76
- if stat.S_ISREG(info.st_mode) and info.st_mtime < now - 14 * DAY:
77
- path.unlink()
78
- removed += 1
79
- if removed == 200:
80
- break
81
- except OSError:
82
- continue
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
83
88
  return removed
84
89
 
85
90
 
@@ -106,6 +111,52 @@ def _auto_rows(rows):
106
111
  and row.get('action') == 'warm' and row.get('auto') is True]
107
112
 
108
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
+
130
+ def read_ledger(path, *, strict=True):
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):
136
+ rows = []
137
+ try:
138
+ stream = open(path, encoding='utf-8', errors='strict' if strict else 'replace')
139
+ except FileNotFoundError:
140
+ if strict and os.path.islink(path):
141
+ raise
142
+ return []
143
+ with stream:
144
+ for line in stream:
145
+ if not line.strip():
146
+ continue
147
+ try:
148
+ row = json.loads(line)
149
+ except ValueError:
150
+ if strict:
151
+ raise
152
+ continue
153
+ if isinstance(row, dict):
154
+ rows.append(row)
155
+ elif strict:
156
+ raise ValueError('invalid ledger row')
157
+ return rows
158
+
159
+
109
160
  def _attempt_id(row):
110
161
  return row.get('action_id') or row.get('attempt_key') or (row.get('session_id'), row.get('ts'))
111
162
 
@@ -205,7 +256,15 @@ def decide(facade, session_id, context_tokens, idle_seconds, model, lifetime,
205
256
  return stop('meters-unknown')
206
257
  if not math.isfinite(idle_seconds) or idle_seconds < 0:
207
258
  return out
208
- rows = facade._keepwarm_load_ledger_rows() if rows is None else rows
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))
264
+ for row in _auto_rows(rows):
265
+ stamp = float(row['ts'])
266
+ if not math.isfinite(stamp) or stamp > now:
267
+ return stop('accounting-unavailable')
209
268
  out['caps'] = _cap_counts(rows, session_id, now - idle_seconds, now)
210
269
  for key, reason in zip(out['caps'], ('cap-pause', 'cap-session', 'cap-day')):
211
270
  if not out['caps'][key]:
@@ -0,0 +1,220 @@
1
+ """Publish and watch successive pauses in the same terminal session."""
2
+ from contextlib import contextmanager
3
+ import json
4
+ import os
5
+ import sys
6
+ import tempfile
7
+ import time
8
+
9
+
10
+ def _legacy_writer_alive(owner):
11
+ from .lease_candidate_cleanup import owner_is_gone
12
+
13
+ # Holding the OS lock proves an earlier new-protocol lease is orphaned,
14
+ # including after PID reuse. An old process only held the pathname lease.
15
+ if owner.get('expires_wall') == sys.float_info.max or owner.get('released'):
16
+ return False
17
+ pid = owner.get('pid')
18
+ return type(pid) is int and 0 < pid < 2**31 and not owner_is_gone(pid)
19
+
20
+
21
+ def _displaced_legacy_writer(lease):
22
+ # Old releases keep a private candidate until they leave their critical
23
+ # section, even if another old writer took over their expired pathname.
24
+ prefix = '.' + lease.path.name + '.candidate-'
25
+ with os.scandir(lease.path.parent) as entries:
26
+ for entry in entries:
27
+ if (entry.name.startswith(prefix) and entry.name != prefix + lease.nonce
28
+ and entry.is_file(follow_symlinks=False)):
29
+ try:
30
+ with open(entry.path, encoding='utf-8') as stream:
31
+ owner = json.load(stream)
32
+ if isinstance(owner, dict) and _legacy_writer_alive(owner):
33
+ return True
34
+ except FileNotFoundError:
35
+ continue
36
+ except ValueError:
37
+ # A partial candidate cannot yet have been linked as owner.
38
+ continue
39
+ return False
40
+
41
+
42
+ @contextmanager
43
+ def os_lock(path, timeout):
44
+ """One persistent inode. False means busy, None means unusable storage."""
45
+ from hook_provenance import _acquire
46
+ try:
47
+ path.parent.mkdir(parents=True, exist_ok=True)
48
+ fd = _acquire(path, timeout, busy=False, nofollow=True)
49
+ except OSError:
50
+ fd = None
51
+ if fd is None or fd is False:
52
+ yield fd
53
+ return
54
+ try:
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:
72
+ if not held:
73
+ yield held
74
+ return
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))
78
+ with lease as leased:
79
+ try:
80
+ available = leased and not _displaced_legacy_writer(lease)
81
+ except OSError:
82
+ available = None
83
+ yield lease if available else (None if lease.storage_error or available is None else False)
84
+
85
+
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')
89
+
90
+
91
+ def publish_exclusive(path, content):
92
+ """Readers see the complete record or no pathname. Never replace a claimant."""
93
+ fd, temporary = tempfile.mkstemp(prefix='.keepwarm-publish-', dir=path.parent)
94
+ try:
95
+ with os.fdopen(fd, 'w', encoding='utf-8') as stream:
96
+ stream.write(content)
97
+ os.link(temporary, path)
98
+ finally:
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.
104
+
105
+
106
+ def _commit_arm(facade, record):
107
+ """Caller holds the writer lock. Duplicate Stops share their ping history."""
108
+ from . import keepwarm_safety
109
+ from .mod_action_booking import _append
110
+
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'):
113
+ continue
114
+ if keepwarm_safety.same_pause(existing, record):
115
+ if 'terminal_turn' not in record or 'terminal_turn' in existing:
116
+ return existing
117
+ record = {**existing, 'terminal_turn': record['terminal_turn']}
118
+ break
119
+ _append(facade._keepwarm_sidecar_path(), record)
120
+ return record
121
+
122
+
123
+ def _publish_stop(facade, record, path, now):
124
+ from .keepwarm_auto import CACHE_LIFETIME
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
140
+
141
+
142
+ def publish_arm(facade, record):
143
+ facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
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)
155
+
156
+
157
+ def recover_pending(facade, now):
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
165
+ try:
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)
181
+ except (OSError, KeyError, ValueError, TypeError):
182
+ continue
183
+
184
+
185
+ def latest_terminal_arms(facade):
186
+ # Proof for a previous pause can be appended after the next Stop.
187
+ latest = {}
188
+ for record in facade.load_keepwarm_records():
189
+ sid = record['session_id']
190
+ if record.get('owner') and (sid not in latest or float(record['ts']) >= float(latest[sid]['ts'])):
191
+ latest[sid] = record
192
+ return latest
193
+
194
+
195
+ def watch_terminal(facade, sid, fd, watch_delay):
196
+ """Yield to a new worker or pick up its arm if it already saw our lock."""
197
+ try:
198
+ if not facade._keepwarm_valid_arg(sid):
199
+ return 1
200
+ os.fstat(fd)
201
+ while True:
202
+ record = latest_terminal_arms(facade).get(sid)
203
+ delay = watch_delay(facade, record, fd)
204
+ if delay is not None:
205
+ if delay:
206
+ facade.time.sleep(delay)
207
+ continue
208
+ if os.name != 'posix':
209
+ return 0
210
+ import fcntl
211
+ fcntl.flock(fd, fcntl.LOCK_UN)
212
+ latest = latest_terminal_arms(facade).get(sid)
213
+ if not latest or latest == record:
214
+ return 0
215
+ try:
216
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
217
+ except BlockingIOError:
218
+ return 0
219
+ finally:
220
+ os.close(fd)