tokensafe 2.6.0 → 2.7.0

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.
@@ -15,6 +15,7 @@ import os
15
15
  import sys
16
16
  import json
17
17
  import time
18
+ import secrets
18
19
  import sqlite3
19
20
  import threading
20
21
  import subprocess
@@ -165,53 +166,6 @@ class TelemetrySync:
165
166
  state = cls.get_state()
166
167
  last_id = 0 if force else state.get("last_synced_event_id", 0)
167
168
 
168
- try:
169
- conn = sqlite3.connect(METRICS_DB_PATH)
170
- conn.row_factory = sqlite3.Row
171
- cur = conn.cursor()
172
-
173
- synthetic_events: List[Dict[str, Any]] = []
174
- if not state.get("lifetime_rollup_synced", False):
175
- try:
176
- life_row = cur.execute("SELECT * FROM lifetime_aggregates WHERE id = 1").fetchone()
177
- if life_row and life_row["total_saved_tokens"] > 0:
178
- synthetic_events.append({
179
- "event_type": "ROLLUP_LIFETIME",
180
- "original_tokens": int(life_row["total_original_tokens"]),
181
- "saved_tokens": int(life_row["total_saved_tokens"]),
182
- "usd_saved": float(life_row["total_usd_saved"]),
183
- "model": "aggregate",
184
- "timestamp": int(time.time()),
185
- # Rolled-up historical mass of mixed provenance: conservatively estimated.
186
- "measurement": "estimated"
187
- })
188
- except Exception:
189
- pass
190
-
191
- # The measurement column may be absent on legacy databases that have
192
- # not yet been migrated by MetricsTracker._init_db; fall back to the
193
- # event-type map so sync never blocks on schema drift.
194
- try:
195
- rows = cur.execute(
196
- "SELECT id, timestamp, event_type, original_tokens, saved_tokens, est_usd_saved, details, measurement "
197
- "FROM events WHERE id > ? ORDER BY id ASC LIMIT 2000",
198
- (last_id,)
199
- ).fetchall()
200
- except sqlite3.OperationalError:
201
- rows = cur.execute(
202
- "SELECT id, timestamp, event_type, original_tokens, saved_tokens, est_usd_saved, details, "
203
- "NULL as measurement "
204
- "FROM events WHERE id > ? ORDER BY id ASC LIMIT 2000",
205
- (last_id,)
206
- ).fetchall()
207
- conn.close()
208
- except Exception as e:
209
- return {
210
- "success": False,
211
- "synced_events": 0,
212
- "error": f"Failed to read local metrics database: {str(e)}"
213
- }
214
-
215
169
  try:
216
170
  from src.metrics import MetricsTracker
217
171
  local_monthly_measured = MetricsTracker(db_path=METRICS_DB_PATH).get_monthly_saved_tokens(measured_only=True)
@@ -219,64 +173,13 @@ class TelemetrySync:
219
173
  local_monthly_measured = 0
220
174
  machine_fp = "" if os.environ.get("TOKENSAFE_TELEMETRY_DISABLED") in ("1", "true", "yes") else LicenseManager.get_machine_fingerprint()
221
175
 
222
- if not rows and not synthetic_events:
223
- last_q_sync = float(state.get("last_quota_sync_at", 0) or 0)
224
- if not (machine_fp and active_key == "community" and (time.time() - last_q_sync > 3600)):
225
- return {
226
- "success": True,
227
- "synced_events": 0,
228
- "total_synced": state.get("total_synced_events", 0),
229
- "message": "All metrics are already up to date."
230
- }
231
- formatted_items = [(None, None)] # quota-only probe for community tier
232
- else:
233
- formatted_items = [
234
- (None, ev) for ev in synthetic_events
235
- ]
236
- current_last_id = last_id
237
-
238
- for r in rows:
239
- ev_id = int(r["id"])
240
- raw_ts = r["timestamp"]
241
- ts_int = int(time.time())
242
- if isinstance(raw_ts, (int, float)):
243
- ts_int = int(raw_ts)
244
- elif isinstance(raw_ts, str) and raw_ts.strip():
245
- try:
246
- ts_int = int(float(raw_ts.strip()))
247
- except ValueError:
248
- try:
249
- clean_iso = raw_ts.strip().replace("Z", "+00:00")
250
- dt = datetime.fromisoformat(clean_iso)
251
- ts_int = int(dt.timestamp())
252
- except Exception:
253
- ts_int = int(time.time())
254
-
255
- model_name = os.environ.get("AGY_MODEL") or os.environ.get("MODEL") or "gemini-3.8-flash"
256
- if r["details"]:
257
- try:
258
- det = json.loads(r["details"]) if isinstance(r["details"], str) else r["details"]
259
- if isinstance(det, dict) and det.get("model"):
260
- model_name = str(det["model"])
261
- except Exception:
262
- pass
263
-
264
- formatted_items.append((ev_id, {
265
- "event_type": str(r["event_type"] or "PROMPT"),
266
- "original_tokens": int(r["original_tokens"] or 0),
267
- "saved_tokens": int(r["saved_tokens"] or 0),
268
- "usd_saved": float(r["est_usd_saved"] or 0.0),
269
- "model": model_name,
270
- "timestamp": ts_int,
271
- "measurement": resolve_measurement(str(r["event_type"] or "PROMPT"), r["measurement"])
272
- }))
273
-
274
176
  total_sent = 0
275
177
  cumulative_synced = state.get("total_synced_events", 0)
276
178
  rollup_synced = bool(state.get("lifetime_rollup_synced", False))
179
+ current_last_id = last_id
277
180
  headers = {
278
181
  "Content-Type": "application/json",
279
- "User-Agent": "TokenSafe-Sync/2.6.0"
182
+ "User-Agent": "TokenSafe-Sync/2.7.0"
280
183
  }
281
184
  if active_key:
282
185
  headers["Authorization"] = f"Bearer {active_key}"
@@ -296,54 +199,163 @@ class TelemetrySync:
296
199
  "error": err_msg
297
200
  }
298
201
 
299
- for i in range(0, len(formatted_items), batch_size):
300
- batch_items = formatted_items[i:i + batch_size]
301
- chunk = [item[1] for item in batch_items if item[1] is not None]
302
- body_dict = {
303
- "email": target_email,
304
- "license_key": active_key,
305
- "events": chunk,
306
- }
307
- if machine_fp and active_key == "community":
308
- body_dict["machine_id"] = machine_fp
309
- body_dict["monthly_measured_saved"] = local_monthly_measured
310
- body_bytes = json.dumps(body_dict).encode("utf-8")
311
-
312
- req = urllib.request.Request(target_url, data=body_bytes, headers=headers, method="POST")
202
+ page_limit = 2000
203
+ max_pages = 25
204
+ for page_idx in range(max_pages):
313
205
  try:
314
- with urllib.request.urlopen(req, timeout=timeout) as resp:
315
- if resp.status == 200:
206
+ conn = sqlite3.connect(METRICS_DB_PATH)
207
+ conn.row_factory = sqlite3.Row
208
+ cur = conn.cursor()
209
+
210
+ synthetic_events: List[Dict[str, Any]] = []
211
+ if page_idx == 0 and not rollup_synced:
212
+ try:
213
+ life_row = cur.execute("SELECT * FROM lifetime_aggregates WHERE id = 1").fetchone()
214
+ if life_row and life_row["total_saved_tokens"] > 0:
215
+ synthetic_events.append({
216
+ "event_type": "ROLLUP_LIFETIME",
217
+ "original_tokens": int(life_row["total_original_tokens"]),
218
+ "saved_tokens": int(life_row["total_saved_tokens"]),
219
+ "usd_saved": float(life_row["total_usd_saved"]),
220
+ "model": "aggregate",
221
+ "timestamp": int(time.time()),
222
+ # Rolled-up historical mass of mixed provenance: conservatively estimated.
223
+ "measurement": "estimated"
224
+ })
225
+ except Exception:
226
+ pass
227
+
228
+ # The measurement column may be absent on legacy databases that have
229
+ # not yet been migrated by MetricsTracker._init_db; fall back to the
230
+ # event-type map so sync never blocks on schema drift.
231
+ try:
232
+ rows = cur.execute(
233
+ "SELECT id, timestamp, event_type, original_tokens, saved_tokens, est_usd_saved, details, measurement "
234
+ "FROM events WHERE id > ? ORDER BY id ASC LIMIT ?",
235
+ (current_last_id, page_limit)
236
+ ).fetchall()
237
+ except sqlite3.OperationalError:
238
+ rows = cur.execute(
239
+ "SELECT id, timestamp, event_type, original_tokens, saved_tokens, est_usd_saved, details, "
240
+ "NULL as measurement "
241
+ "FROM events WHERE id > ? ORDER BY id ASC LIMIT ?",
242
+ (current_last_id, page_limit)
243
+ ).fetchall()
244
+ conn.close()
245
+ except Exception as e:
246
+ if total_sent > 0:
247
+ return _record_failure(f"Failed to read local metrics database: {str(e)}")
248
+ return {
249
+ "success": False,
250
+ "synced_events": 0,
251
+ "error": f"Failed to read local metrics database: {str(e)}"
252
+ }
253
+
254
+ if not rows and not synthetic_events:
255
+ if page_idx == 0:
256
+ last_q_sync = float(state.get("last_quota_sync_at", 0) or 0)
257
+ if not (machine_fp and active_key == "community" and (time.time() - last_q_sync > 3600)):
258
+ return {
259
+ "success": True,
260
+ "synced_events": 0,
261
+ "total_synced": cumulative_synced,
262
+ "message": "All metrics are already up to date."
263
+ }
264
+ formatted_items = [(None, None)] # quota-only probe for community tier
265
+ else:
266
+ break
267
+ else:
268
+ formatted_items = [
269
+ (None, ev) for ev in synthetic_events
270
+ ]
271
+
272
+ for r in rows:
273
+ ev_id = int(r["id"])
274
+ raw_ts = r["timestamp"]
275
+ ts_int = int(time.time())
276
+ if isinstance(raw_ts, (int, float)):
277
+ ts_int = int(raw_ts)
278
+ elif isinstance(raw_ts, str) and raw_ts.strip():
279
+ try:
280
+ ts_int = int(float(raw_ts.strip()))
281
+ except ValueError:
316
282
  try:
317
- resp_body = json.loads(resp.read().decode("utf-8") or "{}")
318
- srv_measured = int(resp_body.get("server_monthly_measured_saved") or 0)
319
- if srv_measured > 0:
320
- from src.metrics import MetricsTracker
321
- MetricsTracker(db_path=METRICS_DB_PATH).record_server_quota_floor(srv_measured)
283
+ clean_iso = raw_ts.strip().replace("Z", "+00:00")
284
+ dt = datetime.fromisoformat(clean_iso)
285
+ ts_int = int(dt.timestamp())
322
286
  except Exception:
323
- pass
324
- total_sent += len(chunk)
325
- cumulative_synced += len(chunk)
326
- for ev_id, ev_payload in batch_items:
327
- if ev_id is not None and ev_id > current_last_id:
328
- current_last_id = ev_id
329
- if ev_payload and ev_payload.get("event_type") == "ROLLUP_LIFETIME":
287
+ ts_int = int(time.time())
288
+
289
+ model_name = os.environ.get("AGY_MODEL") or os.environ.get("MODEL") or "gemini-3.8-flash"
290
+ if r["details"]:
291
+ try:
292
+ det = json.loads(r["details"]) if isinstance(r["details"], str) else r["details"]
293
+ if isinstance(det, dict) and det.get("model"):
294
+ model_name = str(det["model"])
295
+ except Exception:
296
+ pass
297
+
298
+ formatted_items.append((ev_id, {
299
+ "event_type": str(r["event_type"] or "PROMPT"),
300
+ "original_tokens": int(r["original_tokens"] or 0),
301
+ "saved_tokens": int(r["saved_tokens"] or 0),
302
+ "usd_saved": float(r["est_usd_saved"] or 0.0),
303
+ "model": model_name,
304
+ "timestamp": ts_int,
305
+ "measurement": resolve_measurement(str(r["event_type"] or "PROMPT"), r["measurement"])
306
+ }))
307
+
308
+ for i in range(0, len(formatted_items), batch_size):
309
+ batch_items = formatted_items[i:i + batch_size]
310
+ chunk = [item[1] for item in batch_items if item[1] is not None]
311
+ body_dict = {
312
+ "email": target_email,
313
+ "license_key": active_key,
314
+ "events": chunk,
315
+ }
316
+ if machine_fp and active_key == "community":
317
+ body_dict["machine_id"] = machine_fp
318
+ body_dict["monthly_measured_saved"] = local_monthly_measured
319
+ body_bytes = json.dumps(body_dict).encode("utf-8")
320
+
321
+ req = urllib.request.Request(target_url, data=body_bytes, headers=headers, method="POST")
322
+ try:
323
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
324
+ if resp.status == 200:
325
+ try:
326
+ resp_body = json.loads(resp.read().decode("utf-8") or "{}")
327
+ srv_measured = int(resp_body.get("server_monthly_measured_saved") or 0)
328
+ if srv_measured > 0:
329
+ from src.metrics import MetricsTracker
330
+ MetricsTracker(db_path=METRICS_DB_PATH).record_server_quota_floor(srv_measured)
331
+ except Exception:
332
+ pass
333
+ total_sent += len(chunk)
334
+ cumulative_synced += len(chunk)
335
+ for ev_id, ev_payload in batch_items:
336
+ if ev_id is not None and ev_id > current_last_id:
337
+ current_last_id = ev_id
338
+ if ev_payload and ev_payload.get("event_type") == "ROLLUP_LIFETIME":
339
+ rollup_synced = True
340
+ if not synthetic_events:
330
341
  rollup_synced = True
331
- if not synthetic_events:
332
- rollup_synced = True
333
- cls.save_state({
334
- "last_synced_event_id": current_last_id,
335
- "last_synced_at": int(time.time()),
336
- "last_attempt_at": int(time.time()),
337
- "last_quota_sync_at": int(time.time()),
338
- "total_synced_events": cumulative_synced,
339
- "lifetime_rollup_synced": rollup_synced
340
- })
341
- else:
342
- return _record_failure(f"Server returned HTTP {resp.status}")
343
- except urllib.error.HTTPError as he:
344
- return _record_failure(f"Cloud API error: {he.code} {he.reason}")
345
- except Exception as ex:
346
- return _record_failure(f"Network error during sync: {str(ex)}")
342
+ cls.save_state({
343
+ "last_synced_event_id": current_last_id,
344
+ "last_synced_at": int(time.time()),
345
+ "last_attempt_at": int(time.time()),
346
+ "last_quota_sync_at": int(time.time()),
347
+ "total_synced_events": cumulative_synced,
348
+ "lifetime_rollup_synced": rollup_synced
349
+ })
350
+ else:
351
+ return _record_failure(f"Server returned HTTP {resp.status}")
352
+ except urllib.error.HTTPError as he:
353
+ return _record_failure(f"Cloud API error: {he.code} {he.reason}")
354
+ except Exception as ex:
355
+ return _record_failure(f"Network error during sync: {str(ex)}")
356
+
357
+ if len(rows) < page_limit:
358
+ break
347
359
 
348
360
  return {
349
361
  "success": True,
@@ -352,11 +364,48 @@ class TelemetrySync:
352
364
  "message": f"Successfully synchronized {total_sent:,} events to TokenSafe Cloud."
353
365
  }
354
366
 
367
+ @staticmethod
368
+ def _is_pid_alive(pid: int) -> bool:
369
+ if pid <= 0:
370
+ return False
371
+ try:
372
+ os.kill(pid, 0)
373
+ return True
374
+ except (OSError, ProcessLookupError):
375
+ return False
376
+
355
377
  @classmethod
356
- def sync_background(cls, throttle_seconds: float = 60.0, force: bool = False):
378
+ def _lock_is_active(cls, raw_content: str, allow_legacy_self: bool = False) -> bool:
379
+ """Interprets .sync.lock contents (`spawn:<token>:<ts>`, `worker:<pid>`, or legacy `<pid>`)."""
380
+ text = (raw_content or "").strip()
381
+ if not text:
382
+ return False
383
+ if text.startswith("spawn:"):
384
+ parts = text.split(":")
385
+ try:
386
+ claimed_at = float(parts[2])
387
+ except (IndexError, ValueError):
388
+ return False
389
+ return (time.time() - claimed_at) < 15.0
390
+ if text.startswith("worker:"):
391
+ try:
392
+ pid = int(text.split(":", 1)[1])
393
+ except ValueError:
394
+ return False
395
+ return cls._is_pid_alive(pid)
396
+ try:
397
+ pid = int(text)
398
+ except ValueError:
399
+ return False
400
+ if not allow_legacy_self and pid == os.getpid():
401
+ return False
402
+ return cls._is_pid_alive(pid)
403
+
404
+ @classmethod
405
+ def sync_background(cls, throttle_seconds: float = 20.0, force: bool = False):
357
406
  """
358
407
  Spawns a detached, non-blocking background OS process to sync metrics.
359
- Throttled to run at most once every `throttle_seconds` (default: 60s)
408
+ Throttled to run at most once every `throttle_seconds` (default: 20s)
360
409
  using persistent state from sync_state.json.
361
410
  Detached from parent process group so it survives the termination of short-lived CLI lifecycle hooks.
362
411
  """
@@ -372,30 +421,35 @@ class TelemetrySync:
372
421
  if status.get("pending_events", 0) == 0:
373
422
  return
374
423
 
375
- # Prevent overlapping sync runs via PID lock file.
376
- # Atomic O_EXCL claim closes the check-then-write race where two hook
377
- # processes could both pass the liveness check and spawn duplicate syncs.
424
+ os.makedirs(DATA_DIR, exist_ok=True)
425
+ # Claim a short-lived spawn handoff token atomically so concurrent hooks
426
+ # don't spawn duplicate workers, while the spawned child replaces the
427
+ # lock with its own `worker:<pid>` instead of deadlocking on parent PID.
428
+ claim_token = secrets.token_hex(8)
429
+ spawn_marker = f"spawn:{claim_token}:{now:.3f}"
378
430
  lock_claimed = False
379
431
  for _ in range(2):
380
432
  try:
381
433
  fd = os.open(SYNC_LOCK_PATH, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
382
- os.write(fd, str(os.getpid()).encode("utf-8"))
383
- os.close(fd)
434
+ try:
435
+ os.write(fd, spawn_marker.encode("utf-8"))
436
+ finally:
437
+ os.close(fd)
384
438
  lock_claimed = True
385
439
  break
386
440
  except FileExistsError:
387
441
  try:
388
442
  with open(SYNC_LOCK_PATH, "r", encoding="utf-8") as f:
389
- pid = int(f.read().strip())
390
- # Check if PID is still alive
391
- os.kill(pid, 0)
392
- return # an active sync owns the lock
393
- except (ValueError, OSError, ProcessLookupError):
394
- # Stale lock from a dead process: reclaim it once
395
- try:
396
- os.unlink(SYNC_LOCK_PATH)
397
- except OSError:
443
+ existing = f.read()
444
+ if cls._lock_is_active(existing, allow_legacy_self=False):
398
445
  return
446
+ except OSError:
447
+ return
448
+ # Stale spawn/dead-worker/legacy-self lock: reclaim it once
449
+ try:
450
+ os.unlink(SYNC_LOCK_PATH)
451
+ except OSError:
452
+ return
399
453
  if not lock_claimed:
400
454
  return
401
455
 
@@ -405,7 +459,7 @@ class TelemetrySync:
405
459
  flags = subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.DETACHED_PROCESS
406
460
  script_path = os.path.abspath(__file__)
407
461
  subprocess.Popen(
408
- [sys.executable, script_path, "--background"],
462
+ [sys.executable, script_path, "--background", f"--claim-token={claim_token}"],
409
463
  cwd=PROJECT_ROOT,
410
464
  stdout=subprocess.DEVNULL,
411
465
  stderr=subprocess.DEVNULL,
@@ -414,41 +468,80 @@ class TelemetrySync:
414
468
  creationflags=flags
415
469
  )
416
470
  except Exception:
417
- pass
471
+ try:
472
+ with open(SYNC_LOCK_PATH, "r", encoding="utf-8") as f:
473
+ if f.read().strip() == spawn_marker:
474
+ os.unlink(SYNC_LOCK_PATH)
475
+ except OSError:
476
+ pass
418
477
 
419
478
 
420
- if __name__ == "__main__":
421
- is_bg = "--background" in sys.argv
422
- os.makedirs(DATA_DIR, exist_ok=True)
423
- # Claim the lock atomically; if another live process owns it, exit without syncing.
424
- try:
425
- fd = os.open(SYNC_LOCK_PATH, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
426
- os.write(fd, str(os.getpid()).encode("utf-8"))
427
- os.close(fd)
428
- except FileExistsError:
479
+ def _claim_worker_lock(claim_token: str) -> bool:
480
+ """Claims or takes over .sync.lock for the current sync worker process."""
481
+ worker_marker = f"worker:{os.getpid()}"
482
+ for _ in range(2):
429
483
  try:
430
- with open(SYNC_LOCK_PATH, "r", encoding="utf-8") as f:
431
- pid = int(f.read().strip())
432
- os.kill(pid, 0)
433
- sys.exit(0) # live owner is syncing already
434
- except (ValueError, OSError, ProcessLookupError):
484
+ fd = os.open(SYNC_LOCK_PATH, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
435
485
  try:
436
- os.unlink(SYNC_LOCK_PATH)
486
+ os.write(fd, worker_marker.encode("utf-8"))
487
+ finally:
488
+ os.close(fd)
489
+ return True
490
+ except FileExistsError:
491
+ try:
492
+ with open(SYNC_LOCK_PATH, "r", encoding="utf-8") as f:
493
+ existing = f.read().strip()
437
494
  except OSError:
438
- sys.exit(0)
495
+ return False
496
+
497
+ if claim_token and existing.startswith(f"spawn:{claim_token}:"):
498
+ tmp_path = f"{SYNC_LOCK_PATH}.{os.getpid()}.tmp"
499
+ try:
500
+ fd = os.open(tmp_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
501
+ try:
502
+ os.write(fd, worker_marker.encode("utf-8"))
503
+ finally:
504
+ os.close(fd)
505
+ os.replace(tmp_path, SYNC_LOCK_PATH)
506
+ return True
507
+ except OSError:
508
+ try:
509
+ if os.path.exists(tmp_path):
510
+ os.unlink(tmp_path)
511
+ except OSError:
512
+ pass
513
+ return False
514
+
515
+ if TelemetrySync._lock_is_active(existing, allow_legacy_self=True):
516
+ return False
517
+
439
518
  try:
440
- fd = os.open(SYNC_LOCK_PATH, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
441
- os.write(fd, str(os.getpid()).encode("utf-8"))
442
- os.close(fd)
443
- except FileExistsError:
444
- sys.exit(0)
519
+ os.unlink(SYNC_LOCK_PATH)
520
+ except OSError:
521
+ return False
522
+ return False
523
+
524
+
525
+ if __name__ == "__main__":
526
+ is_bg = "--background" in sys.argv
527
+ claim_token = ""
528
+ for arg in sys.argv[1:]:
529
+ if arg.startswith("--claim-token="):
530
+ claim_token = arg.split("=", 1)[1].strip()
531
+
532
+ os.makedirs(DATA_DIR, exist_ok=True)
533
+ if not _claim_worker_lock(claim_token):
534
+ sys.exit(0)
535
+
536
+ worker_marker = f"worker:{os.getpid()}"
445
537
  try:
446
538
  res = TelemetrySync.sync(timeout=10.0, verbose=not is_bg)
447
539
  if not is_bg:
448
540
  print(json.dumps(res, indent=2))
449
541
  finally:
450
542
  try:
451
- if os.path.exists(SYNC_LOCK_PATH):
452
- os.remove(SYNC_LOCK_PATH)
543
+ with open(SYNC_LOCK_PATH, "r", encoding="utf-8") as f:
544
+ if f.read().strip() == worker_marker:
545
+ os.remove(SYNC_LOCK_PATH)
453
546
  except Exception:
454
547
  pass