Code-Driven Scaling: Breaking the Context Bottleneck in Long-Running LLM Tasks

    Large language models don't suddenly "get dumber" on long tasks. Their context window fills with irrelevant material until key constraints get diluted. This article explains context degradation and offers two practical remedies: treating code as the action layer so a controlled runtime handles retrieval and computation, and externalizing state with recursive decomposition so the window holds only the current sub-problem. It also covers how to combine the two approaches, the engineering guardrails they require, and when a code loop is the wrong choice.

    On long tasks, a model doesn’t suddenly get worse. Its context gets flooded with irrelevant information. Driving code, querying data, and running workflows through natural language is already common, but once the steps pile up, an agent starts missing conditions, repeating work, and even reporting intermediate results as established facts. The more tools you connect, the clearer the problem tends to become: every call drags along tool descriptions, parameter schemas, and return text, leaving less and less room in the window for the actual goal. The industry calls this context degradation: as input grows, the model follows key constraints less reliably, and its attention is diluted by historical noise.

    To address it, start by looking at what usually sits in the window. Fixed system instructions take up only a small share. Tool lists, skill descriptions, multi-turn dialogue, retrieved snippets, and tool outputs quickly consume most of the budget. The user’s real question for the current turn ends up as a thin layer within all of that. Expanding the window to a hundred thousand or even hundreds of thousands of tokens does not automatically mean the model “remembers better.” Within a single inference pass, the model still has to tell apart which sentence is a hard constraint, which passage is a stale draft, and which table is just an intermediate product. Once these materials blur together, forgetting and hallucination show up together.

    The fix is not to pile on ever more prompt text, but to change the action space and where state is stored. The two paths below can be used on their own or combined.

    1. Code as Action: Let Programs Do Retrieval and Computation

    A language model is already good at generating structured text, and code is structured text that is executable and verifiable. Rather than having the model read through a mass of records line by line in context, have it write a program, run that program in a controlled environment, then decide whether to keep editing based on the output.

    Take a student-record query. The requirement is to find all students for a given enrollment year. Stuffing the whole table into the prompt and asking the model to filter is slow and prone to dropping rows. The normal engineering approach hands filtering to a data engine:

    1. SELECT student_id, name, enrollment_year
    2. FROM students
    3. WHERE enrollment_year = 2025;

    The model translates natural language into a correct query or script; the engine handles scanning, filtering, and aggregation. What comes back to the model should be the row count, a sample, and the necessary fields, not the full contents of the database. The context keeps only what was asked, what conditions were used, and what conclusion was reached.

    A typical loop can be reduced to five steps.

    1. Intent parsing: extract entities, filter conditions, time range, output format, and prohibitions. When a field is missing, ask first rather than guessing at business rules.
    2. Code generation: prefer short, repeatable scripts. Write queries, statistics, and format conversions separately; avoid one script that handles every side effect at once.
    3. Controlled execution: run in an isolated environment with limits on the file system, network, and execution time. Input data enters through a defined interface, and no secrets go into the prompt or code comments.
    4. Result verification: check whether the result is empty, whether it exceeds the expected row count, whether field types match, and whether the filter conditions were actually applied. You can run a separate count statement or assertion and compare it against the main query.
    5. Iterate or deliver: if the result is off, send back only the error message and minimal context for the model to fix; if it meets expectations, output the conclusion and discard intermediate drafts.

    In the simplest “single API call” case, expressing the action as code usually reaches a level comparable to a structured parameter call, and it is often more flexible for anything more complex. Code can express loops, conditionals, composite queries, and intermediate variables, which a fixed parameter template struggles to cover. Conversely, if the action is just sending a notification or flipping a status, a structured call is steadier and easier to audit for permissions. The selection rule is concrete: use code when you need branching, batch processing, and repeatable computation; use a structured call for a single side effect that needs strong auditing and strict schema constraints.

    2. Externalized State and Recursive Decomposition: Keep Only the Current Sub-Problem in the Window

    The second path targets tasks that are themselves longer than the window. Don’t expect a single inference pass to read every piece of material. Put global state outside the window: raw files in object storage, business records in a database, run traces in logs, and a task table that stores only conclusions. Each turn, the model sees just three things: the current sub-goal, a brief conclusion from the previous step, and the tools or code interfaces allowed for this step.

    Recursion is not pasting the same prompt again; it is breaking a large problem into smaller problems that can be verified independently. For example, “compile the abnormal orders from the past year and give a distribution of causes” can be split into: define the time range, aggregate by error code, sample-read the anomaly descriptions, list the samples that can’t be classified separately, and finally summarize. Each layer returns only a summary, counts, and open questions upward. The parent task does not re-ingest the full text of the sub-task.

    This loop, where conclusions come back and raw text stays external, also counters the window being blown out by history. At the end of each turn, force a short state record: confirmed facts, unresolved questions, the next plan, and failed attempts. The next turn uses this state in place of the lengthy dialogue, rather than appending to the old conversation. Keep the reason for each failed attempt so the model doesn’t repeatedly generate the same ineffective code.

    3. How the Two Paths Work Together

    In a real system, it is best to separate planning, execution, and memory.

    The planner only decomposes tasks and writes acceptance criteria; it never touches bulk data directly. The executor generates queries or scripts from a sub-task and runs them in a sandbox. The memory layer stores only citable conclusions: the data source, filter conditions, sample size, anomalies, and confidence notes. If a conclusion depends on a particular query, save the reproducible statement and parameters, not the model’s verbal explanation at the time.

    A solid return convention is: on success, give “result + evidence pointer + coverage”; on failure, give “error type + retry suggestion,” without dumping the entire stack trace back into the window. An evidence pointer can be a query ID, a result file in object storage, or a time-versioned data table. This way, later review doesn’t require replaying the whole conversation.

    4. Engineering Boundaries You Must Hold

    Code amplifies capability, and it also amplifies mistakes. Generated code is untrusted by default and should be held to the same standard as untrusted user input.

    Least privilege. The execution identity can access only the databases, tables, and directories needed for this step. Deny arbitrary outbound connections by default; when external data is required, go through a registered read-only interface. Keep production writes separate from queries, and require explicit confirmation and an idempotency key for writes.

    Quotas and circuit breakers. Limit loop counts, single-run time, returned rows, and generated code length. Stop automatic editing once consecutive failures hit a threshold, and hand the diff to a human. Otherwise the model keeps patching on top of a wrong assumption indefinitely.

    Verify before you trust. For aggregate queries, run sanity checks on totals, null ratios, and extreme values. For a generated transformation script, compare input and output on a small sample first, then run it on the full dataset. The model saying “already checked” does not count as checking; there must be a program assertion or a reviewable query.

    No secrets in the prompt. Connection details come from the runtime environment, and logs mask sensitive fields. Truncate the samples returned to the model to avoid pouring large amounts of private data back into the window just to “let the model see it clearly.”

    Versioning and reproducibility. Save the task state, code version, input data version, and acceptance results. The same problem should be re-runnable the next day, rather than relying on fragments from a conversation that have already scrolled out of the window.

    5. When You Should Not Use a Code Loop

    When the problem is short, the rules are clear, and a single structured call can finish it, adding code generation only increases latency and failure points. When you need strict, verbatim adherence to regulations or contract terms, retrieve the original text and cite the source rather than letting the model “summarize with code and treat it as fact.” When the data definitions are in dispute, fix the definitions before writing the query; otherwise even a correct statement is just executing a wrong definition.

    6. A Minimal Rollout

    Start from a read-only scenario: a natural-language question comes in, the model generates a query, a sandbox executes it, the program checks row count and fields, and only a summary is returned once it passes. Once this chain is stable, add multi-step decomposition and an external state table. For each new write operation, add its own set of confirmation, idempotency, and auditing, rather than hanging all the tools onto one long conversation up front.

    The context window is a workbench, not a warehouse. The warehouse belongs in databases, object storage, and reproducible scripts; the workbench holds only the facts, constraints, and evidence pointers needed for the current decision. Code handles precise execution, recursive decomposition controls complexity, and short state records fight forgetting. Together, the three keep a long task from losing the one sentence that really matters just because too much was said.