DeepTutor icon indicating copy to clipboard operation
DeepTutor copied to clipboard

[Bug]: Mastery sessions resend unbounded context (up to 573k prompt tokens/turn) after repeated condensation failures, draining provider balance

Open Marling2024 opened this issue 4 weeks ago • 3 comments

Do you need to file an issue?

  • [x] I have searched the existing issues and this bug is not already filed.
  • [x] I believe this is a legitimate bug, not just a question or feature request.

Describe the bug

Long mastery-path sessions can resend an unbounded conversation history to the model. Every turn starts with a call whose prompt_tokens is larger than the previous one, up to 573,715 tokens in a single request — 4.4× the MAX_HISTORY_PLAN_TOKENS = 131_072 budget in deeptutor/services/session/context_builder.py. The provider balance was exhausted mid-session (HTTP 402), and the app then retried the failing calls four more times.

Two things appear to compound:

  1. Context condensation keeps failing. context_builder.py catches the summarizer error and logs Context condensation failed (ValueError); bounding recent history without advancing its watermark. Because the watermark is not advanced (context_builder.py:772-785), the next turn re-selects the same unsummarized prefix and retries the same failing summarization. On 2026-11-06 this warning fired 26 times in one session (14:00–16:38 local); the database shows 214 occurrences since 10-24.

  2. The per-request fallback does not actually bound the request. After a failed summarize the code trims retained_groups only while len(retained_groups) > 1 (context_builder.py:787-792), so a single oversized group is kept verbatim regardless of the budget. In addition, the mastery prompt assembler / previous-turn replay path may not be measured by _model_tokens at all. We cannot tell from the logs which of the two paths produced the 573k request because the warning intentionally hides the exception message.

The user-visible symptom is a drained provider balance: 1,382 calls / 41,988,796 prompt tokens accumulated in 15 days, of which 15,890,129 prompt tokens came from one 2h20m session.

Steps to reproduce

  1. Configure a mastery-path session with a model whose detected context_window is large (here: deepseek-flash, context_window = 1048576, context_window_source = metadata).
  2. Run a mastery session with many turns and large tool results (we did 26 turns of a math mastery path; 14:18–16:38).
  3. Watch a session accumulate a stale compressed_summary / failing condensation. The condition is observable from the log line Context condensation failed (...); bounding recent history without advancing its watermark.
  4. Each subsequent turn's first LLM call grows monotonically: 24,337 → 191,708 → 401,969 → 474,154 → 497,213 → 521,601 → 540,794 → 573,715.
  5. Inspect data/user/usage.sqlite3 table llm_calls; the prompt_tokens column shows the growth, and the calls eventually fail with HTTP 402 Insufficient Balance.

Minimal analysis snippet (no credentials required, read-only):

import sqlite3, json
con = sqlite3.connect("file:data/user/usage.sqlite3?mode=ro", uri=True)
for ts, sess, turn, uj in con.execute(
        "SELECT started_at, session_id, turn_id, usage_json FROM llm_calls ORDER BY started_at"):
    u = json.loads(uj)
    if (u.get("prompt_tokens") or 0) >= 300_000:
        print(ts, u["prompt_tokens"], u["model"], u["status"], sess)

Expected Behavior

  • The input of any single model request should be bounded by the configured history budget (here 131,072 tokens), regardless of session length.
  • A failed condensation should not cause the next turn to resend the same unsummarized material; either the watermark advances on a deterministic fallback or the failure surfaces to the user.
  • Terminal provider errors (HTTP 402 insufficient_balance_error) should not be retried.
  • The UI should show a session-level "input tokens / estimated cost" indicator so runaway growth is visible before the balance is gone.

Related Module

Guided Learning

Configuration Used

DeepTutor 1.6.15 (source install, `pip install -e .`, `deeptutor start`)
Provider: DeepSeek (provider=deepseek, official endpoint)
Model: deepseek-flash, context_window=1048576 (context_window_source=metadata)
capability: mastery_path, long multi-turn session

Logs and screenshots

Redacted excerpts from data/user/logs/deeptutor.jsonl (local time; request ids truncated; no keys or account data included):

# 2026-11-06, 26 occurrences between 14:00:27 and 16:38
14:26:54 WARNING deeptutor.services.session.context_builder | Context condensation failed (ValueError); bounding recent history without advancing its watermark
14:32:36 WARNING deeptutor.services.session.context_builder | Context condensation failed (ValueError); bounding recent history without advancing its watermark
... (24 more, all inside the same session)

# balance exhausted while the session was still running
16:27:47 ERROR deeptutor.runtime.orchestrator | Capability mastery_path failed: Error code: 402 - {'error': {'message': 'Insufficient Balance (request_id: 21e7ae62-...)', 'type': 'insufficient_balance_error'}}
16:36:01 ERROR deeptutor.Chat.context_summary_agent | LLM streaming failed: [deepseek] Error: {'message': 'Insufficient Balance (request_id: 63b7cc68-...)'}
16:36:28 ERROR deeptutor.runtime.orchestrator | Capability mastery_path failed: Error code: 402 (request_id: c1592628-...)
16:37:49 ERROR deeptutor.Chat.context_summary_agent | LLM streaming failed: [deepseek] Error: {'message': 'Insufficient Balance (request_id: dd07358c-...)'}
16:38:17 ERROR deeptutor.runtime.orchestrator | Capability mastery_path failed: Error code: 402 (request_id: f367b972-...)

Per-turn prompt_tokens in the affected session (usage.sqlite3, first call of each turn; 103 calls / 15,890,129 prompt tokens total):

14:19:08    24,337      15:12:14   523,422
14:24:44   191,708      15:22:35   525,438
14:32:04   401,969      15:45:07   531,844
14:43:14   474,154      15:56:37   534,481
14:52:19   497,213      16:21:19   540,794
15:00:35   521,601      16:26:43   573,715   <- largest single request

Distribution across the whole installation (llm_calls, 15 days):

prompt tokens per call calls prompt tokens
>= 50,000 148 24,191,092
>= 100,000 56 17,739,549
>= 300,000 27 13,343,397
>= 500,000 17 8,991,298

For comparison, only 118 of 1,382 calls (254,465 prompt tokens, 0.6%) occurred outside a user turn window, and no calls occurred outside 09:00–18:00 local — so this is not a background/scheduled caller, it is the per-turn context growth inside mastery sessions.

Additional Information

  • DeepTutor Version: 1.6.15
  • Operating System: Windows 11 25H2 (10.0.26200)
  • Python Version: 3.13.3
  • Node.js Version: 24.11.1
  • Browser (if applicable): n/a (API/backend usage)
  • Related Issues: none that we could find; #2486 touches mastery turn evidence but not context budgeting

Suggested fixes (for discussion)

  1. Do not swallow the summarizer error. context_builder.py:766 logs only type(exc).__name__. Include a redacted repr(exc) (or its args) behind a debug flag so the ValueError source is diagnosable.
  2. Advance the watermark on a deterministic fallback. When summarization fails, persist a "hard truncation" marker (keep the last N messages, drop the rest) so the next turn does not resend the same unsummarized prefix forever.
  3. Enforce the request ceiling at the LLM client. A per-request input cap independent of context_window (e.g. min(model_window, MAX_HISTORY_PLAN_TOKENS) + tool/system budget) would have rejected the 573k request before it was billed. Also fix the len(retained_groups) > 1 trim loop so a single oversized group cannot survive.
  4. Audit the mastery prompt assembly. With MAX_HISTORY_PLAN_TOKENS = 131_072, something in the mastery path (_lesson_packet, previous_model_turn replay, or share_mastery_history) appears to bypass the measured budget; the 573k requests need a trace showing which assembler produced them.
  5. Cost guardrails. Warn (and optionally block) when a session exceeds a configurable token budget; surface session prompt tokens / estimated cost in the UI.
  6. Treat 402 as terminal. insufficient_balance_error should fail fast and tell the user to top up, not retry.

Note: logs, identifiers, paths and request ids in this report were truncated/redacted; the full per-call ledger stayed local.

Marling2024 avatar Nov 06 '26 12:11 Marling2024

Confirmed the oversized-history branch on current dev (60fb3bd, v1.7.2), using synthetic text, a temporary SQLite store, and the real ContextBuilder. No provider call was needed. It also overflows when the summarizer succeeds, which separates this from the repeated-condensation-failure problem.

With context_window=1_048_576, max_tokens=4096, three short messages followed by an assistant message containing "alpha " * 150_000:

Controlled summary result result.budget result.token_count Second build
Raises ValueError 131,072 150,002 150,002
Returns a short successful summary 131,072 150,009 150,009

In the failure case, the watermark stays at zero and summarization is attempted again on the second build. Both cases preserve the durable messages. The overflow comes from the final retained-group loop: it stops with one group remaining even when that group exceeds the budget. A summary retry/backoff change alone would leave this case.

Small offline reproduction, run from the source checkout's Python environment
import asyncio
import tempfile
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch

from deeptutor.services.session.context_builder import ContextBuilder
from deeptutor.services.session.sqlite_store import SQLiteSessionStore

async def main():
    for succeeds in (False, True):
        with tempfile.TemporaryDirectory() as tmp:
            store = SQLiteSessionStore(Path(tmp) / "history.db")
            sid = (await store.create_session())["id"]
            for role, text in [
                ("user", "Earlier question"), ("assistant", "Earlier answer"),
                ("user", "Latest question"), ("assistant", "alpha " * 150_000),
            ]:
                await store.add_message(sid, role, text)
            builder = ContextBuilder(store)
            summary = (AsyncMock(return_value=("Small successful summary", []))
                       if succeeds else AsyncMock(side_effect=ValueError("fixture")))
            cfg = SimpleNamespace(model="synthetic-model", binding="openai",
                                  context_window=1_048_576, max_tokens=4096)
            with patch.object(builder, "_summarize", summary):
                result = await builder.build(session_id=sid, llm_config=cfg)
            print(succeeds, result.budget, result.token_count)
            assert result.token_count > result.budget

asyncio.run(main())

This verifies the history-builder overflow, not the reported 573k provider request or its 402 retry behavior. The full request also includes system/tool/current-turn context, so those need separate measurement at request assembly. For a regression, it would help to cover both summary outcomes and both legacy text rows and recorded model turns; any request-bounding change should retain the existing durable-history/watermark recovery guarantees and valid tool-call/result pairing.

Taz33m avatar Nov 07 '26 00:11 Taz33m

Thanks for the offline reproduction — it matches what we see, and it is useful that it holds for the successful summary branch too. Two additions from the original installation (redacted).

The production session also had a non-zero watermark. Its stored state is a 1,391-character compressed_summary with summary_up_to_msg_id = 476, and condensation still failed repeatedly afterwards (26 times between 14:00 and 16:38). So the overflow is not only "watermark stuck at 0"; it reproduces with a durable summary present, consistent with your single-group observation.

Request-assembly measurement (the part you flagged as unverified). We do have per-turn context_budget events (segment estimates recorded at assembly) next to the provider-reported usage for the same turn:

turn ContextBuilder used_tokens (messages segment) provider prompt_tokens cache_read_input_tokens hit rate
…abd94b6f36 14:55:20 36,027 (9,817) 517,600 497,152 96.0%
…5a4956d112 15:12:14 35,846 (9,636) 523,422 521,344 99.6%
…b67664af8f 15:13:42 34,763 (8,554) 524,238 523,392 99.8%

The assembly estimate stayed near 35k while the provider billed ~520k, ~99% of it cache reads. That gap is not in the message segment that _model_tokens measures — our hypothesis is the replayed provider-side turns (replay_history / previous_model_turn, including tool results) are sent but not counted. Separately, the assembly-side messages segment did reach 216,715 on one turn (…fd6b2be62f), which already exceeds MAX_HISTORY_PLAN_TOKENS = 131_072 and is the same single-surviving-group shape you described.

402 tail. First 402 insufficient_balance_error at 16:27:47. Over the next 11 minutes there were four more attempts: 16:36:01 and 16:37:49 from context_summary_agent (condensation itself calling the model), plus two turns created at 16:35:50 and 16:37:38 with no recorded user message. The server-side logs do not show what created those two turns, so the retry source is not determinable from this data alone.

Data note: figures come from the local llm_calls ledger (data/user/usage.sqlite3) and per-turn context_budget events in turn_events; identifiers are truncated, and no keys, endpoints, or account data are included.

Marling2024 avatar Nov 07 '26 04:11 Marling2024

Fixed on local dev (e0872716f0245549565ba49169143c3e8b54e4ad). fix(runtime): announce input waits and reject oversized history plans. Validated with targeted regression tests and compatibility checks.

will be fixed in the next releases!

pancacake avatar Nov 14 '26 16:11 pancacake