You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 9d528a6
Browse filesBrowse the repository at this point in the historyBrowse 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
Copy file name to clipboardExpand all lines: README.md
+4-1Lines changed: 4 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -24,13 +24,14 @@ Designed from first principles for reliability, auditability, and production dep
24
24
-`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.
25
25
-`read_file`: Path traversal and symlink escape defended sandboxed file reader.
-`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.
28
28
-**Dual-Store Persistence**:
29
29
-**Redis**: Sliding-window session memory and high-throughput sliding window rate limiter.
30
30
-**PostgreSQL**: Durable execution audit trails with step-by-step latency, token counts, and tool outcomes.
31
31
-**Enterprise-Grade Reliability**:
32
32
- Exponential backoff retry with full jitter for transient LLM errors.
33
33
- 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.
34
35
- Structured contextual JSON logging (`run_id`, `step_no`, duration) with zero raw confidential prompt leakage.
35
36
-**Containerized & CI-Ready**: Multi-stage production `Dockerfile`, `docker-compose.yml` with healthchecks, and full GitHub Actions CI matrix (`ruff`, `mypy`, `pytest` >= 85% coverage).
36
37
@@ -287,6 +288,8 @@ View run traces programmatically via REST API:
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).
Copy file name to clipboardExpand all lines: docs/DECISIONS.md
+8Lines changed: 8 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -2,6 +2,14 @@
2
2
3
3
This log records significant architectural, technical, and design decisions made throughout the lifecycle of AgentKit.
4
4
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
+
5
13
---
6
14
7
15
## ADR-001: Framework-less Agent Runtime from Scratch
| 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%). |
0 commit comments