tokensafe 4.15.0 → 4.16.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.
@@ -375,6 +375,133 @@ class LicenseManager:
375
375
  except Exception:
376
376
  pass
377
377
 
378
+ # --- Quota aggregate cache -------------------------------------------
379
+ # check_quota() runs on every hook invocation and reads a 30-day SQL
380
+ # aggregate plus the sidecar ledger. The aggregate is cached for a few
381
+ # seconds only while usage is in the lower half of the limit, and every
382
+ # recorded measured saving drops the entry, so a cap crossing is never
383
+ # delayed by the TTL.
384
+ _QUOTA_CACHE_KEEP = 4
385
+
386
+ @staticmethod
387
+ def _quota_cache_ttl() -> float:
388
+ try:
389
+ return max(0.0, float(os.environ.get("TOKENSAFE_QUOTA_CACHE_TTL", "60")))
390
+ except (TypeError, ValueError):
391
+ return 60.0
392
+
393
+ @classmethod
394
+ def _quota_cache_path(cls) -> str:
395
+ try:
396
+ return os.path.join(resolve_data_dir(), "quota_state.json")
397
+ except Exception:
398
+ return ""
399
+
400
+ @classmethod
401
+ def _read_quota_cache(cls) -> Dict[str, Any]:
402
+ path = cls._quota_cache_path()
403
+ if not path:
404
+ return {}
405
+ try:
406
+ with open(path, "r", encoding="utf-8") as fh:
407
+ data = json.load(fh)
408
+ entries = data.get("entries") if isinstance(data, dict) else None
409
+ return dict(entries) if isinstance(entries, dict) else {}
410
+ except Exception:
411
+ return {}
412
+
413
+ @classmethod
414
+ def _write_quota_cache(cls, slot: str, payload: Dict[str, Any]) -> None:
415
+ path = cls._quota_cache_path()
416
+ if not path:
417
+ return
418
+ try:
419
+ now = time.time()
420
+ entries = {
421
+ key: value
422
+ for key, value in cls._read_quota_cache().items()
423
+ if isinstance(value, dict) and float(value.get("expires", 0)) > now
424
+ }
425
+ entries[slot] = payload
426
+ trimmed = dict(list(entries.items())[-cls._QUOTA_CACHE_KEEP:])
427
+ tmp = f"{path}.tmp.{os.getpid()}"
428
+ with open(tmp, "w", encoding="utf-8") as fh:
429
+ json.dump({"version": 1, "entries": trimmed}, fh)
430
+ os.replace(tmp, path)
431
+ except Exception:
432
+ pass
433
+
434
+ @classmethod
435
+ def _drop_quota_cache(cls, slot: Optional[str] = None) -> None:
436
+ path = cls._quota_cache_path()
437
+ if not path:
438
+ return
439
+ try:
440
+ if slot is None:
441
+ if os.path.exists(path):
442
+ os.unlink(path)
443
+ return
444
+ entries = cls._read_quota_cache()
445
+ if slot not in entries:
446
+ return
447
+ entries.pop(slot, None)
448
+ if not entries:
449
+ os.unlink(path)
450
+ return
451
+ tmp = f"{path}.tmp.{os.getpid()}"
452
+ with open(tmp, "w", encoding="utf-8") as fh:
453
+ json.dump({"version": 1, "entries": entries}, fh)
454
+ os.replace(tmp, path)
455
+ except Exception:
456
+ pass
457
+
458
+ @classmethod
459
+ def note_quota_activity(cls, delta_saved: int) -> None:
460
+ """Drops the cached aggregate after any recorded measured saving.
461
+
462
+ Measured savings are what the quota counts, so a process that records
463
+ them (the MCP server, where the check gates real optimization) must not
464
+ read a figure from before its own write. Estimated events do not count
465
+ against the quota and leave the cache alone — that is the hook path.
466
+ """
467
+ try:
468
+ if int(delta_saved or 0) <= 0 or not cls._quota_cache_ttl():
469
+ return
470
+ cls._drop_quota_cache(None)
471
+ except Exception:
472
+ pass
473
+
474
+ @classmethod
475
+ def _cached_monthly_saved(cls, tracker, max_tokens: int) -> int:
476
+ """30-day measured savings for quota, cached for a few seconds.
477
+
478
+ Only the lower half of the limit is cached: near the cap the aggregate is
479
+ recomputed on every check, so crossing it is never delayed by the TTL.
480
+ """
481
+ ttl = cls._quota_cache_ttl()
482
+ if ttl <= 0:
483
+ return int(tracker.get_monthly_saved_tokens())
484
+ slot = cls._cache_slot("quota:" + str(getattr(tracker, "db_path", "") or ""))
485
+ try:
486
+ now = time.time()
487
+ entry = cls._read_quota_cache().get(slot)
488
+ if isinstance(entry, dict) and float(entry.get("expires", 0)) > now:
489
+ cached = entry.get("local_saved")
490
+ if isinstance(cached, int) and not isinstance(cached, bool) and 0 <= cached < max_tokens * 0.5:
491
+ return cached
492
+ value = int(tracker.get_monthly_saved_tokens())
493
+ if value < max_tokens * 0.5:
494
+ cls._write_quota_cache(slot, {
495
+ "local_saved": value,
496
+ "expires": now + ttl,
497
+ })
498
+ else:
499
+ cls._drop_quota_cache(slot)
500
+ return value
501
+ except Exception:
502
+ cls._drop_quota_cache(slot)
503
+ return int(tracker.get_monthly_saved_tokens())
504
+
378
505
  @classmethod
379
506
  def validate_license(
380
507
  cls,
@@ -789,7 +916,7 @@ class LicenseManager:
789
916
  except Exception:
790
917
  tracker = None
791
918
 
792
- local_saved = tracker.get_monthly_saved_tokens() if tracker else 0
919
+ local_saved = cls._cached_monthly_saved(tracker, max_tokens) if tracker else 0
793
920
  server_floor = cls._get_server_quota_floor(tracker)
794
921
 
795
922
  # Guest state backup floor (scoped to tracker dir when explicit db_path is provided)