@alexgreensh/token-optimizer 5.13.69 → 5.13.71
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 +729 -767
- package/skills/token-optimizer/assets/savings_story.js +765 -0
- package/skills/token-optimizer/pricing/prices.json +1 -0
- package/skills/token-optimizer/references/cli-reference.md +1 -1
- 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 +66 -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 +30 -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 +295 -0
- package/skills/token-optimizer/scripts/_measure/daemon.py +53 -74
- package/skills/token-optimizer/scripts/_measure/dashboard.py +90 -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 +129 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +260 -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 +174 -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 +439 -864
- package/skills/token-optimizer/scripts/_measure/savings_headline.py +130 -0
- 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 +103 -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 +144 -30
- package/skills/token-optimizer/scripts/structural.py +25 -0
- package/skills/token-optimizer/scripts/structure_map.py +4 -26
|
@@ -14,8 +14,7 @@ PRIMARY KEY, legacy rows backfilled by a one-time ``rebuild``). A bounded
|
|
|
14
14
|
|
|
15
15
|
Configuration:
|
|
16
16
|
- WAL mode for concurrent read/write from separate hook processes
|
|
17
|
-
- busy_timeout=50ms:
|
|
18
|
-
accepts dropped writes rather than stalling the hook process)
|
|
17
|
+
- busy_timeout=50ms: bound database waits; tracking events can be queued
|
|
19
18
|
- synchronous=NORMAL (WAL-safe relaxation for performance)
|
|
20
19
|
- 50MB cap per session DB
|
|
21
20
|
- PreToolUse hooks: READ-ONLY queries only
|
|
@@ -28,11 +27,15 @@ import hashlib
|
|
|
28
27
|
import json
|
|
29
28
|
import re
|
|
30
29
|
import sqlite3
|
|
30
|
+
import sys
|
|
31
31
|
import time
|
|
32
32
|
import uuid
|
|
33
|
+
import session_store_guard
|
|
34
|
+
from _measure import session_store_spool
|
|
33
35
|
from pathlib import Path
|
|
34
36
|
from typing import Any, Optional
|
|
35
37
|
|
|
38
|
+
from hint_paths import normalize_hint_path
|
|
36
39
|
from plugin_env import resolve_snapshot_dir
|
|
37
40
|
from reset_epoch import ResetEpochMixin, bump_reset_epoch
|
|
38
41
|
|
|
@@ -69,7 +72,7 @@ CREATE TABLE IF NOT EXISTS file_reads (
|
|
|
69
72
|
last_structure_confidence REAL DEFAULT 0.0,
|
|
70
73
|
last_tool_use_id TEXT DEFAULT ''
|
|
71
74
|
);
|
|
72
|
-
|
|
75
|
+
CREATE INDEX IF NOT EXISTS idx_file_reads_last_access ON file_reads(last_access DESC);
|
|
73
76
|
CREATE TABLE IF NOT EXISTS tool_outputs (
|
|
74
77
|
tool_use_id TEXT PRIMARY KEY,
|
|
75
78
|
tool_name TEXT NOT NULL,
|
|
@@ -130,7 +133,7 @@ CREATE TABLE IF NOT EXISTS context_intel_events (
|
|
|
130
133
|
output_chars INTEGER NOT NULL,
|
|
131
134
|
timestamp REAL NOT NULL
|
|
132
135
|
);
|
|
133
|
-
|
|
136
|
+
CREATE INDEX IF NOT EXISTS idx_intel_timestamp ON context_intel_events(timestamp DESC); CREATE INDEX IF NOT EXISTS idx_intel_tool_use ON context_intel_events(tool_use_id);
|
|
134
137
|
CREATE TABLE IF NOT EXISTS activity_log (
|
|
135
138
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
136
139
|
tool_name TEXT NOT NULL,
|
|
@@ -220,29 +223,25 @@ class SessionStore(ResetEpochMixin):
|
|
|
220
223
|
if self._conn is not None:
|
|
221
224
|
return self._conn
|
|
222
225
|
self._store_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
223
|
-
# Align the connect timeout (seconds) with the PRAGMA busy_timeout (ms)
|
|
224
|
-
# so the schema init AND later writes honor the same lock-wait budget.
|
|
225
226
|
timeout_s = max(0.05, self._busy_timeout_ms / 1000.0)
|
|
226
|
-
self._conn =
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
self._conn.row_factory = sqlite3.Row
|
|
245
|
-
self._init_schema()
|
|
227
|
+
self._conn = session_store_guard.connect(self, timeout_s)
|
|
228
|
+
try:
|
|
229
|
+
self._conn.execute("PRAGMA journal_mode=WAL")
|
|
230
|
+
self._conn.execute(f"PRAGMA busy_timeout={int(self._busy_timeout_ms)}")
|
|
231
|
+
self._conn.execute("PRAGMA synchronous=NORMAL")
|
|
232
|
+
# The DB and its sidecars contain private cached output.
|
|
233
|
+
import os as _os
|
|
234
|
+
for _p in (self.db_path, self.db_path.with_suffix(".db-wal"),
|
|
235
|
+
self.db_path.with_suffix(".db-shm")):
|
|
236
|
+
try:
|
|
237
|
+
_os.chmod(_p, 0o600)
|
|
238
|
+
except OSError:
|
|
239
|
+
pass
|
|
240
|
+
self._conn.row_factory = sqlite3.Row
|
|
241
|
+
self._init_schema()
|
|
242
|
+
except BaseException:
|
|
243
|
+
self.close()
|
|
244
|
+
raise
|
|
246
245
|
return self._conn
|
|
247
246
|
|
|
248
247
|
def _init_schema(self) -> None:
|
|
@@ -268,8 +267,6 @@ class SessionStore(ResetEpochMixin):
|
|
|
268
267
|
# U6/fix-1: probe + setup the external-content FTS5 mirror (LIKE
|
|
269
268
|
# fallback). Backfills legacy rows once, gated on prior_version < 2.
|
|
270
269
|
self._ensure_fts5_index(conn, prior_version)
|
|
271
|
-
# Stamp the current schema version last (INSERT OR REPLACE so the bump
|
|
272
|
-
# actually lands on pre-existing DBs, not just brand-new ones).
|
|
273
270
|
conn.execute(
|
|
274
271
|
"INSERT OR REPLACE INTO session_meta (key, value) VALUES (?, ?)",
|
|
275
272
|
("_schema_version", str(_SCHEMA_VERSION)),
|
|
@@ -510,8 +507,9 @@ class SessionStore(ResetEpochMixin):
|
|
|
510
507
|
try:
|
|
511
508
|
self._conn.close()
|
|
512
509
|
except Exception:
|
|
513
|
-
|
|
510
|
+
return
|
|
514
511
|
self._conn = None
|
|
512
|
+
session_store_guard.release(self)
|
|
515
513
|
|
|
516
514
|
_cap_warned = False
|
|
517
515
|
|
|
@@ -649,32 +647,14 @@ class SessionStore(ResetEpochMixin):
|
|
|
649
647
|
output_text: Optional[str] = None,
|
|
650
648
|
truncated: Optional[int] = None,
|
|
651
649
|
) -> None:
|
|
652
|
-
if self._is_over_size_cap():
|
|
653
|
-
return
|
|
654
650
|
index_text, index_truncated = _bound_tool_output_index(output_text)
|
|
655
|
-
|
|
656
|
-
conn.execute(
|
|
657
|
-
"""INSERT OR IGNORE INTO tool_outputs
|
|
658
|
-
(tool_use_id, tool_name, tool_type, command_or_path,
|
|
659
|
-
output_hash, output_chars, output_tokens_est,
|
|
660
|
-
compressed_preview, timestamp,
|
|
661
|
-
source_file_path, language, archived_from, output_text,
|
|
662
|
-
truncated, index_truncated)
|
|
663
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
664
|
-
""",
|
|
665
|
-
(
|
|
651
|
+
session_store_spool.enqueue(self, {"kind": "tool_output", "values": (
|
|
666
652
|
tool_use_id, tool_name, tool_type, command_or_path,
|
|
667
653
|
output_hash, output_chars, output_tokens_est,
|
|
668
654
|
compressed_preview, time.time(),
|
|
669
655
|
source_file_path, language, archived_from, index_text,
|
|
670
656
|
truncated, index_truncated,
|
|
671
|
-
)
|
|
672
|
-
)
|
|
673
|
-
# fix-1: the external-content FTS mirror is maintained by the AFTER
|
|
674
|
-
# INSERT trigger, which fires only when the INSERT OR IGNORE above
|
|
675
|
-
# actually writes a new row. No manual FTS write here -- that was the
|
|
676
|
-
# source of duplicate FTS rows on re-insert of the same tool_use_id.
|
|
677
|
-
conn.commit()
|
|
657
|
+
)})
|
|
678
658
|
|
|
679
659
|
# ----- tool_outputs search (U6: FTS5 with LIKE fallback) -----
|
|
680
660
|
|
|
@@ -846,7 +826,7 @@ class SessionStore(ResetEpochMixin):
|
|
|
846
826
|
def record_file_edit(self, file_path: str) -> None:
|
|
847
827
|
"""Keep edit evidence without persisting credential-shaped path text."""
|
|
848
828
|
fingerprint = hashlib.sha256(file_path.encode("utf-8")).hexdigest()
|
|
849
|
-
|
|
829
|
+
session_store_spool.enqueue(self, {"kind": "file_edit", "fingerprint": fingerprint})
|
|
850
830
|
|
|
851
831
|
def was_file_edited(self, file_path: str) -> bool:
|
|
852
832
|
fingerprint = hashlib.sha256(file_path.encode("utf-8")).hexdigest()
|
|
@@ -861,16 +841,7 @@ class SessionStore(ResetEpochMixin):
|
|
|
861
841
|
summary: str,
|
|
862
842
|
output_chars: int,
|
|
863
843
|
) -> None:
|
|
864
|
-
|
|
865
|
-
return
|
|
866
|
-
conn = self._connect()
|
|
867
|
-
conn.execute(
|
|
868
|
-
"""INSERT INTO context_intel_events
|
|
869
|
-
(tool_name, tool_use_id, summary, output_chars, timestamp)
|
|
870
|
-
VALUES (?, ?, ?, ?, ?)""",
|
|
871
|
-
(tool_name, tool_use_id, summary, output_chars, time.time()),
|
|
872
|
-
)
|
|
873
|
-
conn.commit()
|
|
844
|
+
session_store_spool.enqueue_intel(self, tool_name, tool_use_id, summary, output_chars)
|
|
874
845
|
|
|
875
846
|
def get_intel_events(self, limit: int = 20) -> list[dict[str, Any]]:
|
|
876
847
|
conn = self._connect()
|
|
@@ -937,26 +908,17 @@ class SessionStore(ResetEpochMixin):
|
|
|
937
908
|
"""Record that a proactive prior-session hint surfaced these files to
|
|
938
909
|
this session. A later read of one of them is observed evidence the hint
|
|
939
910
|
spared an exploratory search (credited once via claim_hint_follow)."""
|
|
940
|
-
paths = [
|
|
911
|
+
paths = [normalize_hint_path(p) for p in (file_paths or []) if str(p or "").strip()]
|
|
941
912
|
if not paths:
|
|
942
913
|
return
|
|
943
|
-
# Defensive cap independent of the call site (which
|
|
944
|
-
# a hint never legitimately surfaces dozens of files, so bound the write.
|
|
914
|
+
# Defensive cap, independent of the call site (which slices to ~5).
|
|
945
915
|
paths = paths[:25]
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
"""INSERT INTO hint_serves (file_path, served_at, credited)
|
|
950
|
-
VALUES (?, ?, 0)
|
|
951
|
-
ON CONFLICT(file_path) DO NOTHING""",
|
|
952
|
-
[(p, now) for p in paths],
|
|
953
|
-
)
|
|
954
|
-
conn.commit()
|
|
916
|
+
epoch = session_store_spool.hint_epoch(self)
|
|
917
|
+
session_store_spool.enqueue(self, {"kind": "hint_serves", "paths": paths, "timestamp": time.time(),
|
|
918
|
+
"reset_epoch": epoch})
|
|
955
919
|
|
|
956
|
-
#
|
|
957
|
-
#
|
|
958
|
-
# coincidence than the hint doing its job -- keeps the avoided-search credit
|
|
959
|
-
# causally honest (and conservative).
|
|
920
|
+
# Credit a follow only within this window of the serve; later reads of the
|
|
921
|
+
# same file are more likely coincidence (keeps the credit conservative).
|
|
960
922
|
HINT_FOLLOW_MAX_AGE_SECONDS = 4 * 60 * 60
|
|
961
923
|
|
|
962
924
|
def claim_hint_follow(self, file_path: str, max_age_seconds: float = HINT_FOLLOW_MAX_AGE_SECONDS) -> bool:
|
|
@@ -972,17 +934,18 @@ class SessionStore(ResetEpochMixin):
|
|
|
972
934
|
return False
|
|
973
935
|
conn = self._connect()
|
|
974
936
|
fresh_after = time.time() - max(0.0, max_age_seconds)
|
|
937
|
+
keys = (normalize_hint_path(file_path), str(file_path)) # raw: pre-normalization rows
|
|
975
938
|
hit = conn.execute(
|
|
976
939
|
"SELECT 1 FROM hint_serves "
|
|
977
|
-
"WHERE file_path
|
|
978
|
-
(
|
|
940
|
+
"WHERE file_path IN (?, ?) AND credited = 0 AND served_at >= ? LIMIT 1",
|
|
941
|
+
(*keys, fresh_after),
|
|
979
942
|
).fetchone()
|
|
980
943
|
if not hit:
|
|
981
944
|
return False
|
|
982
945
|
cur = conn.execute(
|
|
983
946
|
"UPDATE hint_serves SET credited = 1 "
|
|
984
|
-
"WHERE file_path
|
|
985
|
-
(
|
|
947
|
+
"WHERE file_path IN (?, ?) AND credited = 0 AND served_at >= ?",
|
|
948
|
+
(*keys, fresh_after),
|
|
986
949
|
)
|
|
987
950
|
conn.commit()
|
|
988
951
|
return cur.rowcount > 0
|
|
@@ -1024,10 +987,11 @@ def mark_context_reset(session_id: str, snapshot_dir: Optional[Path] = None) ->
|
|
|
1024
987
|
marker = _context_reset_marker(session_id, snapshot_dir)
|
|
1025
988
|
if marker is None:
|
|
1026
989
|
return
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
990
|
+
from _measure import context_reset_marker
|
|
991
|
+
if not context_reset_marker.publish(marker, time.time()):
|
|
992
|
+
print("[Session Store] Context reset marker not updated: lock busy", file=sys.stderr)
|
|
993
|
+
except OSError as exc:
|
|
994
|
+
print("[Session Store] Context reset marker not updated: " + str(exc), file=sys.stderr)
|
|
1031
995
|
|
|
1032
996
|
|
|
1033
997
|
def context_reset_at(session_id: str, snapshot_dir: Optional[Path] = None) -> float:
|
|
@@ -1043,18 +1007,4 @@ def context_reset_at(session_id: str, snapshot_dir: Optional[Path] = None) -> fl
|
|
|
1043
1007
|
|
|
1044
1008
|
def cleanup_old_stores(max_age_hours: int = CLEANUP_AGE_HOURS) -> int:
|
|
1045
1009
|
"""Delete session store DBs older than max_age_hours. Returns count deleted."""
|
|
1046
|
-
|
|
1047
|
-
return 0
|
|
1048
|
-
cutoff = time.time() - (max_age_hours * 3600)
|
|
1049
|
-
deleted = 0
|
|
1050
|
-
for db_file in SESSION_STORE_DIR.glob("*.db"):
|
|
1051
|
-
try:
|
|
1052
|
-
if db_file.stat().st_mtime < cutoff:
|
|
1053
|
-
db_file.unlink()
|
|
1054
|
-
for wal in (db_file.with_suffix(".db-wal"), db_file.with_suffix(".db-shm")):
|
|
1055
|
-
if wal.exists():
|
|
1056
|
-
wal.unlink()
|
|
1057
|
-
deleted += 1
|
|
1058
|
-
except OSError:
|
|
1059
|
-
pass
|
|
1060
|
-
return deleted
|
|
1010
|
+
return session_store_guard.prune_old_stores(SESSION_STORE_DIR, time.time() - max_age_hours * 3600)
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Coordinate session-store connections with age-based cleanup."""
|
|
2
|
+
import errno
|
|
3
|
+
import os
|
|
4
|
+
import sqlite3
|
|
5
|
+
import time
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
import fcntl
|
|
9
|
+
except ImportError:
|
|
10
|
+
fcntl = None
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _open_guard(db_path):
|
|
14
|
+
flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0)
|
|
15
|
+
return os.fdopen(os.open(str(db_path.with_suffix(".db.guard")), flags, 0o600), "r+b")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def connect(store, timeout):
|
|
19
|
+
if fcntl is None:
|
|
20
|
+
return sqlite3.connect(str(store.db_path), timeout=timeout)
|
|
21
|
+
guard = _open_guard(store.db_path)
|
|
22
|
+
try:
|
|
23
|
+
try:
|
|
24
|
+
deadline = time.monotonic() + timeout
|
|
25
|
+
while True:
|
|
26
|
+
try:
|
|
27
|
+
fcntl.flock(guard.fileno(), fcntl.LOCK_SH | fcntl.LOCK_NB)
|
|
28
|
+
break
|
|
29
|
+
except BlockingIOError as exc:
|
|
30
|
+
remaining = deadline - time.monotonic()
|
|
31
|
+
if remaining <= 0:
|
|
32
|
+
raise sqlite3.OperationalError("session store cleanup lock timed out") from exc
|
|
33
|
+
time.sleep(min(0.01, remaining))
|
|
34
|
+
except OSError as exc:
|
|
35
|
+
if exc.errno in (errno.ENOSYS, errno.ENOTSUP, errno.EOPNOTSUPP):
|
|
36
|
+
guard.close()
|
|
37
|
+
return sqlite3.connect(str(store.db_path), timeout=timeout)
|
|
38
|
+
raise
|
|
39
|
+
conn = sqlite3.connect(str(store.db_path), timeout=timeout)
|
|
40
|
+
except BaseException:
|
|
41
|
+
guard.close()
|
|
42
|
+
raise
|
|
43
|
+
store._cleanup_guard = guard
|
|
44
|
+
return conn
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def release(store):
|
|
48
|
+
guard = getattr(store, "_cleanup_guard", None)
|
|
49
|
+
if guard is not None:
|
|
50
|
+
store._cleanup_guard = None
|
|
51
|
+
guard.close()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def prune_old_stores(directory, cutoff):
|
|
55
|
+
# Unsupported platforms retain stores rather than race an active connection.
|
|
56
|
+
if fcntl is None or not directory.exists():
|
|
57
|
+
return 0
|
|
58
|
+
deleted = 0
|
|
59
|
+
for db_path in directory.glob("*.db"):
|
|
60
|
+
try:
|
|
61
|
+
with _open_guard(db_path) as guard:
|
|
62
|
+
try:
|
|
63
|
+
fcntl.flock(guard.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
64
|
+
except BlockingIOError:
|
|
65
|
+
continue
|
|
66
|
+
if db_path.stat().st_mtime >= cutoff or db_path.with_suffix(".db-wal").exists():
|
|
67
|
+
continue
|
|
68
|
+
db_path.unlink()
|
|
69
|
+
shm = db_path.with_suffix(".db-shm")
|
|
70
|
+
if shm.exists():
|
|
71
|
+
shm.unlink()
|
|
72
|
+
deleted += 1
|
|
73
|
+
except OSError:
|
|
74
|
+
continue
|
|
75
|
+
return deleted
|