ds4 icon indicating copy to clipboard operation
ds4 copied to clipboard

Server: fix agent-loop cache misses, add cancellation, observability, and robustness fixes

Open elkaix opened this issue 5 months ago • 1 comments

This series came out of running ds4-server as the daily backend for a tool-calling coding agent (OpenAI chat completions dialect, 45K-90K token conversations) on the project's reference M5 Max. In that workload every agent turn was paying a full-state evict store (~650 MiB) plus a disk snapshot restore and a 12-25K-token tail re-prefill (~80-100 s per turn), because nothing bound a chat tool-call turn to the next request. The series fixes that (turns now cost only their genuinely new tokens, 2-3 s), plus the robustness and observability gaps found while diagnosing it.

No inference/backend code is touched: changes are confined to ds4_server.c, ds4_kvstore.c, and ds4_help.c. CUDA and ROCm were not validated (no backend-specific code changed); the CPU target was built as a compile check.

Commits

Cache efficiency (the agent-loop fix):

  1. Capture sampled whitespace separator in raw DSML tool blocks — raw-DSML replay was byte-exact only when the model sampled the canonical \n\n separator; any other separator was silently dropped from both content and raw block, so replayed history never byte-matched live KV. With this fix, agent replays retokenize token-identically in practice and hit the exact token-prefix path.
  2. Remember a visible live checkpoint for chat/Anthropic tool-call turns — mirrors the Responses API's predicted-visible-transcript mechanism for chat/Anthropic tool turns (reusing the thinking_live machinery), so when BPE spelling does drift, the next request still continues from live KV instead of taking the disk round trip. Hits are labeled tool-visible. The predicted text is prompt_text + build_tool_checkpoint_suffix(...), whose byte-equality with the next rendered prompt is already covered by test_tool_checkpoint_suffix_is_future_prompt_canonical.
  3. Store continued KV snapshots on step thresholds, not exact multiples — prefills resumed from unaligned cached positions never land on exact multiples of the continued interval, so waypoint snapshots silently stopped firing (observed 12-20K-token gaps). Threshold-crossing fires from any resume position; the cadence restarts at the continuation point.
  4. Give fresh KV snapshots an eviction grace over stale never-hit anchors — under budget pressure the newest waypoints of the live conversation (always hits=0, they were just written) were evicted first while stale anchors survived on the unconditional 2.0x reason bonus. Observed in production: the waypoint one position below a mid-history divergence was evicted seconds before it would have been hit. Never-hit entries now get a freshness grace (one hit decaying on the existing half-life) and the anchor bonus scales with the same activity term.
  5. Defer consumed KV snapshot deletion until the tail prefill succeeds — consume-on-load unlinked the snapshot before the tail prefill ran, so a transient sync failure (Metal OOM under memory pressure) or cancellation lost both live state and snapshot, forcing a cold prefill.
  6. Skip tool-map disk scan when all replay ids are already in RAM — every tools request opened and parsed the trailer of every checkpoint file for ids tool_memory already holds; now only missing ids trigger the walk (normally only right after a restart).

Correctness:

  1. Do not replay multi-invoke DSML blocks into partial messages — a client that splits one turn's parallel tool calls across two assistant messages (or drops one) got the full multi-invoke block attached to each message, rendering duplicated ghost invokes into the prompt. Blocks now record their invoke count and only attach to messages carrying exactly that many calls. Regression test included.

Robustness / operations:

  1. Cancel prefill and decode for disconnected clients — wires ds4_session_set_cancel() (already used by ds4-agent) around all server syncs, so prefill stops at the next chunk on shutdown or a dead socket instead of burning up to ~10 minutes for a client that timed out and retried; queued jobs from dead clients are skipped, and non-streaming decode polls the socket. Interrupted syncs keep the valid session prefix and do not discard the loaded disk snapshot.
  2. Add /health, /stats, and a bounded request queue — GET /health and GET /stats answer on the client thread (responsive mid-generation) with uptime, queue depth, per-source cache hit counters, token totals, and last prefill/decode t/s. Optional --max-queue N returns 429 when N jobs already wait (default 0 keeps unbounded behavior). 429/503 get proper HTTP reason strings.
  3. Small HTTP and API fidelity fixes — answer Expect: 100-continue; reject chunked transfer encoding with an explicit message instead of parsing an empty body; TCP_NODELAY; Anthropic-shaped error envelopes on /v1/messages; OpenAI error type follows status class (api_error for 5xx, rate_limit_error for 429); chat tool_choice "required"/forced now rejected like the Responses endpoint already does; log once per request when thinking mode overrides client sampling params.

Testing

Machine/backend: MacBook Pro M5 Max 128 GB, macOS (Metal). Model: DeepSeek-V4-Flash-Layers37-42Q4KExperts-OtherExpertLayersIQ2XXSGateUp-Q2KDown-AProjQ8-SExpQ8-OutQ8-chat-v2-imatrix-fixed.gguf (q2-q4 imatrix mixed quant), iogpu.wired_limit_mb=118000.

Commands run:

  • make clean && make — zero warnings.
  • make clean && make cpu — compile check, builds (pre-existing ds4.c warnings only, none in touched files).
  • git diff --check — clean.
  • make test — all suites pass (metal-tensor-equivalence worst_max_abs=0.139, top1_mismatch=0; server OK). SSD-streaming and MTP-verify suites skipped by the harness (require DS4_TEST_SSD_STREAMING / DS4_TEST_MTP).
  • ./ds4_test --server — OK (includes new regression tests for the raw-DSML separator, multi-invoke attach, continued-store thresholds, and eviction freshness).
  • ./ds4_test --tool-call-quality — OK (fast and exact paths).
  • ./ds4_test --logprob-vectors — OK (long_memory_archive skipped by the harness: API/official graph mismatch).
  • ./ds4_agent_test, ./ds4-eval --self-test-extractors — OK.
  • End-to-end smoke against a live server (scratch KV dir, 128 MiB budget, --max-queue 1): /health + /stats schema; OpenAI chat non-stream + SSE (thinking on/off); Responses; Anthropic success and error envelope; OpenAI error envelope; tool_choice=required 400; chunked rejection; Expect: 100-continue; 429 on queue overflow; disconnect cancellation frees the worker mid-decode (log shows finish=error error="client disconnected" within seconds of the socket dying); repeat >512-token request reports cached_tokens via disk second-hit; tiny budget triggers eviction and store-after-evict keeps the newest entry; graceful shutdown persists KV. 18/18 checks pass.

Production validation (same machine, pi coding agent, 45K-90K token sessions): agent turn overhead dropped from ~80-100 s (evict store + disk restore + 12-25K-token re-prefill, live kv cache miss ... token-mismatch every turn) to 2-3 s (exact-token or tool-visible live continuation); decode 24.8 -> 25-27.9 t/s at 46K ctx; a server restart resumed a 87K-token session from the shutdown snapshot prefetching only ~150 tokens.

Not validated: CUDA, ROCm, distributed (no backend or distributed code touched; ds4_server.c/ds4_kvstore.c compile into those targets unchanged). Speed: no inference-path changes; production decode/prefill numbers above show no regression on Metal.

elkaix avatar Jul 02 '26 21:07 elkaix

@elkaix The freshness grace is a good fix for fresh waypoints evicted before they earn a hit, but it misses one case, and for that case it's slightly worse than main.

Keeping a cache entry is a bet on future reuse, and past reuse is the best signal for it. A COLD reused a hundred times will likely be reused again; an EVICT or CONTINUED idle a few days probably won't be, no matter what size it is.

#489's activity-scaled anchor bonus strips a COLD entry's bonus once it goes idle, so a COLD that is reused often but on a slow cadence (mine gets hit dozens of times every couple of weeks) loses protection right when it needs it, and ranks below a much larger, but days-old conversation.

#550 keeps the 6h half-life for conversation snapshots (continued/evict) but stretches it to weeks for COLD, so a repeatedly-reused entry point's reuse count survives the gap instead of collapsing to zero.

unsaltedbutter-ai avatar Jul 21 '26 03:07 unsaltedbutter-ai