Skip to content

Structured storage and usage queries ​

All persistent storage in Zhin is managed centrally by the Host (defaulting to out-of-the-box .zhin/data.sqlite, or configurable to PostgreSQL, MySQL, etc. in zhin.config.yml).

How plugins use Host-managed storage (developer overview) ​

Plugins do not open their own database connections or hard-code global table names. Instead, they use two Host-managed storage surfaces:

  1. Key-Value Store (KV Store): Ideal for lightweight state, cursors, and flags, automatically namespaced by plugin instance (owner) and inspectable in Console's Database page.
  2. Structured Tables (DatabaseFeature table declarations): Plugins declare logical table schemas and the Host maps them to owner-scoped physical tables with single-transaction atomic updates (CAS, claims, and receipts), preventing collisions across multiple plugin instances.

In addition, with Agent enabled and SQLite, MySQL or PostgreSQL configured, the runtime persists turn and model-call usage independently of log level, multi-Agent collaboration and trace archives. The Console database page can inspect these tables. Charts, statistics commands and a dedicated query API are not included yet.

yaml
ai:
  usage:
    retentionDays: 30

The retention period must be a positive integer. It defaults to 30 days. Cleanup runs at startup and hourly, removing each root turn and its calls together according to the root turn's completion time. This does not change message, session, task or ordinary log retention.

Tables and counting ​

agent_usage_turns stores one root turn: owner, trace/turn/session identifiers, principal, origin, complete conversation address, selected model, outcome, timestamps, duration and call count. agent_usage_calls stores each reported model response, and each perception pre-pass request (failed and cancelled ones included, token columns possibly NULL): root ID, actual child turn, call sequence, provider/model, stop reason, duration and numeric input/output/total, cache-read/write and reasoning tokens. Join calls to turns on root_id = id.

Every perception pre-pass request is a call row too (one per request to each candidate of the fallback chain, failed ones and one in flight at cancellation included), with that request's service id as provider, its model as model and stop, error or aborted as stop_reason; a failed or cancelled request, or one whose provider reported no usage, has NULL token columns (the quota is still charged an estimate). When the instance has no structured usage store (not SQLite, MySQL or PostgreSQL), the first turn logs one [ai.usage] usage_store | status: unavailable warning saying the tables are not written; it is not repeated.

Synchronous child calls belong to the same root and retain their own turn IDs. Do not add parent counts to detail counts. Unknown usage is NULL; only a proven zero is 0. Return both totals and known sample counts:

sql
SELECT provider, model, COUNT(*) AS calls,
       COUNT(input_tokens) AS calls_with_input,
       SUM(input_tokens) AS input_tokens,
       SUM(output_tokens) AS output_tokens
FROM agent_usage_calls
GROUP BY provider, model;

Cache tokens are input components; reasoning tokens are output components. These are provider-reported facts, not a billing ledger. Independent calls outside the turn event chain and failures without usage (other than the perception pre-pass requests above) are not estimated. Records commit atomically when a turn ends, so an unfinished turn lost in a process crash may have no final record. Persistence failure logs usage_persist | status: failed without changing delivery or repeating the model call.

Usage tables contain no chat body, prompt, reasoning text, tool arguments/results or exception body. Identity columns still contain business data and follow existing database/Console access controls.

Messages, sessions and tasks ​

  • conversation_events: event type, exact endpoint, conversation, parent, thread, actor and platform message ID; original event JSON and cursors remain intact.
  • agent_messages: actor, turn/intent, provider/model, stop reason and tool-result dimensions; payload, extensions and message-tree relationships remain intact.
  • agent_sessions: provenance at creation, without changing session routing or authorization. Unprovable historical provenance stays NULL.
  • unified_inbox_message: direction, canonical endpoint and thread alongside the original Console content/raw fields.
  • agent_schedule_jobs: schedule, creator, target, status and execution result as columns. Variable lists and event/schedule extensions remain explicitly named *_json fields.
  • Reminder/RSS owner-scoped tables separate tasks, operation receipts, seen article IDs and pending summary items. *_book rows hold revisions and migration markers, not a JSON task book. All rows and claims commit in one transaction. Unknown deliveries are never automatically resent; RSS baseline/resume and pause behavior is unchanged.

Identity columns use reversible k1: encoding (% → %25, NUL → %00) because canonical endpoint IDs may contain NUL, which PostgreSQL text rejects. Use encodeStorageIdentity / decodeStorageIdentity from zhin.js/plugin-runtime. Null and empty string remain distinct. Task free text uses the same encoding; provider/model and status fields remain plain text.

Upgrade ​

Stop the old process and back up the database and data/schedule-jobs.json before upgrading. Perform a full restart to register the new task tables. Do not run old and new writers against the same task storage.

Message migrations are additive and backfill in batches, preserving old columns, message trees and summary anchors. A malformed row in agent_messages fails that migration without deleting the original; fix it and start again. A conversation_events row with a null query_version or message_revision whose event_json does not parse (invalid_event_json), or is not a valid event (unknown or missing type, missing address or references — invalid_event), is skipped with a warning (table, row id and reason, never the body; the first 20 rows each, the rest only in the closing count). The row is left as stored: event_json is not rewritten and derived columns already written are not cleared. Rows that already have both columns set are not examined again. Indexes are still created, and the instance still starts. History reads and the Console transcript skip those rows (at most 20 warnings per store, then one notice with id: * and reason: reports_suppressed). Writing the same event_id again does not treat the damaged row as an existing event: the insert hits the unique key and fails until that row is repaired or removed. The next start warns again about rows that are still unbackfilled; the data is not dropped. Reminder/RSS import old CAS keys transactionally, then remove the old keys; durable markers prevent resurrection. Agent imports the old schedule file once and SQL becomes authoritative; after the import commits, the file is renamed to schedule-jobs.json.migrated (.migrated.1, .migrated.2, … when taken), unchanged, so nobody edits a file that no longer has an effect. Invalid or unsupported files fail migration and keep their name. Recovery: to roll back to a version that reads the JSON file, or to go back to file mode (no relational database), stop the process and rename data/schedule-jobs.json.migrated back to data/schedule-jobs.json. Jobs added, changed or removed in the database after the migration are not written back to that file, and the SQL store's migration marker keeps a later start from importing it again.

MongoDB, Redis and memory retain existing session capabilities. They do not gain structured usage or transactional task tables in this change, and emit an explicit unsupported diagnostic without switching databases. Existing Agent file-mode tasks retain their original storage.

The database-live CI job validates SQLite and both single-connection and pooled MySQL/PostgreSQL storage. This is database validation, not live IM delivery acceptance.