Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 10 min read

The Agent Read 8 KB of a 23 KB Test Report and Said 0 Failed

In the demo below, a test runner returns 240 results as JSON Lines, 23,760 bytes, with 3 failures in the module that sorts last. A loop that keeps the first 8,192 bytes hands the model 82 complete records, all passed, an

In the demo below, a test runner returns 240 results as JSON Lines, 23,760 bytes, with 3 failures in the module that sorts last. A loop that keeps the first 8,192 bytes hands the model 82 complete records, all passed, and the model reports 82 passed, 0 failed. Nothing raised, and every line it read was valid JSON.

A truncated tool result does not look broken. The first 8 KB of a log is a valid log, and the first 8 KB of a JSON Lines file is a valid JSON Lines file. Even a cut pretty-printed JSON object, which is no longer valid JSON, is easy to read as text. In the orders demo below, a reader that extracts amounts from the cut object finds 87 of 150, sums them to 7,221.00 against a real total of 17,175.00, and never sees the "has_more": true that sits after the array. Repairing a cut document by closing its brackets, as partial-JSON parsers do, gives the same silent prefix.

Where the cut comes from

Several things can cap a tool result before the model reads it: the context window, a limit in the provider or the MCP host, or the loop's own str(result)[:N]. The cap itself is reasonable. The problem is that the cut is silent, and the three shapes below make silence expensive:

  1. The verdict is at the end. A test report sorted by module puts the last module's failures last. A build log stops at the error, so the error is in the last screen.
  2. The metadata is at the end. has_more, next_cursor and total_count come after the array in many list responses. A prefix never contains them, so every page looks like the last page.
  3. The change is after the cut. An agent polling a build log reads the same first 8 KB every time. The model concludes nothing happened. Worse, a result-hash no-progress guard (the kind from the previous post in this series) sees an identical payload twice and calls it a stall.

Schema validation will not help here, because the truncated test report passes any per-record schema you write, and a stuck-loop guard will not help either, because the loop is making progress toward a wrong answer.

Four rules for cutting a result

  • Cut on line boundaries. A half record is noise the model skips, and the record it skipped may be the one that failed.
  • Keep the tail. For logs and reports the end is where the verdict lives. Spend a quarter of the budget there.
  • Say it where the model reads. A header at the top of the content and a marker where lines were dropped. Metadata the loop keeps in a side channel never reaches the model.
  • Carry the size and the hash of the full payload. Two different 100 KB results with the same first 8 KB must not look identical, to the model or to your stall guard.

The header also tells the model what to do: narrow the call. A total computed from a partial result is the thing to refuse.

Do not rely on the model reading the header. The loop knows truncated=True before the model does, so it can refuse to accept a final answer built on a truncated result until a narrower call has come back clean. If the tool is cheap to re-run, the other honest option is to skip the partial view entirely: return an error that gives the size and the cap and asks for a narrower query, such as a filter or a time range.

The guard

Standard library only. Save as result_guard.py. prefix is the baseline most loops already have. guarded is the replacement.

import hashlib


def prefix(text, cap=8192):
    """What most loops do today: keep the first `cap` bytes and say nothing."""
    data = text.encode()
    if len(data) <= cap:
        return dict(content=text, truncated=False, bytes=len(data))
    cut = data[:cap].decode(errors="ignore")
    return dict(content=cut, truncated=True, bytes=len(data))


def guarded(text, cap=8192, tail_share=0.25):
    """Fit a tool result into `cap` bytes without hiding that it was cut.

    Whole lines only, head and tail both kept, a header the model cannot
    miss, and the size and hash of the full payload so two different
    results never look identical after truncation.
    """
    data = text.encode()
    digest = hashlib.sha256(data).hexdigest()[:16]
    if len(data) <= cap:
        return dict(content=text, truncated=False, bytes=len(data), sha256=digest)
    lines = text.splitlines(keepends=True)
    header = ("[TRUNCATED TOOL RESULT: %d bytes, %d line(s), sha256 %s. "
              "You are seeing only part of it. Do not report "
              "totals from this. Narrow the call (filter, page, tail) to "
              "see the rest.]\n" % (len(data), len(lines), digest))
    marker = "[... %d line(s) omitted ...]\n"
    # 8 bytes of slack for the digits in the marker
    budget = cap - len(header.encode()) - len(marker.encode()) - 8
    tail_budget = int(budget * tail_share)
    head_budget = budget - tail_budget

    head, used = [], 0
    for ln in lines:
        b = len(ln.encode())
        if used + b > head_budget:
            break
        head.append(ln)
        used += b

    tail, used = [], 0
    for ln in reversed(lines[len(head):]):
        b = len(ln.encode())
        if used + b > tail_budget:
            break
        tail.append(ln)
        used += b
    tail.reverse()

    omitted = len(lines) - len(head) - len(tail)
    content = header + "".join(head) + marker % omitted + "".join(tail)
    return dict(content=content, truncated=True, bytes=len(data), sha256=digest)

The content field goes to the model. The truncated, bytes and sha256 fields stay in the loop: log them, and feed sha256 to your no-progress guard instead of hashing the content the model saw.

The demo

Save as demo.py next to result_guard.py and run python3 demo.py. Three tools return more than 8 KB: a test runner emitting JSON Lines, an orders API returning one JSON object with the cursor after the array, and a build log read twice while it grows. The "model" is a script that reads only the text it is shown; it is not an LLM, so these numbers show what reaches the model, not how a given model behaves. Its one assumption is in complete: it treats a result as whole unless the content starts with the truncation header.

import hashlib
import json
import re
from result_guard import prefix, guarded

CAP = 8192

# ---- Three tools that return more than 8 KB -------------------------------

MODULES = ["test_billing", "test_catalog", "test_invoice", "test_pricing",
           "test_refunds", "test_webhook"]


def run_tests():
    """JSON Lines, one record per test, sorted by module. The three
    failures are in test_webhook, which sorts last."""
    out = []
    for m in MODULES:
        for i in range(40):
            status = "failed" if (m == "test_webhook" and i >= 37) else "passed"
            out.append(json.dumps(dict(module="tests/%s.py" % m,
                                       name="test_case_%02d" % i,
                                       status=status,
                                       duration_ms=10 + i)))
    return "\n".join(out) + "\n"


def list_orders():
    """One JSON object. The cursor that says there is more comes after the array."""
    orders = [dict(id="ord_%d" % (1000 + i), customer="cus_%03d" % ((i * 37) % 500),
                   amount=40 + i, currency="USD")
              for i in range(150)]
    return json.dumps(dict(orders=orders, page=1, has_more=True,
                           next_cursor="eyJvZmZzZXQiOjE1MH0"), indent=1)


def read_log(lines):
    """A build log that grows between two polls. The ERROR is near the end
    of the second read and does not exist in the first."""
    out = []
    for i in range(lines):
        if i == 2290:
            out.append("[%05d] ERROR link failed: undefined symbol _gz_open in libarchive.so" % i)
        else:
            out.append("[%05d] compiling src/module_%02d/file_%04d.c ... ok" % (i, i % 97, i))
    return "\n".join(out) + "\n"


# ---- A scripted model: it reads only what it is shown ---------------------

def model_tests(seen):
    passed = failed = 0
    for ln in seen.splitlines():
        try:
            rec = json.loads(ln)
        except ValueError:
            continue  # a partial last line, or a header: skip it
        if rec.get("status") == "passed":
            passed += 1
        elif rec.get("status") == "failed":
            failed += 1
    return "%d passed, %d failed" % (passed, failed)


def model_orders(seen):
    amounts = [float(a) for a in re.findall(r'"amount": ([0-9.]+)', seen)]
    more = '"has_more": true' in seen
    return "%d orders, USD %s, more pages: %s" % (len(amounts), format(sum(amounts), ",.2f"), more)


def model_log(seen, before):
    status = "ERROR" if "ERROR" in seen else "no errors"
    same = hashlib.sha256(seen.encode()).digest() == hashlib.sha256(before.encode()).digest()
    return "%s, same as last poll: %s" % (status, same)


def complete(seen):
    """Would the model treat this as the whole result?"""
    return not seen.startswith("[TRUNCATED")


# ---- Run every scenario through both paths --------------------------------

def show(label, path, delivered, report):
    flag = "complete" if complete(delivered["content"]) else "PARTIAL"
    seen_bytes = len(delivered["content"].encode())
    print("%-8s %-8s %5d/%-6d %-9s %s" % (label, path, seen_bytes, delivered["bytes"], flag, report))


if __name__ == "__main__":
    tests, orders = run_tests(), list_orders()
    log1, log2 = read_log(2000), read_log(2300)
    truth_total = sum(o["amount"] for o in json.loads(orders)["orders"])
    print("truth    tests    %5d bytes   240 tests, 3 failed" % len(tests.encode()))
    print("truth    orders   %5d bytes   150 orders, USD %s, more pages: True"
          % (len(orders.encode()), format(truth_total, ",.2f")))
    print("truth    log      %5d then %d bytes, ERROR at line 2291 of the second read"
          % (len(log1.encode()), len(log2.encode())))
    print()
    print("result   path     seen/total   model     what the model reports")
    for name, fn in (("prefix", prefix), ("guarded", guarded)):
        d = fn(tests, CAP)
        show("tests", name, d, model_tests(d["content"]))
        d = fn(orders, CAP)
        show("orders", name, d, model_orders(d["content"]))
        d1, d2 = fn(log1, CAP), fn(log2, CAP)
        show("log", name, d2, model_log(d2["content"], d1["content"]))

Output:

truth    tests    23760 bytes   240 tests, 3 failed
truth    orders   14278 bytes   150 orders, USD 17,175.00, more pages: True
truth    log      102000 then 117319 bytes, ERROR at line 2291 of the second read

result   path     seen/total   model     what the model reports
tests    prefix    8192/23760  complete  82 passed, 0 failed
orders   prefix    8192/14278  complete  87 orders, USD 7,221.00, more pages: False
log      prefix    8192/117319 complete  no errors, same as last poll: True
tests    guarded   8144/23760  PARTIAL   77 passed, 3 failed
orders   guarded   8167/14278  PARTIAL   83 orders, USD 8,063.00, more pages: True
log      guarded   8151/117319 PARTIAL   ERROR, same as last poll: False

Reading the table:

  • tests. Each record is 99 bytes, so 8,192 bytes holds 82 whole records and 74 bytes of the 83rd. The partial line fails to parse and the script skips it. Guarded, the tail holds the last 20 records of test_webhook, so all three failures are in front of the model, and the header says the 77 is not a total.
  • orders. The prefix ends inside order 87, right after its amount, so the model sums 87 amounts and sees no cursor. Guarded, the tail is the end of the document: the last 20 orders, "has_more": true and the cursor. The count is still wrong, and the header says so.
  • log. The two prefix reads are byte-for-byte identical even though the log grew by 15,319 bytes and gained an ERROR. A no-progress guard keyed on the content hash would have called this a stall. Guarded, the header carries different byte counts and digests, and the ERROR at line 2291 is inside the 38-line tail.

Every guarded row is a few bytes under the cap because the header and marker are charged against the same budget. Nothing in the guarded content is a number the model could mistake for a total without reading past a line that says not to.

What this does not fix

The tail is a heuristic, not a search. Move the ERROR to line 1,500 of the log and head plus tail miss it. The fix for logs is tool-side: tail(n), grep(pattern), or a summary mode that returns counts and the first failure. Treat the guard as the floor under tools that have not been given those options yet.

Paging beats truncation when the tool is yours. If you control the tool, return whole pages with an explicit next offset instead of a head and tail. The guard is for the tools you can't change.

A single-line payload gets nothing but the header. Minified JSON of 14 KB is one line, so neither head nor tail fits and the model sees only the truncation notice. That is the correct outcome, since there is no honest partial view of a single JSON value, but it means list tools should paginate or pretty-print before they reach this code.

The model still has to read the header, and you should not depend on it. The scripted model obeys it by construction, and I have not measured how real models react to it. I put the notice at the top of the content and made it name the fix, but that is a design choice, not a result. Measure it: log truncated=True events alongside the model's next action, and count how often the next call narrows the query. That ratio tells you whether your header text works, and a sudden drop is a prompt regression you want on a dashboard.

Size the cap from your own data. The 8 KB here is a demo value. Take the distribution of tool result sizes in successful runs and set the cap above the high end, so truncation is rare enough that every event is worth looking at.

AI-assisted: the first draft of this article was written with an AI model, then edited by hand. All code was run with Python 3, and every number above comes from that run.

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.