Files
ai-agent/backend/test_fresh_context.py
gabrielvidalandClaude Opus 5.5 046af22f6e feat(fresh): a compaction's divider shows what it has saved so far
The parser keeps a running tally per /compact (Fresh & send, Auto fresh, or
one typed in a terminal): each call after it, up to the next compaction,
would have replayed the dropped context (preTokens less the first call's
prompt) on top — written again on a turn's first call back to an expired
cache, read otherwise — less the compaction's own cost. Served as
CompactInfo.saved; the divider reads "saved ≈ $28.26 so far" (green) or
"not paid back yet". An automatic compaction shows none.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 13:52:04 +01:00

258 lines
12 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Fresh context (runs/fresh.py): what the parser tells the reply box's nudge
— when the last call was made, the cache TTL it left, a compaction's divider
and cost — and the settings / compact step. ``python -m unittest
test_fresh_context`` from ``backend/``."""
import datetime
import json
import pathlib
import tempfile
import unittest
from conversations.parse import parse_conversation
from runs import fresh
SID = "11111111-2222-3333-4444-555555555555"
class T:
"""A tiny transcript builder."""
def __init__(self):
self.recs, self.n = [], 0
def _ts(self):
self.n += 1
at = datetime.datetime(2026, 10, 30, 10, tzinfo=datetime.timezone.utc) \
+ datetime.timedelta(seconds=self.n)
return at.strftime("%Y-%m-%dT%H:%M:%S.000Z")
def idle(self, seconds):
"""Let the clock run (the gap before the next record)."""
self.n += seconds
return self
def user(self, text, **extra):
self.recs.append({"type": "user", "timestamp": self._ts(), "sessionId": SID,
"message": {"role": "user", "content": text}, **extra})
return self
def reply(self, text, ctx, *, model="claude-opus-5-5", w1h=0, w5m=0):
"""An assistant call replaying ``ctx`` tokens, ``w1h``/``w5m`` of them
written to the cache."""
write = w1h + w5m
self.recs.append({
"type": "assistant", "timestamp": self._ts(), "sessionId": SID,
"requestId": f"r{self.n}",
"message": {"id": f"m{self.n}", "role": "assistant", "model": model,
"content": [{"type": "text", "text": text}],
"usage": {"input_tokens": 10, "output_tokens": 100,
"cache_read_input_tokens": ctx - write - 10,
"cache_creation_input_tokens": write,
"cache_creation": {"ephemeral_1h_input_tokens": w1h,
"ephemeral_5m_input_tokens": w5m}}}})
return self
def cost_state(self, **models):
self.recs.append({"type": "cost-state", "sessionId": SID, "modelUsage": {
m: {"inputTokens": u[0], "outputTokens": u[1], "cacheReadInputTokens": 0,
"cacheCreationInputTokens": 0, "cacheCreationEphemeral5mInputTokens": 0,
"cacheCreationEphemeral1hInputTokens": 0}
for m, u in models.items()}})
return self
def compact(self, pre, post, summary="1. Primary Request: ship it.", trigger="manual"):
self.recs.append({"type": "system", "subtype": "compact_boundary",
"timestamp": self._ts(), "sessionId": SID,
"content": "Conversation compacted",
"compactMetadata": {"trigger": trigger, "preTokens": pre,
"postTokens": post, "durationMs": 26544}})
self.user("This session is being continued from a previous conversation that "
"ran out of context. The summary below covers the earlier portion "
"of the conversation.\n\n<system-reminder>\ntools\n</system-reminder>\n"
f"Summary:\n{summary}", isCompactSummary=True, isVisibleInTranscriptOnly=True)
self.user("<command-name>/compact</command-name>\n<command-message>compact"
"</command-message>")
self.user("<local-command-stdout>Compacted</local-command-stdout>")
return self
def parse(self, full=False):
with tempfile.TemporaryDirectory() as d:
p = pathlib.Path(d) / f"{SID}.jsonl"
p.write_text("\n".join(json.dumps(r) for r in self.recs) + "\n")
return parse_conversation(p, full=full)
class CacheClock(unittest.TestCase):
def test_last_call_and_the_1h_tier(self):
s = T().user("go").reply("a", 60_000, w1h=60_000).reply("b", 61_000).parse()
self.assertEqual(s["lastCallAt"], "2026-10-30T10:00:03.000Z")
self.assertEqual(s["cacheTtl"], 3600)
self.assertEqual(s["contextTokens"], 61_100)
self.assertIsNone(s["compactions"])
def test_the_5m_tier(self):
s = T().user("go").reply("a", 60_000, w5m=60_000).parse()
self.assertEqual(s["cacheTtl"], 300)
def test_no_write_no_ttl(self):
self.assertIsNone(T().user("go").reply("a", 60_000).parse()["cacheTtl"])
class Compaction(unittest.TestCase):
def convo(self):
return (T().user("go").reply("a", 50_000, w1h=50_000).reply("b", 190_000)
.cost_state(**{"claude-opus-5-5": (20, 200), "claude-haiku-5-5": (1000, 10)})
.compact(190_000, 16_000)
# the compaction's own Haiku call, which only the CLI's tally shows
.cost_state(**{"claude-opus-5-5": (20, 200),
"claude-haiku-5-5": (1000 + 190_000, 10 + 8_000)}))
def test_divider_with_summary_not_a_turn(self):
s = self.convo().parse(full=True)
items = [i for i in s["thread"] if i.get("kind") == "compact"]
self.assertEqual(len(items), 1)
it = items[0]
self.assertEqual(it["compact"], {"trigger": "manual", "preTokens": 190_000,
"postTokens": 16_000, "durationMs": 26544})
self.assertEqual(it["text"], "1. Primary Request: ship it.")
self.assertEqual(s["userTurns"], 1)
self.assertFalse(any(i.get("kind") == "text" and "continued" in (i.get("text") or "")
for i in s["thread"]))
self.assertEqual(s["compactions"], 1)
def test_context_is_what_the_next_call_replays(self):
s = self.convo().parse()
self.assertEqual(s["contextTokens"], s["firstContextTokens"] + 16_000)
self.assertEqual(s["contextModel"], "claude-opus-5-5")
def test_the_compaction_call_is_charged(self):
s = self.convo().parse(full=True)
it = next(i for i in s["thread"] if i.get("kind") == "compact")
self.assertEqual(it["model"], "claude-haiku-5-5")
# Haiku 5.5 over 100K bills 5×: 190K in at $0.50/M + 8K out at $2.50/M.
self.assertAlmostEqual(it["turnCost"], 0.19 * 0.5 + 0.008 * 2.5, places=6)
self.assertEqual(it["turnBucket"], "context")
self.assertAlmostEqual(sum(i.get("turnCost") or 0 for i in s["thread"]), s["cost"])
self.assertGreaterEqual(s["byTool"]["context"]["cost"], it["turnCost"])
# The divider's running saving. Opus 5.5: write $8/M (1 h tier), read
# $0.20/M; the compaction (Haiku, 190K in, 8K out) costs $0.115.
COMPACTION = 0.19 * 0.5 + 0.008 * 2.5
def fresh_after(self, idle):
return (T().user("go").reply("a", 50_000, w1h=50_000).reply("b", 190_000)
.cost_state(**{"claude-opus-5-5": (20, 200), "claude-haiku-5-5": (1000, 10)})
.idle(idle).compact(190_000, 16_000)
.cost_state(**{"claude-opus-5-5": (20, 200),
"claude-haiku-5-5": (1000 + 190_000, 10 + 8_000)})
.user("next").reply("c", 60_000, w1h=36_000).reply("d", 62_000))
def saved(self, s):
return next(i for i in s["thread"] if i.get("kind") == "compact")["compact"].get("saved")
def test_a_fresh_reply_on_an_expired_cache_saves_the_rewrite(self):
s = self.fresh_after(2 * 3600).parse(full=True)
# 190K − 60K = 130K not written again on the first call, not read on the second.
self.assertAlmostEqual(self.saved(s), 130_000 * (8 + 0.2) / 1e6 - self.COMPACTION,
places=4)
def test_a_compaction_on_a_warm_cache_saves_only_reads(self):
s = self.fresh_after(60).parse(full=True)
self.assertAlmostEqual(self.saved(s), 2 * 130_000 * 0.2 / 1e6 - self.COMPACTION,
places=4)
self.assertLess(self.saved(s), 0) # "not paid back yet"
def test_a_later_cold_turn_counts_again_until_the_next_compaction(self):
t = (self.fresh_after(2 * 3600).idle(3 * 3600).user("later").reply("e", 64_000)
.compact(64_000, 9_000, trigger="auto").reply("f", 40_000))
s = t.parse(full=True)
self.assertAlmostEqual(self.saved(s), 130_000 * (8 + 0.2 + 8) / 1e6 - self.COMPACTION,
places=4)
def test_no_saving_without_a_call_or_on_an_auto_compaction(self):
self.assertIsNone(self.saved(self.convo().parse(full=True)))
t = (T().user("go").reply("a", 190_000, w1h=190_000)
.compact(190_000, 16_000, trigger="auto").reply("b", 60_000))
self.assertIsNone(self.saved(t.parse(full=True)))
def test_an_auto_compaction_mid_run_is_not_guessed(self):
# A turn ran between the boundary and the tally: the tally's growth
# is that turn's (already priced), not the compaction's.
s = (T().user("go").reply("a", 50_000, w1h=50_000)
.cost_state(**{"claude-opus-5-5": (10, 100)})
.compact(190_000, 16_000).reply("c", 70_000, w1h=70_000)
.cost_state(**{"claude-opus-5-5": (20, 200)}).parse(full=True))
it = next(i for i in s["thread"] if i.get("kind") == "compact")
self.assertNotIn("turnCost", it)
def test_calls_since_the_last_tally_are_not_charged_twice(self):
# The run before the compaction was killed: no tally of its own, so
# the next one also counts its (transcript-priced) call.
s = (T().user("go").cost_state(**{"claude-opus-5-5": (0, 0)})
.reply("a", 50_010, w1h=50_000)
.compact(50_000, 5_000)
.cost_state(**{"claude-opus-5-5": (10, 100),
"claude-haiku-5-5": (50_000, 4_000)}).parse(full=True))
it = next(i for i in s["thread"] if i.get("kind") == "compact")
self.assertEqual(it["model"], "claude-haiku-5-5")
self.assertAlmostEqual(it["turnCost"], 0.05 * 0.1 + 0.004 * 0.5, places=6)
class Settings(unittest.TestCase):
def test_store_validates_and_persists(self):
with tempfile.TemporaryDirectory() as d:
path = pathlib.Path(d) / "fresh-context.json"
st = fresh.FreshContextStore(str(path))
self.assertEqual(st.get(), fresh.DEFAULTS)
st.set({"coldUsd": 2, "model": "own", "minSavingsPct": 30.4})
again = fresh.FreshContextStore(str(path)).get()
self.assertEqual((again["coldUsd"], again["model"], again["minSavingsPct"]),
(2.0, "own", 30))
for bad in ({"coldUsd": -1}, {"model": "gpt"},
{"confirm": "yes"}, {"minSavingsPct": 120},
{"minSavingsUsd": True}):
with self.assertRaises(ValueError):
st.set(bad)
def test_auto_fresh_is_the_owners_own_and_off_by_default(self):
with tempfile.TemporaryDirectory() as d:
path = pathlib.Path(d) / "fresh-context.json"
st = fresh.FreshContextStore(str(path))
self.assertIs(st.get()["autoFresh"], False)
st.set({"autoFresh": True})
self.assertIs(fresh.FreshContextStore(str(path)).get()["autoFresh"], True)
with self.assertRaises(ValueError):
st.set({"autoFresh": "on"})
def test_retired_keys_in_the_file_are_dropped(self):
with tempfile.TemporaryDirectory() as d:
path = pathlib.Path(d) / "fresh-context.json"
path.write_text('{"calls": "mean", "heavyTokens": 600000, "minSavingsUsd": 1}')
got = fresh.FreshContextStore(str(path)).get()
self.assertNotIn("calls", got)
self.assertNotIn("heavyTokens", got)
self.assertEqual(got["minSavingsUsd"], 1.0)
def test_scenarios_cover_every_follow_up(self):
sc = fresh.ASSUMPTIONS["scenarios"]
self.assertAlmostEqual(sum(s["share"] for s in sc), 1.0)
for a, b in zip(sc, sc[1:]):
self.assertEqual(a["maxCalls"] + 1, b["minCalls"])
self.assertTrue(a["minCalls"] <= a["calls"] <= a["maxCalls"])
self.assertIsNone(sc[-1]["maxCalls"])
def test_compact_spec(self):
spec = fresh.compact_spec(fresh.DEFAULTS, SID, "claude-opus-5-5")
self.assertEqual(spec["model"], "haiku")
self.assertIn("every user message verbatim", spec["instructions"])
self.assertIn(f"{SID}.jsonl", spec["instructions"])
own = fresh.compact_spec({**fresh.DEFAULTS, "model": "own", "pointer": False},
SID, "claude-opus-5-5")
self.assertEqual(own["model"], "claude-opus-5-5")
self.assertNotIn(SID, own["instructions"])
if __name__ == "__main__":
unittest.main()