@alexgreensh/token-optimizer 5.13.77 → 5.13.79

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,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
- for path in facade.SNAPSHOT_DIR.iterdir():
72
- if (path.name.startswith('keepwarm-owner-watch-')
73
- or not path.name.startswith(('keepwarm-ended-', 'keepwarm-owner-'))):
74
- continue
75
- try:
76
- info = path.lstat()
77
- if stat.S_ISREG(info.st_mode) and info.st_mtime < now - 14 * DAY:
78
- path.unlink()
79
- removed += 1
80
- if removed == 200:
81
- break
82
- except OSError:
83
- 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
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
- rows = read_ledger(facade._keepwarm_ledger_path()) 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))
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 writer_lock(facade, timeout):
69
- """True while locked, False on contention, None on a storage error."""
70
- path = facade.SNAPSHOT_DIR / facade._KEEPWARM_LOCK_NAME
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 = os.open(str(path), flags, 0o600)
48
+ fd = _acquire(path, timeout, busy=False, nofollow=True)
75
49
  except OSError:
76
- yield None
50
+ fd = None
51
+ if fd is None or fd is False:
52
+ yield fd
77
53
  return
78
54
  try:
79
- until = time.monotonic() + timeout
80
- try:
81
- held = _acquire_writer(fd, timeout)
82
- except (OSError, ImportError):
83
- held = None
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
- # Older processes only know the lease. Wait for their live writer,
88
- # even after expiry. Their clock-based reclaimer must also leave our
89
- # lease alone until we release it. The next writer recovers a dead PID.
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 available
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
- @contextmanager
108
- def arm_lock(facade, transcript, turn, expires=None):
109
- """A detached Stop can retry a busy writer while its own pause is current."""
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
- os.unlink(temporary)
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['owner']:
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,97 @@ def _commit_arm(facade, record):
152
120
  return record
153
121
 
154
122
 
155
- def publish_arm(facade, record, transcript, turn):
156
- from .keepwarm_auto import CACHE_LIFETIME
157
- from .keepwarm_safety import terminal_turn
123
+ def _publish_stop(facade, record, path, now):
124
+ from .keepwarm_safety import session_ended, terminal_turn
158
125
 
159
- pending = None
160
- expires = record['last_turn_ts'] + CACHE_LIFETIME
126
+ result = None
127
+ # Spending checks cache expiry against proved pings. Only expire the pause itself here.
128
+ if now - record['ts'] <= facade._KEEPWARM_MAX_AGE_SECONDS:
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, retry=None):
161
143
  facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
162
- if turn is not None:
163
- pending = facade.SNAPSHOT_DIR / ('keepwarm-pending-stop-' + os.urandom(16).hex())
164
- publish_exclusive(pending, json.dumps(record, allow_nan=False))
165
- with arm_lock(facade, transcript, turn, expires) as held:
166
- if not held:
167
- return None
168
- current = turn is None or terminal_turn(transcript) == turn
169
- result = _commit_arm(facade, record) if current else None
170
- if pending:
171
- pending.unlink(missing_ok=True)
172
- return result
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
+ if held is False and pending is not None and retry is not None:
156
+ retry.append((record, pending))
173
157
 
174
158
 
175
- def recover_pending(facade, now):
176
- """Retry a detached worker's Stop even if it exited waiting for storage."""
177
- from .keepwarm_auto import CACHE_LIFETIME
159
+ def retry_due_stop(facade, record, path):
160
+ from .keepwarm_auto import BUCKETS
161
+
162
+ if facade.time.time() - record['last_turn_ts'] >= BUCKETS[0]:
163
+ # Fresh pauses can wait for the scheduler. A due one may have less
164
+ # than a minute left, so let this worker claim it as the writer exits.
165
+ with state_lock(facade.SNAPSHOT_DIR, 60) as held:
166
+ if held:
167
+ return _publish_stop(facade, record, path, facade.time.time())
168
+
178
169
 
179
- for path in facade.SNAPSHOT_DIR.glob('keepwarm-pending-stop-*'):
180
- with facade._keepwarm_lock() as held:
181
- if not held:
182
- return
170
+ def _import_legacy(facade, now):
171
+ from codex_io import atomic_write_json
172
+ from .mod_action_booking import _append
173
+
174
+ directory = facade.SNAPSHOT_DIR
175
+ marker = directory / '.kw2-imported'
176
+ try:
177
+ previous = {} if marker.is_symlink() else json.loads(marker.read_bytes())
178
+ except (FileNotFoundError, ValueError):
179
+ previous = {} # 5.13.78 left an empty marker.
180
+ stamps = {}
181
+ with os.scandir(directory) as entries:
182
+ for entry in entries:
183
+ legacy = entry.name == 'keepwarm_state.jsonl' or entry.name.startswith('keepwarm-pending-stop-')
184
+ if legacy and entry.is_file(follow_symlinks=False):
185
+ st = entry.stat(follow_symlinks=False)
186
+ stamps[entry.name] = [st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns]
187
+ if stamps == previous:
188
+ return
189
+ imported = {(r['session_id'], r['ts']) for r in facade.load_keepwarm_records(strict=True)}
190
+ for name, stamp in stamps.items():
191
+ if not isinstance(previous, dict) or stamp != previous.get(name):
192
+ rows = {(r['session_id'], r['ts']): r for r in facade.load_keepwarm_records(directory / name, strict=True)}
193
+ for key, row in rows.items():
194
+ if key not in imported and now - float(row['ts']) <= facade._KEEPWARM_MAX_AGE_SECONDS:
195
+ _append(facade._keepwarm_sidecar_path(), row)
196
+ imported.add(key)
197
+ atomic_write_json(marker, stamps, replace_symlink=True)
198
+
199
+
200
+ def recover_pending(facade, now):
201
+ with facade._keepwarm_lock() as held:
202
+ if not held:
203
+ return
204
+ try:
205
+ _import_legacy(facade, now)
206
+ except OSError:
207
+ pass # Retry migration independently of current Stops.
208
+ for path in facade.SNAPSHOT_DIR.glob('kw2-stop-*'):
183
209
  try:
184
- if path.is_symlink():
185
- continue
186
- record = json.loads(path.read_text(encoding='utf-8'))
187
- if (facade._valid_keepwarm_record(record) and record.get('terminal_turn')
188
- and now < record['last_turn_ts'] + CACHE_LIFETIME
189
- and facade.classify_keepwarm_record(record, now=now) == 'still_paused'):
190
- _commit_arm(facade, record)
191
- path.unlink(missing_ok=True)
210
+ if not path.is_symlink():
211
+ row = json.loads(path.read_bytes())
212
+ if facade._valid_keepwarm_record(row):
213
+ _publish_stop(facade, row, path, now)
192
214
  except (OSError, KeyError, ValueError, TypeError):
193
215
  continue
194
216