Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(decisions): count a batch whose reply hit max_tokens as lost, not as nothing found (#4424)

Yunus Ozen8812da7a0fb6
diff --git a/packages/core/src/repowise/core/analysis/decisions/extractor.py b/packages/core/src/repowise/core/analysis/decisions/extractor.py
index 8c30a4587..61a384455 100644
--- a/packages/core/src/repowise/core/analysis/decisions/extractor.py
+++ b/packages/core/src/repowise/core/analysis/decisions/extractor.py
@@ -54,6 +54,7 @@ from .model_answers import ( # noqa: F401 (_coerce_paths, _collect_batches re-
_collect_batches,
_run_batches,
parse_decisions_json,
+ parse_decisions_reply,
)
from .prompts import (
_SYSTEM_PROMPT,
@@ -63,11 +64,12 @@ from .prompts import (
PR_BODY_MINING_PROMPT,
README_MINING_PROMPT,
)
-from .records import ( # noqa: F401 (the two errors are re-exported)
+from .records import ( # noqa: F401 (the three errors are re-exported)
DecisionExtractionReport,
DecisionSourceError,
EmptyModelResponseError,
ExtractedDecision,
+ TruncatedModelResponseError,
)
from .source_files import (
_BINARY_EXTENSIONS,
@@ -404,7 +406,7 @@ class DecisionExtractor:
response = await provider.generate(
_SYSTEM_PROMPT, prompt, max_tokens=2000, temperature=0.2
)
- decisions.extend(parse_decisions_json(response.content))
+ decisions.extend(parse_decisions_reply(response))
return decisions
# ------------------------------------------------------------------
@@ -433,7 +435,7 @@ class DecisionExtractor:
response = await provider.generate(
_SYSTEM_PROMPT, prompt, max_tokens=_BATCH_MAX_TOKENS, temperature=0.2
)
- extracted = parse_decisions_json(response.content)
+ extracted = parse_decisions_reply(response)
# Enrich with commit metadata
for d in extracted:
@@ -510,7 +512,7 @@ class DecisionExtractor:
response = await provider.generate(
_SYSTEM_PROMPT, prompt, max_tokens=2000, temperature=0.2
)
- for d in parse_decisions_json(response.content):
+ for d in parse_decisions_reply(response):
d.source = "adr"
d.status = "proposed"
d.confidence = 0.80
@@ -580,12 +582,13 @@ class DecisionExtractor:
bodies_block += pr_commit_block(c, files_by_sha.get(c["sha"], []), forge)
source_by_sha[c["sha"]] = f"{c['subject']}\n{c['body']}"
prompt = PR_BODY_MINING_PROMPT.format(bodies_block=bodies_block)
- # Not caught: _run_batches counts a failed batch, so an outage is
- # reported rather than read as nothing found.
+ # Not caught: _run_batches counts a failed batch, so an outage or a
+ # reply cut off at max_tokens is reported rather than read as
+ # nothing found.
response = await provider.generate(
_SYSTEM_PROMPT, prompt, max_tokens=_BATCH_MAX_TOKENS, temperature=0.2
)
- extracted = parse_decisions_json(response.content)
+ extracted = parse_decisions_reply(response)
for d in extracted:
_attribute_to_commit(d, batch, "subject", files_by_sha, source_by_sha)
d.source = "pr"
@@ -631,7 +634,7 @@ class DecisionExtractor:
response = await provider.generate(
_SYSTEM_PROMPT, prompt, max_tokens=2500, temperature=0.2
)
- extracted = parse_decisions_json(response.content)
+ extracted = parse_decisions_reply(response)
for d in extracted:
best_fp, best_prose = _snippet_for(d, batch)
d.source = "comment"
diff --git a/packages/core/src/repowise/core/analysis/decisions/model_answers.py b/packages/core/src/repowise/core/analysis/decisions/model_answers.py
index e8e178969..4e7627444 100644
--- a/packages/core/src/repowise/core/analysis/decisions/model_answers.py
+++ b/packages/core/src/repowise/core/analysis/decisions/model_answers.py
@@ -10,7 +10,12 @@ from typing import Any
import structlog
-from .records import DecisionSourceError, EmptyModelResponseError, ExtractedDecision
+from .records import (
+ DecisionSourceError,
+ EmptyModelResponseError,
+ ExtractedDecision,
+ TruncatedModelResponseError,
+)
logger = structlog.get_logger(__name__)
@@ -160,3 +165,18 @@ def parse_decisions_json(content: str) -> list[ExtractedDecision]:
for item in data
if isinstance(item, dict) and item.get("title", "")
]
+
+
+def parse_decisions_reply(response: Any) -> list[ExtractedDecision]:
+ """Parse a batch reply, which must not have been cut off.
+
+ A reply that stopped at ``max_tokens`` raises
+ :class:`TruncatedModelResponseError`: its text would otherwise read as
+ ``[]`` and the batch as one with nothing in it.
+ """
+ if getattr(response, "stop_reason", None) == "max_tokens":
+ raise TruncatedModelResponseError(
+ "the model's reply for this batch hit max_tokens "
+ f"({getattr(response, 'output_tokens', '?')} output tokens)"
+ )
+ return parse_decisions_json(response.content)
diff --git a/packages/core/src/repowise/core/analysis/decisions/records.py b/packages/core/src/repowise/core/analysis/decisions/records.py
index cca06c31e..a4a2a92c3 100644
--- a/packages/core/src/repowise/core/analysis/decisions/records.py
+++ b/packages/core/src/repowise/core/analysis/decisions/records.py
@@ -69,6 +69,15 @@ class EmptyModelResponseError(DecisionSourceError):
"""
+class TruncatedModelResponseError(DecisionSourceError):
+ """The model's reply for one batch stopped at its output token limit.
+
+ The cut-off text is not valid JSON, so :func:`parse_decisions_json` would
+ read it as ``[]``. Raised so the batch is counted as lost, and retried on
+ the next run, rather than read as nothing found.
+ """
+
+
@dataclass
class DecisionExtractionReport:
total_found: int
diff --git a/tests/unit/analysis/test_decision_batch_budget.py b/tests/unit/analysis/test_decision_batch_budget.py
index e4b4aaf98..e507cbdab 100644
--- a/tests/unit/analysis/test_decision_batch_budget.py
+++ b/tests/unit/analysis/test_decision_batch_budget.py
@@ -13,14 +13,17 @@ import json
from types import SimpleNamespace
import pytest
+from structlog.testing import capture_logs
from repowise.core.analysis.decisions.extractor import (
_BATCH_MAX_TOKENS,
DecisionExtractor,
DecisionSourceError,
EmptyModelResponseError,
+ TruncatedModelResponseError,
_collect_batches,
parse_decisions_json,
+ parse_decisions_reply,
)
_SHA = "9a0b27a7"
@@ -50,17 +53,22 @@ def _meta_map() -> dict[str, dict]:
class _Provider:
"""Returns whatever content it is given, and records the budget asked for."""
- def __init__(self, content: str) -> None:
+ def __init__(self, content: str, stop_reason: str = "end_turn") -> None:
self._content = content
+ self._stop_reason = stop_reason
self.max_tokens: list[int] = []
async def generate(self, system, prompt, **kwargs):
self.max_tokens.append(kwargs.get("max_tokens"))
- return SimpleNamespace(content=self._content)
+ return SimpleNamespace(
+ content=self._content,
+ stop_reason=self._stop_reason,
+ output_tokens=kwargs.get("max_tokens"),
+ )
-def _extractor(tmp_path, content: str) -> DecisionExtractor:
- provider = _Provider(content)
+def _extractor(tmp_path, content: str, stop_reason: str = "end_turn") -> DecisionExtractor:
+ provider = _Provider(content, stop_reason)
ex = DecisionExtractor(
repo_path=tmp_path, provider=provider, git_meta_map=_meta_map()
)
@@ -100,6 +108,28 @@ def test_unparseable_content_still_reads_as_nothing_found():
assert parse_decisions_json("I could not find any decisions.") == []
+# A reply cut off inside its second object: not valid JSON, and the last
+# ``]`` closes a nested array, so it used to parse as ``[]``.
+_CUT_OFF = (
+ '[{"title": "Resolve CLI command modules lazily", "decision": "lazy",'
+ ' "tags": ["perf"], "commit_sha": "9a0b27a7"},'
+ ' {"title": "Second", "alternatives": ["eager"], "rationale": "becau'
+)
+
+
+def test_a_reply_cut_off_at_max_tokens_raises_rather_than_reading_as_no_decisions():
+ assert parse_decisions_json(_CUT_OFF) == []
+ with pytest.raises(TruncatedModelResponseError, match="max_tokens"):
+ parse_decisions_reply(
+ SimpleNamespace(content=_CUT_OFF, stop_reason="max_tokens", output_tokens=8000)
+ )
+
+
+def test_a_complete_reply_parses_as_before():
+ reply = SimpleNamespace(content='[{"title": "T"}]', stop_reason="end_turn")
+ assert [d.title for d in parse_decisions_reply(reply)] == ["T"]
+
+
# --- what the miners do with it -------------------------------------------
@@ -115,6 +145,38 @@ async def test_a_lost_batch_fails_the_archaeology_source_too(tmp_path):
await ex.mine_git_archaeology()
[email protected]("miner", ["mine_pr_bodies", "mine_git_archaeology"])
+async def test_a_cut_off_batch_fails_the_source_instead_of_returning_zero(tmp_path, miner):
+ ex = _extractor(tmp_path, _CUT_OFF, stop_reason="max_tokens")
+ with pytest.raises(DecisionSourceError, match="max_tokens"):
+ await getattr(ex, miner)()
+
+
+async def test_a_cut_off_marker_reply_falls_back_to_the_raw_markers(tmp_path):
+ (tmp_path / "app.py").write_text(
+ "def fn():\n # DECISION: use lazy imports because startup is slow\n return 1\n",
+ encoding="utf-8",
+ )
+ ex = _extractor(tmp_path, _CUT_OFF, stop_reason="max_tokens")
+
+ decisions = await ex.scan_inline_markers()
+
+ assert [d.evidence_line for d in decisions] == [2]
+ assert decisions[0].confidence == 0.7 # the raw-marker fallback, not []
+
+
+async def test_a_cut_off_adr_reply_is_logged_as_a_failure(tmp_path):
+ ex = _extractor(tmp_path, _CUT_OFF, stop_reason="max_tokens")
+
+ with capture_logs() as logs:
+ decisions = await ex._mine_unstructured_adr(
+ ex.test_provider, "docs/adr/0001-notes.md", "We chose lazy imports."
+ )
+
+ assert decisions == []
+ assert any(e["event"] == "decision_extractor.adr_llm_failed" for e in logs)
+
+
async def test_the_failure_reaches_the_report_as_a_failure(tmp_path):
"""What the user sees: a named failure, not "Nothing found in"."""