hermes-agent/tests/run_agent
Soju06 174ad45939 perf(state): apply per-call token accounting on a background single-writer queue
Every API call in the tool loop persisted its token/cost delta by
calling SessionDB.update_token_counts() synchronously on the turn
thread — a BEGIN IMMEDIATE sessions UPDATE plus a session_model_usage
upsert, measured in production at p50 3.3ms / p95 70.4ms per call and
up to 299ms against a cold multi-GB state.db. The tool loop stalls for
that long between calls, N times per multi-tool turn.

SessionDB gains queue_token_counts(): same signature and semantics as
update_token_counts(), but the critical path is a deque append plus a
condvar notify. A lazily started daemon thread applies deltas in
enqueue order through the existing update_token_counts ->
_execute_write path, so the established self._lock / BEGIN IMMEDIATE /
jitter-retry discipline is unchanged. When a backlog forms, adjacent
same-route incremental deltas coalesce into one UPDATE: token and
api-call fields sum, cost fields sum None-preservingly (an all-None
run stays None so COALESCE keeps the stored value), and absolute=True
deltas never merge and act as ordering barriers. Route equality is
required for a merge because those fields feed COALESCE backfill, the
last-non-None-wins status fields, and the per-model usage attribution
key — a merged apply is row-equivalent to sequential applies.

Correctness and durability:

- flush_token_counts() gives read-your-writes to token/cost readers
  (get_session, list_sessions_rich, _get_session_rich_row,
  list_gateway_sessions, InsightsEngine.generate) — a plain attribute
  check when nothing is queued. The writer sets its busy flag before
  popping the queue so the lock-free fast path can never miss an
  in-flight batch.
- update_session_model / update_session_billing_route /
  update_session_meta write the sessions row synchronously, bypassing
  the queue, so they flush it first: a still-queued first-of-session
  delta carries the pre-switch route, and applying it after the switch
  UPDATE would trip the first_accounted_route branch (api_call_count
  == 0 plus a route mismatch) and resurrect the old model/provider.
- AIAgent._persist_session flushes at turn finalize and every
  error-exit persist point; close() stops and drains the writer before
  the WAL checkpoint; an atexit hook (registered on first enqueue,
  unregistered on close so closed instances are not pinned until
  interpreter exit) drains at shutdown. Worst-case crash loss is the
  in-flight call's delta — the same window as the old inline write.
- A flush trusts a live stop-flagged writer (its loop drains before
  exiting) and only drains on the caller's thread when the writer is
  dead or never started, claiming the same busy flag so concurrent
  flushes wait instead of racing an in-flight batch.
- After close() has stopped the writer, queue_token_counts applies the
  delta inline instead of parking it on a queue nothing will drain; a
  closed-connection failure then raises at the call site, which
  already guards for it, exactly like the old synchronous path.
- Writer apply failures are logged and never raise into a turn; the
  writer thread survives and keeps applying.

Call sites switched to the queue: the per-call site in
agent/conversation_loop.py and both codex app-server sites in
agent/codex_runtime.py. In-memory per-turn counters
(agent.session_estimated_cost_usd etc.) stay synchronous, so live turn
displays never see the queue.

Tests: tests/agent/test_async_token_accounting.py (19 tests: enqueue
ordering, absolute-as-barrier, backlog coalescing with exact sums,
coalesced-vs-sequential row equivalence, merge unit rules, None-cost
preservation, read-your-writes, flush vs stop-flagged/concurrent
drains, inline apply after writer stop, close/atexit durability,
_persist_session drain, writer failure isolation);
tests/run_agent/test_token_persistence_non_cli.py updated to the
queue_token_counts contract.
2026-07-28 18:47:54 +05:30
..
__init__.py
…
conftest.py
…
repro_48013_image_shrink_brick.py
…
test_413_compression.py fix(context_compression): roll back interrupted preflight state pollution 2026-07-23 16:38:06 -07:00
test_860_dedup.py
…
test_1630_context_overflow_loop.py
…
test_18028_content_policy_blocked.py
…
test_24996_fallback_exhaustion_cooldown.py
…
test_28161_anthropic_stream_pool_cleanup.py fix(agent): request-local Anthropic clients so the stale/interrupt watchdog never corrupts SQLite (#67142) 2026-07-18 21:20:48 -04:00
test_31273_402_not_retried.py
…
test_32646_fallback_429_after_timeout.py
…
test_63425_credential_pool_auto_detect.py fix(agent): validate credential pool after provider auto-detection (#63425) 2026-07-14 16:51:35 +05:30
test_66267_multimodal_interim.py fix: normalize multimodal list content in build_assistant_message (#66267) 2026-07-18 19:39:07 +05:30
test_70773_shared_client_fd_corruption.py fix(agent): retire replaced shared OpenAI clients instead of cross-thread pool close 2026-07-24 16:04:48 -07:00
test_agent_guardrails.py fix(agent): uniquify duplicate tool-call ids to keep call/result pairing lossless 2026-07-26 20:59:06 -07:00
test_anthropic_prompt_cache_policy.py nous portal anthropic wire 2026-07-27 11:53:48 -04:00
test_anthropic_response_header_capture.py nous portal anthropic wire 2026-07-27 11:53:48 -04:00
test_anthropic_third_party_oauth_guard.py
…
test_anthropic_truncation_continuation.py
…
test_api_max_retries_config.py
…
test_async_httpx_del_neuter.py
…
test_auth_provider_failover.py
…
test_background_review.py
…
test_background_review_cache_parity.py fix(background_review): gate reasoning_config inheritance on not-routed + dedupe recorder stubs 2026-07-14 17:19:46 +05:30
test_background_review_cost_controls.py
…
test_background_review_summary.py
…
test_background_review_toolset_restriction.py
…
test_callable_api_key.py
…
test_codex_app_server_compaction.py revert: PR #72817 — session activity watchdog, stall notify, compress timeout 2026-07-28 00:15:00 +05:00
test_codex_app_server_integration.py fix(codex): reconcile app-server bridge with #38835, gate commentary on show_commentary 2026-07-17 04:32:56 -07:00
test_codex_multimodal_tool_result.py
…
test_codex_no_tools_nonetype.py
…
test_codex_silent_hang_hint.py
…
test_codex_xai_oauth_recovery.py fix(credential-pool): refresh the failing entry, not current(), on auth recovery 2026-07-23 07:33:25 -07:00
test_commit_memory_session_context_engine.py
…
test_compress_focus_plugin_fallback.py
…
test_compression_abort_state_reset.py test(compression): audit abort paths for per-attempt in-place state reset 2026-07-23 07:25:21 -07:00
test_compression_boundary.py
…
test_compression_boundary_hook.py fix(compression): recover rotated session lineage 2026-07-24 16:00:34 -07:00
test_compression_feasibility.py fix(compression): mirror the full trigger recomputation in the suggestion guard 2026-07-22 06:58:58 -07:00
test_compression_lock_defer.py fix(gateway): retry-next-message semantics for compression_deferred + regression suite 2026-07-23 16:23:57 -07:00
test_compression_persistence.py fix(conversation): anchor the cwd staleness read to the host-info block 2026-07-25 19:25:34 -07:00
test_compression_trigger_excludes_reasoning.py
…
test_compressor_fallback_update.py
…
test_concurrent_interrupt.py
…
test_context_token_tracking.py
…
test_conversation_fallback_state.py fix(conversation): clear _mute_post_response on substantive tool-only turn 2026-07-14 16:33:14 +05:30
test_copilot_native_vision_headers.py
…
test_create_openai_client_disables_sdk_retries.py
…
test_create_openai_client_kwargs_isolation.py
…
test_create_openai_client_proxy_env.py
…
test_create_openai_client_reuse.py test(agent): cover mount-pool interrupt abort and zero-socket warning 2026-07-28 18:07:44 +05:30
test_create_openai_client_ssl_verify.py
…
test_credential_pool_interrupt.py test: make interrupt-pool double's entries callable 2026-07-23 07:33:25 -07:00
test_credential_rotation_route_settings.py fix: restore base_url rstrip, extract should_clear_context_pin helper 2026-07-22 11:19:37 +05:30
test_credits_notices_toggle.py
…
test_custom_provider_extra_headers_client.py
…
test_deepseek_reasoning_content_echo.py
…
test_deepseek_v4_thinking_live.py
…
test_dict_tool_call_args.py
…
test_dropped_tool_call_recovery.py fix(agent): make dropped tool-call nudge pair ephemeral scaffolding 2026-07-24 15:56:39 -07:00
test_empty_response_recovery_persistence.py
…
test_empty_terminal_reasoning_surface.py feat(agent): surface a labeled reasoning excerpt at the empty-response terminal 2026-07-26 20:59:21 -07:00
test_exit_cleanup_interrupt.py
…
test_fallback_credential_isolation.py
…
test_fallback_reasoning_override.py feat(config): support per-model reasoning_effort overrides 2026-07-14 11:46:40 -07:00
test_file_mutation_verifier.py
…
test_fireworks_live.py
…
test_identity_flush.py
…
test_image_rejection_fallback.py
…
test_image_shrink_recovery.py
…
test_in_place_compaction.py test: assert durable compression rotation 2026-07-19 08:55:08 +05:30
test_infinite_compaction_loop.py
…
test_init_fallback_on_exhausted_pool.py
…
test_interactive_interrupt.py
…
test_interrupt_propagation.py
…
test_invalid_context_length_warning.py fix(compression): harden startup route scoping 2026-07-22 11:19:37 +05:30
test_iteration_budget_race.py
…
test_jsondecodeerror_retryable.py
…
test_last_reasoning_per_turn.py
…
test_lmstudio_load_mode.py feat: add LM Studio JIT load mode 2026-07-16 15:23:14 +05:30
test_long_context_tier_429.py
…
test_malformed_tool_arguments.py
…
test_materialize_data_url_cleanup.py
…
test_memory_nudge_counter_hydration.py
…
test_memory_provider_init.py
…
test_memory_sync_interrupted.py
…
test_message_sequence_repair.py refactor: single owner for empty-content wire repair (class fix) 2026-07-27 20:27:56 -07:00
test_moa_fanout_cadence.py feat(moa): add every_n fanout cadence with cached-guidance reuse 2026-07-23 17:50:40 -07:00
test_moa_loop_mode.py feat(moa): default advisor fanout to user_turn — the cheapest cadence 2026-07-23 21:07:18 -07:00
test_moa_privacy_filter.py feat(moa): add privacy redaction filter with display/full modes 2026-07-23 17:50:40 -07:00
test_moa_streaming.py feat(analytics): record auxiliary model usage per task in session accounting (#65537) 2026-07-16 04:23:12 -07:00
test_multimodal_tool_content_recovery.py
…
test_nonretryable_error_html_summary.py
…
test_notice_spine.py
…
test_nous_429_fallback_reentry.py
…
test_nous_fallback_unavailable.py
…
test_openai_client_lifecycle.py
…
test_partial_stream_finish_reason.py refactor: single owner for empty-content wire repair (class fix) 2026-07-27 20:27:56 -07:00
test_per_model_compression_threshold.py fix: close review gaps for per-model threshold overrides (#63020) 2026-07-22 07:00:27 -07:00
test_per_model_threshold_init_ordering.py fix: close review gaps for per-model threshold overrides (#63020) 2026-07-22 07:00:27 -07:00
test_percentage_clamp.py
…
test_plugin_context_engine_init.py
…
test_post_tool_compression_attempt_cap.py fix(compression): unify the attempt cap across every compression site 2026-07-22 06:56:42 -07:00
test_pre_compress_memory_context.py fix(redaction): normalize URL credential key aliases 2026-07-20 02:25:57 -07:00
test_preflight_compression_cap_e2e.py fix(compression): unify the attempt cap across every compression site 2026-07-22 06:56:42 -07:00
test_primary_runtime_restore.py nous portal anthropic wire 2026-07-27 11:53:48 -04:00
test_proactive_prune_loop_wiring.py feat(compression): prompt-cache reclaim gate + hardened wiring for proactive prune 2026-07-23 16:44:12 -07:00
test_provider_attribution_headers.py fix(xai): send Hermes-Agent User-Agent on chat/completions 2026-07-27 17:47:28 -07:00
test_provider_fallback.py nous portal anthropic wire 2026-07-27 11:53:48 -04:00
test_provider_parity.py test(providers): update Nous parity test for conversation tag 2026-07-16 01:13:43 -07:00
test_real_interrupt_subagent.py test(delegate): model socket-abort interrupt for the inline child API path 2026-07-26 20:37:51 -07:00
test_redirect_stdout_issue.py
…
test_repair_tool_call_arguments.py
…
test_repair_tool_call_name.py
…
test_retry_status_buffer.py
…
test_review_prompt_class_first.py
…
test_run_agent.py refactor: single owner for empty-content wire repair (class fix) 2026-07-27 20:27:56 -07:00
test_run_agent_codex_responses.py test: update credential-refresh tests for retire-not-close contract 2026-07-24 16:04:48 -07:00
test_run_agent_multimodal_prologue.py
…
test_sequential_chats_live.py
…
test_session_id_env.py
…
test_session_meta_filtering.py fix(timeline): persist typed display events (#69771) 2026-07-23 14:46:24 -04:00
test_session_reset_fix.py
…
test_session_source.py
…
test_steer.py fix(agent): keep interrupt-checkpoint scaffolding out of the steered transcript 2026-07-28 01:05:02 -05:00
test_stream_drop_logging.py
…
test_stream_interrupt_retry.py fix(streaming): block stale stream deltas 2026-07-18 19:55:16 +05:30
test_stream_single_writer_65991.py Revert "feat(observability): integrate NeMo Relay runtime and shared metrics" 2026-07-27 22:28:08 -04:00
test_stream_stale_breaker_reset.py
…
test_stream_stale_circuit_breaker.py fix(agent): request-local Anthropic clients so the stale/interrupt watchdog never corrupts SQLite (#67142) 2026-07-18 21:20:48 -04:00
test_streaming.py refactor: single owner for empty-content wire repair (class fix) 2026-07-27 20:27:56 -07:00
test_streaming_tool_call_repair.py
…
test_strict_api_validation.py
…
test_strip_reasoning_tags_cli.py
…
test_summarize_api_error.py
…
test_switch_model_context.py fix(providers): scope route-owned runtime settings 2026-07-22 11:19:37 +05:30
test_switch_model_fallback_prune.py
…
test_switch_model_pool_reload_52727.py
…
test_switch_model_reapplies_headers.py
…
test_switch_model_reasoning_override.py feat(config): support per-model reasoning_effort overrides 2026-07-14 11:46:40 -07:00
test_switch_model_rollback.py
…
test_switch_model_stale_base_url.py
…
test_thinking_only_sanitizer.py
…
test_thinking_sig_recovery_persistence.py
…
test_tls_fd_recycle_corruption.py test(agent): cover mount-pool interrupt abort and zero-socket warning 2026-07-28 18:07:44 +05:30
test_token_persistence_non_cli.py perf(state): apply per-call token accounting on a background single-writer queue 2026-07-28 18:47:54 +05:30
test_tool_arg_coercion.py
…
test_tool_batch_segmentation.py fix(agent): canonicalise paths in parallel-batch planner to prevent same-file concurrent mutation 2026-07-16 04:26:32 -07:00
test_tool_call_args_sanitizer.py
…
test_tool_call_guardrail_runtime.py Revert "feat(observability): integrate NeMo Relay runtime and shared metrics" 2026-07-27 22:28:08 -04:00
test_tool_call_incremental_persistence.py fix(session): persist tool activity before projection 2026-07-28 00:14:19 +05:30
test_tool_executor_contextvar_propagation.py
…
test_tool_name_db_persistence.py
…
test_turn_completion_explainer.py fix: follow-ups for salvaged PR #72425 2026-07-28 00:14:19 +05:30
test_unicode_ascii_codec.py
…
test_verification_continuation_budget.py fix(desktop, ink): don't wipe messages before final message (#65919) 2026-07-20 11:42:29 -04:00
test_vision_aware_preprocessing.py
…
test_vision_tool_messages.py
…
test_wait_state_visibility.py feat(agent): explain long provider waits on the live status line (#64775) 2026-07-15 00:14:05 -07:00