fix(shadow_report): window is days, not seconds #117

Merged
alee merged 3 commits from fix/shadow-report-window into main 2026-10-18 03:24:21 +00:00
2 changed files with 90 additions and 10 deletions

View File

@@ -19,14 +19,14 @@ def run_report(db_path: str, days: int):
sys.exit(1) sys.exit(1)
# Window filter - use AND so it can be appended after an existing WHERE # Window filter - use AND so it can be appended after an existing WHERE
where_clause = "AND julianday(observed_at) >= julianday('now') - ? / 86400.0" where_clause = "AND julianday(observed_at) >= julianday('now') - ?"
params = (days,) params = (days,)
# Empty table guard # Empty table guard
try: try:
has_rows = conn.execute( has_rows = conn.execute(
"SELECT 1 FROM classifier_shadow " "SELECT 1 FROM classifier_shadow "
"WHERE julianday(observed_at) >= julianday('now') - ? / 86400.0 " "WHERE julianday(observed_at) >= julianday('now') - ? "
"LIMIT 1", params "LIMIT 1", params
).fetchone() ).fetchone()
except sqlite3.OperationalError as e: except sqlite3.OperationalError as e:
@@ -51,7 +51,7 @@ def run_report(db_path: str, days: int):
shadow_count = conn.execute( shadow_count = conn.execute(
"SELECT COUNT(*) as n FROM classifier_shadow " "SELECT COUNT(*) as n FROM classifier_shadow "
"WHERE julianday(observed_at) >= julianday('now') - ? / 86400.0", "WHERE julianday(observed_at) >= julianday('now') - ?",
params, params,
).fetchone()["n"] ).fetchone()["n"]
@@ -60,7 +60,7 @@ def run_report(db_path: str, days: int):
SELECT COUNT(DISTINCT s.decision_id) as n SELECT COUNT(DISTINCT s.decision_id) as n
FROM classifier_shadow s FROM classifier_shadow s
JOIN route_decisions d ON s.decision_id = d.id JOIN route_decisions d ON s.decision_id = d.id
WHERE d.kind = 'chat' AND julianday(s.observed_at) >= julianday('now') - ? / 86400.0 WHERE d.kind = 'chat' AND julianday(s.observed_at) >= julianday('now') - ?
""", params """, params
).fetchone()["n"] ).fetchone()["n"]
@@ -130,7 +130,7 @@ def run_report(db_path: str, days: int):
JOIN route_decisions d ON s.decision_id = d.id JOIN route_decisions d ON s.decision_id = d.id
WHERE s.abstained = 0 WHERE s.abstained = 0
AND d.classification_source = 'classifier' AND d.classification_source = 'classifier'
AND julianday(s.observed_at) >= julianday('now') - ? / 86400.0 AND julianday(s.observed_at) >= julianday('now') - ?
""", params """, params
).fetchall() ).fetchall()
@@ -162,7 +162,7 @@ def run_report(db_path: str, days: int):
FROM classifier_shadow s FROM classifier_shadow s
JOIN route_decisions d ON s.decision_id = d.id JOIN route_decisions d ON s.decision_id = d.id
WHERE d.classification_source IN ('session_history', 'fallback') WHERE d.classification_source IN ('session_history', 'fallback')
AND julianday(s.observed_at) >= julianday('now') - ? / 86400.0 AND julianday(s.observed_at) >= julianday('now') - ?
""", params """, params
).fetchall() ).fetchall()
@@ -194,7 +194,7 @@ def run_report(db_path: str, days: int):
JOIN route_decisions d ON s.decision_id = d.id JOIN route_decisions d ON s.decision_id = d.id
JOIN verifications v ON d.request_id = v.request_id JOIN verifications v ON d.request_id = v.request_id
WHERE v.kind = 'client_outcome' WHERE v.kind = 'client_outcome'
AND julianday(s.observed_at) >= julianday('now') - ? / 86400.0 AND julianday(s.observed_at) >= julianday('now') - ?
""", params """, params
).fetchall() ).fetchall()
@@ -231,7 +231,7 @@ def run_report(db_path: str, days: int):
r["confidence"] r["confidence"]
for r in conn.execute( for r in conn.execute(
"SELECT confidence FROM classifier_shadow " "SELECT confidence FROM classifier_shadow "
"WHERE julianday(observed_at) >= julianday('now') - ? / 86400.0", "WHERE julianday(observed_at) >= julianday('now') - ?",
params, params,
) )
if r["confidence"] is not None if r["confidence"] is not None
@@ -256,7 +256,7 @@ def run_report(db_path: str, days: int):
SUM(CASE WHEN s.task_category = d.task_category THEN 1 ELSE 0 END) as matches SUM(CASE WHEN s.task_category = d.task_category THEN 1 ELSE 0 END) as matches
FROM classifier_shadow s FROM classifier_shadow s
JOIN route_decisions d ON s.decision_id = d.id JOIN route_decisions d ON s.decision_id = d.id
WHERE s.abstained = 0 AND {cond} AND julianday(s.observed_at) >= julianday('now') - ? / 86400.0 WHERE s.abstained = 0 AND {cond} AND julianday(s.observed_at) >= julianday('now') - ?
""", params """, params
).fetchone() ).fetchone()
if res and res["total"] > 0: if res and res["total"] > 0:
@@ -267,7 +267,7 @@ def run_report(db_path: str, days: int):
# Sessions stats # Sessions stats
sess_data = conn.execute( sess_data = conn.execute(
"SELECT session_key, COUNT(*) as n FROM classifier_shadow " "SELECT session_key, COUNT(*) as n FROM classifier_shadow "
"WHERE julianday(observed_at) >= julianday('now') - ? / 86400.0 " "WHERE julianday(observed_at) >= julianday('now') - ? "
"GROUP BY session_key", params "GROUP BY session_key", params
).fetchall() ).fetchall()
if sess_data: if sess_data:

View File

@@ -17,6 +17,7 @@ import json
import sqlite3 import sqlite3
import sys import sys
from datetime import datetime, timezone from datetime import datetime, timezone
from datetime import timedelta
from pathlib import Path from pathlib import Path
import pytest import pytest
@@ -801,3 +802,82 @@ def test_chat_flag_on_schedules_shadow_task(tmp_path, monkeypatch):
assert len(calls) == 1 assert len(calls) == 1
assert calls[0][0] is not None assert calls[0][0] is not None
assert isinstance(calls[0][0], int) assert isinstance(calls[0][0], int)
# ---------------------------------------------------------------------------
# 17. shadow_report.run_report honours the --days window
# ---------------------------------------------------------------------------
def _write_shadow_row(conn, observed_at, decision_id=1, **extra):
"""Insert a classifier_shadow row.
observed_at is a timedelta offset from now (e.g. timedelta(hours=2)).
"""
ts = (datetime.now(timezone.utc) - observed_at).isoformat()
conn.execute(
"""
INSERT INTO classifier_shadow (
decision_id, session_key, labeler, task_category,
confidence, abstained, reject_reason, latency_ms, observed_at
) VALUES (?, 'sess-x', 'local_encoder', 'coding_refactor',
0.9, 0, NULL, 50, ?)
""",
(decision_id, ts),
)
conn.commit()
def _route_decision(conn, id_, offset, **extra):
"""Insert a route_decision row at ``now - offset``.
*offset* is a ``datetime.timedelta`` (e.g. ``timedelta(hours=2)``).
"""
ts = (datetime.now(timezone.utc) - offset).isoformat()
conn.execute(
"""
INSERT INTO route_decisions (
id, observed_at, kind, task_category, task_tier,
required_context_tokens, confidence, classifier_ms,
classification_source, selected_model, selected_provider
) VALUES (?, ?, 'chat', 'coding_refactor', 2,
500, 0.9, 100, 'classifier', 'mock-1', 'neuralwatt')
""",
(id_, ts),
)
def test_report_days_window_2h_row_with_days_1(db_path, capsys):
"""A row observed 2 hours ago is counted when days=1."""
conn = sqlite3.connect(str(db_path))
_route_decision(conn, 1, timedelta(hours=2))
_write_shadow_row(conn, timedelta(hours=2))
conn.close()
try:
shadow_report.run_report(str(db_path), 1)
except SystemExit:
pass
captured = capsys.readouterr()
assert "Shadow rows: 1" in captured.out
def test_report_days_window_3d_row_excluded_days_1_included_days_7(db_path, capsys):
"""A row 3 days ago is excluded with days=1 but included with days=7."""
conn = sqlite3.connect(str(db_path))
_route_decision(conn, 1, timedelta(days=3))
_route_decision(conn, 2, timedelta(seconds=0))
_write_shadow_row(conn, timedelta(days=3), decision_id=1)
_write_shadow_row(conn, timedelta(seconds=0), decision_id=2)
conn.close()
try:
shadow_report.run_report(str(db_path), 1)
except SystemExit:
pass
assert "Shadow rows: 1" in capsys.readouterr().out
try:
shadow_report.run_report(str(db_path), 7)
except SystemExit:
pass
assert "Shadow rows: 2" in capsys.readouterr().out