Skip to content

Commit 9d528a6

Browse files
fix(core,api): harden cancellation and tool telemetry (#122)
* fix(core): harden cancellation and tool telemetry * docs(progress): record run hardening PR #122 * fix(core): finalize canceled runs when the history load is interrupted Cancellation delivered while get_messages() was still awaiting escaped finalization entirely: the run row already existed in 'running', but the only CancelledError handler sat inside the reasoning-loop try block, so no terminal write (and no history repair happened at all) before re-raising. Route both cancellation windows through one shielded _finalize_canceled() helper. During setup the history save is skipped: the local snapshot is still empty and writing it would destroy the stored conversation rather than repair it. Adds the core-loop regression tests pinned to the post-create_run window and records the broadened rule in ADR-021. * test(real): pin /tools registry to an explicit SEARCH_API_KEY per case test_tools_endpoint_exposes_builtin_registry asserted web_search unconditionally, but the real-infra CI job never exports SEARCH_API_KEY, so the conditional registration change failed that suite at 144bc97. The new parametrized tools_client fixture builds one application per case with SEARCH_API_KEY passed explicitly: web_search is expected present with a key configured and absent without one, independent of the ambient environment, so a developer with the variable set cannot mask the key-missing path (or vice versa). * docs(progress): record PR #122 review-fix round
1 parent 01cc02e commit 9d528a6

9 files changed

Lines changed: 322 additions & 25 deletions

File tree

‎.env.example‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ LLM_RETRY_BASE_DELAY_S=0.5
5252
LLM_RETRY_MAX_DELAY_S=10
5353

5454
# External Tools & Sandboxing
55-
SEARCH_API_KEY=your_search_api_key_here
55+
# Optional: web_search is omitted from the tool registry when this is unset.
56+
SEARCH_API_KEY=
5657
FILE_TOOL_BASE_DIR=/tmp/agentkit_sandbox
5758

5859
# Security & API Authentication

‎README.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,14 @@ Designed from first principles for reliability, auditability, and production dep
2424
- `sql_readonly`: Read-only SQL executor over a dedicated non-superuser role (`DATABASE_READONLY_URL`, `default_transaction_read_only`, `SELECT`-only grants, fail-closed when unconfigured). A statement lexer accepts a single `SELECT`/`WITH`, rejects comments, DDL/DML and privileged built-ins (`pg_read_file`, `setval`, `query_to_xml`, …), and clamps `LIMIT ALL`/oversized limits in SQL.
2525
- `read_file`: Path traversal and symlink escape defended sandboxed file reader.
2626
- `http_fetch`: SSRF-protected HTTP client blocking private subnets, loopbacks, and cloud metadata endpoints.
27-
- `web_search`: Search provider adapter with result truncation.
27+
- `web_search`: Search provider adapter with result truncation; registered only when `SEARCH_API_KEY` is configured.
2828
- **Dual-Store Persistence**:
2929
- **Redis**: Sliding-window session memory and high-throughput sliding window rate limiter.
3030
- **PostgreSQL**: Durable execution audit trails with step-by-step latency, token counts, and tool outcomes.
3131
- **Enterprise-Grade Reliability**:
3232
- Exponential backoff retry with full jitter for transient LLM errors.
3333
- Global run timeout, per-tool timeout guards, and consecutive duplicate tool call loop detection.
34+
- Client disconnects never leave zombie runs: cancellation persists a terminal `canceled` status plus repaired session history inside `asyncio.shield` before re-raising.
3435
- Structured contextual JSON logging (`run_id`, `step_no`, duration) with zero raw confidential prompt leakage.
3536
- **Containerized & CI-Ready**: Multi-stage production `Dockerfile`, `docker-compose.yml` with healthchecks, and full GitHub Actions CI matrix (`ruff`, `mypy`, `pytest` >= 85% coverage).
3637

@@ -287,6 +288,8 @@ View run traces programmatically via REST API:
287288
curl -H "X-API-Key: YOUR_API_KEY" http://localhost:8000/runs/{run_id}/trace | jq .
288289
```
289290

291+
Token attribution note: when one model turn requests several tool calls, the turn's token usage is recorded on that step's *first* successfully recorded tool-call row and sibling rows report `0` on the token columns — so `sum(steps.*) <= runs.total_*` always holds and zero-token rows mean "this row does not carry the turn's usage", not "no tokens were used" (see [docs/DECISIONS.md](docs/DECISIONS.md) ADR-021).
292+
290293
---
291294

292295
## Architectural Decisions (ADR Summary)

‎agentkit/api/deps.py‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -116,14 +116,15 @@ def get_trace_sink(request: Request) -> TraceSink:
116116
return PostgresTraceSink(factory)
117117

118118

119-
def create_default_tool_registry() -> ToolRegistry:
120-
"""Construct standard ToolRegistry populated with all AgentKit built-in tools."""
119+
def create_default_tool_registry(search_api_key: str | None = None) -> ToolRegistry:
120+
"""Construct the built-in registry, including search only when configured."""
121121
registry = ToolRegistry()
122122
registry.register(calculator)
123123
registry.register(read_file)
124124
registry.register(http_fetch)
125125
registry.register(sql_readonly)
126-
registry.register(web_search)
126+
if search_api_key:
127+
registry.register(web_search)
127128
return registry
128129

129130

@@ -133,7 +134,10 @@ def get_tool_registry(request: Request) -> ToolRegistry:
133134
reg: ToolRegistry = request.app.state.tool_registry
134135
return reg
135136

136-
registry = create_default_tool_registry()
137+
settings: Settings = getattr(request.app.state, "settings", None) or get_current_settings(
138+
request
139+
)
140+
registry = create_default_tool_registry(settings.SEARCH_API_KEY)
137141
request.app.state.tool_registry = registry
138142
return registry
139143

‎agentkit/core/agent.py‎

Lines changed: 79 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -195,8 +195,18 @@ async def run(
195195
run_id=run_id,
196196
) from exc
197197

198-
async def _finalize_and_return(result: RunResult) -> RunResult:
199-
if session_id and self.memory is not None and hasattr(self.memory, "save_messages"):
198+
async def _finalize_and_return(
199+
result: RunResult, *, save_history: bool = True
200+
) -> RunResult:
201+
# save_history=False covers cancellation while the history load is still in
202+
# flight: at that point the local list is empty and saving it would overwrite
203+
# the stored conversation with nothing instead of repairing it.
204+
if (
205+
save_history
206+
and session_id
207+
and self.memory is not None
208+
and hasattr(self.memory, "save_messages")
209+
):
200210
_repair_trailing_tool_calls(messages)
201211
try:
202212
await self.memory.save_messages(session_id, messages)
@@ -257,10 +267,60 @@ async def _finalize_and_return(result: RunResult) -> RunResult:
257267
) from exc
258268
return result
259269

270+
async def _finalize_canceled(*, save_history: bool) -> None:
271+
"""Persist a terminal canceled run state before the cancellation re-raises.
272+
273+
create_run() has already persisted a running row, and cancellation can land
274+
on any awaited step that follows it — the session-history load or an await
275+
inside the reasoning loop. Without this finalization the row would be
276+
stranded in 'running' even though the caller received the cancellation.
277+
"""
278+
duration_ms = max(0, int((time.perf_counter() - start_time) * 1000))
279+
canceled_result = RunResult(
280+
run_id=run_id,
281+
session_id=session_id,
282+
goal=goal,
283+
status=RunStatus.CANCELED,
284+
failure_reason="Run was canceled by the caller.",
285+
steps_count=steps_count,
286+
total_input_tokens=total_input_tokens,
287+
total_output_tokens=total_output_tokens,
288+
duration_ms=duration_ms,
289+
)
290+
logger.info("Agent run canceled")
291+
try:
292+
# shield keeps the terminal write alive against further cancellation so
293+
# the store never reads back a run that stayed 'running' behind a cancel.
294+
await asyncio.shield(
295+
_finalize_and_return(canceled_result, save_history=save_history)
296+
)
297+
except PersistenceError:
298+
logger.error("Could not persist canceled run state for run %s", run_id)
299+
300+
# Initialized before the history load so a cancellation landing during setup
301+
# can still read zeroed counters when composing the canceled RunResult.
302+
total_input_tokens = 0
303+
total_output_tokens = 0
304+
steps_count = 0
305+
traced_turn_usage: set[int] = set()
306+
# Sliding window of recent call signatures. Remembering only the immediately
307+
# preceding signature lets an alternating pattern (A, B, A, B, ...) reset the
308+
# counter on every step, so the guard never fires and the run burns max_steps.
309+
recent_tool_signatures: deque[tuple[str, str]] = deque(
310+
maxlen=self.config.duplicate_tool_call_window
311+
)
312+
260313
messages: list[Message] = []
261314
if session_id and self.memory is not None and hasattr(self.memory, "get_messages"):
262315
try:
263316
loaded = await self.memory.get_messages(session_id)
317+
except asyncio.CancelledError:
318+
# The history load is the only awaited setup the CancelledError handler
319+
# below does not reach, and it runs after the run row already exists.
320+
# Finalize here so the row cannot stay 'running'; history was never read
321+
# or mutated in this window, hence save_history is deliberately False.
322+
await _finalize_canceled(save_history=False)
323+
raise
264324
except Exception as exc:
265325
# Continuing here would answer with no context and then overwrite the real
266326
# history with the shorter one: silent, permanent conversation loss.
@@ -297,16 +357,6 @@ async def _finalize_and_return(result: RunResult) -> RunResult:
297357
messages.insert(0, Message.system(self.config.system_prompt))
298358
messages.append(Message.user(goal))
299359

300-
total_input_tokens = 0
301-
total_output_tokens = 0
302-
steps_count = 0
303-
# Sliding window of recent call signatures. Remembering only the immediately
304-
# preceding signature lets an alternating pattern (A, B, A, B, ...) reset the
305-
# counter on every step, so the guard never fires and the run burns max_steps.
306-
recent_tool_signatures: deque[tuple[str, str]] = deque(
307-
maxlen=self.config.duplicate_tool_call_window
308-
)
309-
310360
try:
311361
async with asyncio.timeout(self.config.run_timeout_s):
312362
for _ in range(self.config.max_steps):
@@ -401,10 +451,19 @@ async def _finalize_and_return(result: RunResult) -> RunResult:
401451
result=result.model_dump(),
402452
error=result.error,
403453
latency_ms=result.latency_ms,
404-
input_tokens=response.usage.input_tokens,
405-
output_tokens=response.usage.output_tokens,
454+
input_tokens=(
455+
response.usage.input_tokens
456+
if steps_count not in traced_turn_usage
457+
else 0
458+
),
459+
output_tokens=(
460+
response.usage.output_tokens
461+
if steps_count not in traced_turn_usage
462+
else 0
463+
),
406464
)
407465
await self.trace.record(trace_record)
466+
traced_turn_usage.add(steps_count)
408467
else:
409468
# No tool calls: this is the final answer, a provider refusal, or
410469
# an empty completion. Only a non-empty answer is a success; the
@@ -485,6 +544,12 @@ async def _finalize_and_return(result: RunResult) -> RunResult:
485544
raise MaxStepsExceeded(self.config.max_steps)
486545
return res_max
487546

547+
except asyncio.CancelledError:
548+
# Loop-time cancellation: every step up to here may have left an assistant
549+
# tool-call turn without its results, so the history save (with repair) and
550+
# the terminal run write must both run before the cancellation propagates.
551+
await _finalize_canceled(save_history=True)
552+
raise
488553
except PersistenceError:
489554
# Already logged with its run id; re-raise rather than converting it into a
490555
# FAILED result that the caller could mistake for an executed-but-failed run.

‎agentkit/core/types.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ class RunStatus(StrEnum):
1010
RUNNING = "running"
1111
SUCCEEDED = "succeeded"
1212
FAILED = "failed"
13+
CANCELED = "canceled"
1314
#: The provider refused or filtered the response (safety block, content filter, refusal).
1415
REFUSED = "refused"
1516
MAX_STEPS_EXCEEDED = "max_steps_exceeded"

‎docs/DECISIONS.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,14 @@
22

33
This log records significant architectural, technical, and design decisions made throughout the lifecycle of AgentKit.
44

5+
## ADR-021: Run Cancellation and Turn-Level Trace Usage
6+
7+
- **Date**: 2026-11-01
8+
- **Status**: Accepted
9+
- **Context**: Cancellation can land on any awaited step that follows creation of the durable `running` row — the session-history load before the loop included — and a model response that requests multiple tools has one usage count shared by all calls.
10+
- **Decision**: On any such cancellation, finalize the run as `canceled` through a shielded finalization before re-raising; while the history load is still pending, history is left untouched because the empty local snapshot would overwrite the stored conversation, so only the run row is written. Once the loop is running, the same finalization also persists repaired session history. Store turn-level token usage on only the first successfully recorded tool trace for that reasoning step; subsequent call traces of the same step carry zero on the token columns, keeping per-call latency and outcome. Register the optional `web_search` tool only when `SEARCH_API_KEY` is present.
11+
- **Consequences**: Callers still observe task cancellation, persisted run state is terminal, and `sum(steps.input_tokens/output_tokens) <= runs.total_input_tokens/total_output_tokens` for any run. Equality holds only when every LLM turn either requested tools (so its usage landed on that step's first recorded tool trace) or consumed no tokens; the last, tool-free answer turn contributes to `runs.total_*` only, never to `steps`. Trace consumers must not treat zero-token rows as "the model used no tokens": they mean "this row does not carry the turn's usage". Search availability is consistent between runtime schemas and `GET /tools`.
12+
513
---
614

715
## ADR-001: Framework-less Agent Runtime from Scratch

‎docs/PROGRESS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ This document tracks execution progress across all backlog tasks, including pull
44

55
| Task ID | Milestone | Title | Branch | PR # | Commits | Status | Notes & Blockers |
66
|---------|-----------|-------|--------|------|---------|--------|------------------|
7+
| ROADMAP-01/06/07 | M14 | Run cancellation, token accounting, optional search registration | `fix/related-run-tool-hardening` | [#122](https://github.com/getdownandcode/AgentKit/pull/122) | 5 | In review | Fixes #93, #98 and #99 together: canceled runs persist terminal state, turn usage is attributed once across tool traces, and web_search is registered only with SEARCH_API_KEY. Review-fix round: cancellation during the awaited history load (after create_run but before the guarded loop) also finalizes the run as canceled with history untouched (tests/unit/test_agent_cancellation.py, ADR-021), and the real-infra /tools test now pins SEARCH_API_KEY per case so it is deterministic with the key set or unset. Quality gates pass (ruff check/format, mypy agentkit tests, pytest 508 hermetic passed, 31 real-infra passed, pytest-cov 93.4% >= 85%). |
78
| M0-T01 | M0 | Repository Setup & Context Scaffolding | `main` | N/A | 7 | Done | Initial warm-up repository scaffolding |
89
| M0-T02 | M0 | Configuration Management | `feat/config-settings` | #1 | 2 | Done | Pydantic BaseSettings with env validation |
910
| M0-T03 | M0 | Domain Errors & Core Base Types | `feat/core-errors-types` | #2 | 2 | Done | AgentKitError hierarchy, to_dict, StrEnum types |

‎tests/real/test_api_e2e_real.py‎

Lines changed: 48 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,13 @@
3131
API_KEY = "ak_real_infra_key"
3232

3333

34-
def _build_settings() -> Settings:
35-
"""Settings pointing the app at the live infrastructure under test."""
34+
def _build_settings(search_api_key: str | None = None) -> Settings:
35+
"""Settings pointing the app at the live infrastructure under test.
36+
37+
The search key is always part of the constructed settings object so the served
38+
tool set is pinned by the test case itself and cannot depend on whether the CI
39+
or the developer environment happens to export SEARCH_API_KEY.
40+
"""
3641
return Settings(
3742
DATABASE_URL=database_test_url(),
3843
REDIS_URL=redis_test_url(),
@@ -42,6 +47,7 @@ def _build_settings() -> Settings:
4247
MAX_STEPS=5,
4348
RUN_TIMEOUT_S=30,
4449
SESSION_TTL_S=3600,
50+
SEARCH_API_KEY=search_api_key,
4551
)
4652

4753

@@ -92,6 +98,33 @@ def llm(real_client: tuple[TestClient, FakeLLMClient]) -> FakeLLMClient:
9298
return real_client[1]
9399

94100

101+
@pytest.fixture(
102+
params=[
103+
pytest.param("fake_search_key", id="search-enabled"),
104+
pytest.param(None, id="search-disabled"),
105+
]
106+
)
107+
def tools_client(
108+
request: pytest.FixtureRequest,
109+
real_engine: AsyncEngine,
110+
real_redis: Redis[str],
111+
) -> Iterator[tuple[TestClient, bool]]:
112+
"""TestClient built with a deterministic SEARCH_API_KEY for each case.
113+
114+
A separate application per case is what makes both behaviors observable: the
115+
registry is memoized on app.state at first /tools access, so one shared client
116+
could serve whichever case ran first. The fixtures are requested for the same
117+
guarantee as real_client: truncate/cleanup happen before the app starts.
118+
"""
119+
del real_engine, real_redis
120+
121+
search_key: str | None = request.param
122+
app = create_app(settings=_build_settings(search_api_key=search_key))
123+
124+
with TestClient(app, raise_server_exceptions=False) as client:
125+
yield client, search_key is not None
126+
127+
95128
async def test_health_reports_live_dependencies(client: TestClient) -> None:
96129
"""The health endpoint must probe the real engine and Redis pool."""
97130
response = client.get("/health")
@@ -203,13 +236,23 @@ async def test_run_details_and_missing_run(client: TestClient) -> None:
203236
assert client.get(f"/runs/{uuid.uuid4()}", headers=headers).status_code == 404
204237

205238

206-
async def test_tools_endpoint_exposes_builtin_registry(client: TestClient) -> None:
207-
"""The built-in tool registry is served from the real dependency graph."""
239+
async def test_tools_endpoint_matches_configured_search_key(
240+
tools_client: tuple[TestClient, bool],
241+
) -> None:
242+
"""The served registry depends only on the explicitly pinned SEARCH_API_KEY.
243+
244+
Runs twice: with a key configured (web_search present) and without one
245+
(web_search omitted) — the latter being exactly what CI sees, where
246+
SEARCH_API_KEY is never set for the real-infrastructure job.
247+
"""
248+
client, web_search_expected = tools_client
249+
208250
response = client.get("/tools", headers={"X-API-Key": API_KEY})
209251

210252
assert response.status_code == 200
211253
names = {t["name"] for t in response.json()["tools"]}
212-
assert {"calculator", "read_file", "http_fetch", "sql_readonly", "web_search"} <= names
254+
assert {"calculator", "read_file", "http_fetch", "sql_readonly"} <= names
255+
assert ("web_search" in names) == web_search_expected
213256

214257

215258
async def test_unauthorized_request_is_rejected(client: TestClient) -> None:

0 commit comments

Comments
 (0)