Skip to content

feat: record tier and conversation per turn; osa metrics cost-report (E8.4) - #694

Merged
neuromechanist merged 16 commits into
developfrom
feature/issue-678-cost-per-conversation
Nov 11, 2026
Merged

neuromechanist merged 16 commits into
developfrom
feature/issue-678-cost-per-conversation

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

Summary

The backend half of E8.4: record which tier and which conversation every chat turn belongs to, and report cost per conversation, quick against analysis. Split from the widget work in #693 because the two together passed the 1500 line limit; they are independent.

  • request_log gains tier (quick, analysis, or NULL for a request that is not routed) and conversation_id, with an index on conversation_id. The model was already recorded per row. Existing databases are migrated on startup (_MIGRATION_COLUMNS, and the index is created after the migration so an old table does not fail on it).
  • ChatSession.conversation_id defaults to the session's id. The new session a handover opens inherits the old session's, so the quick row (<request id>:quick), the analysis row and every later turn on the new session, /chat/resume included, share one id. Every _log_streaming_metrics call in the chat stream passes tier and conversation_id; a handover's own row is the analysis run's, and an error before the analysis session starts is recorded as quick, since the assistant in hand is the quick model. A streamed request now leaves one row, the handler's: the metrics middleware no longer adds its stub row (no model) beside it (Streamed chat requests log a stub request_log row under the same request_id as the handler's row #687).
  • get_conversation_costs(conn, community_id, since) in src/metrics/queries.py: per-conversation quick and analysis cost, turns by tier and totals; stub rows (model NULL) are ignored; rows with no conversation id are listed by model. It reads a database from before the new columns existed, since the report does not migrate.
  • osa metrics cost-report --community nemar --since 7d [--db PATH] [--json]: a table of conversation (short id), start, turns quick/analysis, quick cost, analysis cost, total, then totals by tier, and the rows without a conversation id by model. The database is opened read-only (SQLite mode=ro, falling back to immutable=1 for a copy with no WAL files beside it).
  • Docs (docs/community-widget.md) and CHANGELOG.md updated.

Refs #678 (not closing it: the one-week report itself needs a week of use; the follow-up is noted on the issue).

Tests and commands

  • tests/test_metrics/test_db.py: the migration on an old-schema database (columns added, old rows kept, index created, idempotent)
  • tests/test_api/test_model_routing.py (metered_client): a handover writes a :quick row and an analysis row sharing conversation_id with tiers quick/analysis and the two models; a follow-up on the new session stays in the conversation; a /chat/resume row keeps the analysis session's conversation_id and tier; a plain quick turn writes one quick row; a community that does not route has a NULL tier; no row with tokens has a NULL model
  • tests/test_metrics/test_conversation_cost.py: built with real log_request calls and real estimate_cost; stub rows ignored, old rows listed by model, old-schema database read
  • tests/test_cli/test_metrics_cli.py: metrics cost-report through typer's CliRunner (table, --json, --since, read-only, a copy with no WAL files, old schema, empty window, missing and invalid files)
  • uv run pytest tests/test_metrics tests/test_api/test_model_routing.py tests/test_api/test_streaming_metrics.py tests/test_agents/test_model_routing.py tests/test_frontend tests/test_cli -q: 699 passed, 2 skipped
  • uv run pytest tests/test_api tests/test_core -q: 3288 passed, 11 skipped
  • uv run ruff check . && uv run ruff format --check .: clean

Not done here: running the report against a copy of dev's metrics database. The pull needs ssh through the hallu jump host, which this environment could not authenticate to (no identities in the agent). The command to run, and the follow-up, are on #678.

Closes #687

@neuromechanist neuromechanist added P2 Priority 2: Important, fix when possible cost-management Cost tracking and optimization observability Logging, monitoring, and debugging labels Nov 11, 2026
…; a --since with an offset is converted to UTC (#678); tested on real rows
…, falls back to immutable only on unable-to-open, shows failed requests, reads the default path without creating it (#678); tested on real WAL files
…cost-per-conversation

# Conflicts:
#	CHANGELOG.md
…handler's plus a middleware stub (#687); tested through the middleware and router
…cost-per-conversation

# Conflicts:
#	CHANGELOG.md
@neuromechanist

Copy link
Copy Markdown
Member Author

Review round 1 outcomes

  • 1. Important, WAL copy silently reports fewer rows: fixed in 6052ce4 (CLI, tests) and e860c1a (docs).
    • open_read_only now returns (connection, note). The note is set when the file's header says WAL mode and no -wal is beside it (checked before connecting, since a newer SQLite opens such a file read-only without complaint and silently reads the main file alone, and opening can create the -wal), or when the immutable fallback was needed. The CLI prints it to stderr and adds a note field to --json.
    • The fallback now catches only unable to open; a locked database is raised (tested with a real exclusive lock).
    • Docs (docs/community-widget.md, CHANGELOG) say to take the snapshot on the server with VACUUM INTO from a python3 -c in the container (there is no sqlite3 CLI; it works on a read-only connection and the result is not in WAL mode, so it is complete and never flagged), or to copy metrics.db with metrics.db-wal and metrics.db-shm.
    • Tests use real WAL files: a copy of the main file alone with 3 un-checkpointed rows reports fewer turns plus the note, the live file with its -wal reports 3 and no note, and a VACUUM INTO snapshot reports 3 with no note and empty stderr.
  • 2. Suggestion, --since with an offset: fixed in 1798dc5. parse_since and get_conversation_costs convert with .astimezone(UTC); a naive value is still UTC. Tests: parse_since("2026-11-01T00:00-08:00"), the CLI since in JSON, and a query-level window that excludes a row the unconverted text comparison would have kept.
  • 3. Suggestion, failed requests counted as turns: fixed in 1798dc5 (query) and 6052ce4 (CLI table). A row with a status of 400 or more, or an error message, counts under a new per-bucket errors and not under turns; its tokens and cost, if any, are still added. The docstring, CLI help and docs say so, and the totals and unassigned tables show a "Failed" column when there are any. Tests log real failed rows through log_request, including a 200 row with an error message.
  • 4. Informational, expired analysis session: fixed (docs only) in e860c1a: one sentence in the Metrics section says it is recreated with its own id and shows as a new conversation.
  • 5. Nit, get_metrics_db_path() creates the directory: fixed in 6052ce4. New resolve_metrics_db_path() in src/metrics/db.py creates nothing and the CLI uses it; get_metrics_db_path() calls it and then creates the directory as before. Test: with DATA_DIR pointing at a missing directory, the command exits 1 with "No metrics database" and the directory still does not exist.
  • 6. Nit, empty or schemaless database: fixed in 6052ce4. Tests for a 0-byte file and a SQLite file with no tables: both exit 1 with "Cannot read ... as a metrics database".
  • Added by the coordinator, Streamed chat requests log a stub request_log row under the same request_id as the handler's row #687 (stub row beside every streamed request): fixed in 7091c16. The middleware decides about its stub row when the response starts, before the stream's generator sets metrics_logged. The three streaming returns (/ask, /chat, /chat/resume) now call _claim_metrics_row(http_request) before returning the StreamingResponse, so the generator's row is the only one under the request id. Tests through the real MetricsMiddleware and router: a streamed chat and a streamed resume leave exactly one row per request id (they fail, 8 of the file's tests, with the fix removed). The model IS NOT NULL filter in tests/test_api/test_model_routing.py::_request_rows, which only worked around Streamed chat requests log a stub request_log row under the same request_id as the handler's row #687, is dropped, so every existing handover test now asserts on the unfiltered table. The cost report's model IS NOT NULL filter stays: it also covers non-streamed requests that log no model. PR body now says Closes #687.

Merged origin/develop twice (CHANGELOG conflicts, every entry from both sides kept, no duplicates).
Checks after the last merge: uv run ruff check . and ruff format --check src tests pass; pytest tests/ -m "not network and not llm": 5654 passed, 14 skipped, 1 failed. The failure, tests/test_tools/test_hed_suggest.py::test_real_program_suggests_a_schema_tag, runs the machine's installed hed-suggest Node program, which crashes here with Cannot find module 'hed-validator'; it is not touched by this branch (no diff against develop in src/assistants or tests/test_tools).

…cost-per-conversation

# Conflicts:
#	CHANGELOG.md
#	docs/community-widget.md
…n the reader disconnects first (#687); tested through the ASGI app
… created and the note repeats; a skipped -wal gets its own note; symlinks are judged beside the real file (#678); tested on real files
… through the middleware row (#678); tested on the real route
…), non-streamed chats carry a conversation id, the WAL notes (#678, #687)
@neuromechanist

Copy link
Copy Markdown
Member Author

Review round 2 outcomes

  • 1. Important, a stream that never reaches a logging call leaves no row: fixed in 47c4ee3.
    • _log_streaming_metrics sets request.state.stream_row_written when it writes the request's main row (not the :quick row); metrics_logged stays set by _claim_metrics_row, so the middleware stays quiet.
    • New _log_unfinished_stream, called from the outermost finally of both _stream_ask_response and _stream_chat_response, writes the row when the flag is not set: status 499 and client disconnected for a closed generator or a cancelled task, 500 and the exception's type for an exception that escaped, 500 for a generator that returned without a row; it carries the row's tier and conversation id and the tokens counted so far. It is synchronous, so it runs inside a cancelled generator.
    • A handover that is cut off during the summary writes the quick model's tokens on the :quick row only and none on the 499 main row, so they are not counted twice.
    • The overlapping-turn refusal (which returned before any logging) now writes a 409 row.
    • Tests drive the real app with a raw ASGI receive/send that disconnects after a chosen chunk: exactly one row per request id, status 499, for /chat (after the session event), /ask (after the first content event) and a handover cut off during the summary; a full stream is still one 200 row. An exception that escapes and a generator that returned without a row are covered on the real database. With the fix removed these fail. The docstrings of _claim_metrics_row and the middleware say the generator guarantees the row.
    • One limit: partial tokens are covered by the escaped-exception test (50 in, 5 out kept on the row), not by a disconnect. Through BaseHTTPMiddleware a disconnect cannot land between the done chunk and the log call that follows it, and tokens are only counted at the end of a model run, so an ASGI disconnect always ends the stream before any tokens exist.
  • 2. Important, the undercount note disappears on a second run: fixed in 5b5eebf. A WAL-mode file with no -wal is now opened with mode=ro&immutable=1 straight away (it creates no files, and reads the same rows), and keeps the note; _wal_mode_without_log resolves the path so a symlinked database is judged beside its real file. Tests: the directory listing is unchanged after two calls and both return the note; a symlink to a live database with its -wal has no note and sees the row.
  • 3. Suggestion, "no -wal file is beside it" when a -wal exists: fixed in 5b5eebf. When mode=ro fails with "unable to open" and a -wal is beside the file, the immutable fallback returns a second note (IMMUTABLE_WITH_WAL_NOTE: rows in the -wal file beside it are not included). Test: a copy of a live database with its -wal but no -shm in a read-only directory.
  • 4. Suggestion, docs said the stub "stays as it was": fixed in f1d48d2. The Metrics section now says a streamed request writes one row (its generator's, or a 499 row if the reader disconnected, or 409 for a refused overlapping turn), and that rows written before this change may also have a stub, which the report ignores. CHANGELOG is consistent and mentions the 499 row. The WAL paragraph also describes the immutable open, symlinks and the second note.
  • 5. Suggestion, non-streamed /chat rows carry no conversation id: fixed in 63f93b1. _set_metrics_on_request takes conversation_id (passed by /chat) and puts it, and tier (always None, since a request that is not streamed is never routed), into metrics_agent_data; the middleware's agent_kwargs passes both to the row. Test through the real route and middleware: the row has the session's conversation id, no tier, and the tokens. The docs now say so (non-streamed requests have no tier; /ask has no conversation).

Merged origin/develop first (9f2059c; a CHANGELOG and a docs/community-widget.md conflict, every entry from both sides kept, no duplicates); it had not moved again before the push. Checks: uv run ruff check . and ruff format --check src tests pass; pytest tests/ -m "not network and not llm": 5665 passed, 14 skipped, 1 failed (test_hed_suggest.py::test_real_program_suggests_a_schema_tag, the environmental failure already confirmed on develop).

…since Rich wraps it on CI's 80-column terminal
@neuromechanist
neuromechanist merged commit 655da8c into develop Nov 11, 2026
9 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-678-cost-per-conversation branch November 11, 2026 06:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cost-management Cost tracking and optimization observability Logging, monitoring, and debugging P2 Priority 2: Important, fix when possible

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant