From 8ddc05b801af01ed8f4765a24f45b2997bbd9c66 Mon Sep 17 00:00:00 2001 From: kshitijk4poor <82637225+kshitijk4poor@users.noreply.github.com> Date: Sun, 19 Jul 2026 13:12:10 +0530 Subject: [PATCH] perf(compression): skip durable refresh for in-memory-only blocks The ineffective-compression counter is not durable; when it is the sole reason the gate is blocked there is nothing in the DB that could unblock it, so re-reading the guard rows on every gate check for the rest of the session is pure waste. Guard test pins the no-DB-touch behavior. --- agent/context_compressor.py | 10 ++++++++++ .../agent/test_compression_rotation_state.py | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/agent/context_compressor.py b/agent/context_compressor.py index 490cb1b51fd..951002e963f 100644 --- a/agent/context_compressor.py +++ b/agent/context_compressor.py @@ -1593,6 +1593,16 @@ class ContextCompressor(ContextEngine): # and re-evaluate so a stale local block cannot outlive the durable # state that justified it. The unblocked hot path above never pays # for the DB reads. + if ( + self._summary_failure_cooldown_until <= time.monotonic() + and self._fallback_compression_streak < 2 + ): + # Blocked solely by the in-memory ineffective-compression + # counter, which is not durable — there is nothing in the DB + # that could unblock it, so skip the refresh (otherwise this + # branch would re-read the DB on every gate check for the rest + # of the session). + return True self._refresh_durable_guards() return self._automatic_compression_blocked_locally() diff --git a/tests/agent/test_compression_rotation_state.py b/tests/agent/test_compression_rotation_state.py index 7eb46afb09c..039686b758d 100644 --- a/tests/agent/test_compression_rotation_state.py +++ b/tests/agent/test_compression_rotation_state.py @@ -577,3 +577,22 @@ class TestCooldownPersistFailureIsNotAClearedRow: db.clear_compression_failure_cooldown(session_id) assert compressor.get_active_compression_failure_cooldown(refresh=True) is None assert compressor._summary_failure_cooldown_until == 0.0 + + def test_ineffective_count_only_block_skips_durable_refresh( + self, + refresh_state_db: SessionDB, + ): + """A block owed solely to the in-memory ineffective counter (which is + not durable) must not re-read the DB on every gate check.""" + db = refresh_state_db + session_id = "INEFFECTIVE_ONLY_BLOCK" + db.create_session(session_id, source="telegram") + compressor = _bound_context_compressor(db, session_id) + compressor._ineffective_compression_count = 2 + + with patch.object( + compressor, + "_refresh_durable_guards", + side_effect=AssertionError("nothing durable to refresh"), + ): + assert compressor._automatic_compression_blocked() is True