Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions tests/test_tokenly.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,16 @@ def test_totals_and_cost(self):
self.assertEqual(m["codex:gpt-6.1-sol"][:4], [1_000_000, 1_000_000, 2_000_000, 0])
self.assertAlmostEqual(m["codex:gpt-6.1-sol"][4], 12.2)

def test_untouched_logs_are_skipped(self):
# A file last written before the period cannot hold an entry from it, so it is not read at all.
old = os.path.join(self.tmp.name, "claude", "projects", "p", "old.jsonl")
write(old, [{"timestamp": NOW, "requestId": "r9", "cwd": "/x/proj-a", "message": {
"id": "m9", "model": "claude-opus-5-5", "usage": {"input_tokens": 7, "output_tokens": 0}}}])
three_days_ago = datetime.now(timezone.utc).timestamp() - 3 * 86400
os.utime(old, (three_days_ago, three_days_ago))
self.assertEqual(sum(r[0] for r in tokenly.collect(1).groups["day"].values()), 2_000_000) # the fixture: 1M Claude + 1M Codex input
self.assertEqual(sum(r[0] for r in tokenly.collect(30).groups["day"].values()), 2_000_007)

def test_providers(self):
p = tokenly.collect(30).groups["provider"]
self.assertEqual(sorted(p), ["Anthropic", "OpenAI"])
Expand Down
11 changes: 9 additions & 2 deletions tokenly.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,13 @@ def codex_glob():
return os.path.join(home, "sessions", "**", "*.jsonl")


def recent(pattern, since):
"""Log files written since `since`. An older file cannot hold a newer entry, and skipping it is what
keeps a one-day report from reading every log on the machine."""
cutoff = datetime.fromisoformat(since).timestamp()
return [f for f in glob.glob(pattern, recursive=True) if os.path.getmtime(f) >= cutoff]


def read_jsonl(path):
with open(path, errors="ignore") as fh:
for ln in fh:
Expand Down Expand Up @@ -129,7 +136,7 @@ def add(self, ts, model, project, i, o, cr, cw, cw1h=0):
def scan_claude(t):
# Assistant messages carry usage; the same message can be logged several times.
seen = set()
for f in glob.glob(claude_glob(), recursive=True):
for f in recent(claude_glob(), t.since):
for d in read_jsonl(f):
m = d.get("message")
u = m.get("usage") if isinstance(m, dict) else None
Expand All @@ -148,7 +155,7 @@ def scan_claude(t):

def scan_codex(t):
# last_token_usage input includes both cache reads and cache writes.
for f in glob.glob(codex_glob(), recursive=True):
for f in recent(codex_glob(), t.since):
model, project = "codex:?", ""
for d in read_jsonl(f):
p = d.get("payload") or {}
Expand Down
Loading