Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions doc/AI_USAGE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
# Durable AI usage capture

Normal Yetibot runtimes reserve an anonymous PostgreSQL ledger row before each
supported inference boundary. A request cannot proceed if that initial write
fails or does not acknowledge an inserted row. Catalog reads, operation status
polls and artifact downloads are not additional inference events.

## Startup and API

`init/-main` makes tracking mandatory before opening nREPL. Database startup
creates the additive `ai_usage` schema, then `ai-usage/start!` creates the
idempotent coverage marker and timestamp index before adapters and background
command loading activate. Interrupted Gemini agents wait for both the database
and a connected adapter. Losing the database's connected flag later cannot
silently disable capture.

Standalone library helpers used without starting Yetibot or its database keep
their previous API and are outside this runtime coverage. There is no chat
command or runtime setting to disable a running bot's required ledger.

`yetibot.core.util.ai-usage/capture!` accepts host-owned attributes, a request
function and a metrics projection. It:

1. Commits the pending reservation before invoking the request function.
2. Binds anonymous context/request UUIDs for nested model calls.
3. Finalizes safe counters and money in a separate transaction.
4. Returns the original response, even if final ledger preparation or storage
fails. The durable pending row then remains uncertain.

It never retries inference to repair accounting. A request exception retains
its original behavior; only a bounded HTTP status and failed/unknown state are
recorded. Existing model validation, media budgets and delivery behavior are
not replaced by the ledger.

Write transactions require synchronous commit. Connections and transactions
have bounded login, socket, statement and lock waits; no transaction remains
open while a provider or CLI is running. Finalization updates pending rows only.

The four-argument handler API is unchanged. It supplies an anonymous accounting
context around command execution. Applications entering outside that handler,
such as literal reply continuations, must establish the same context binding.

## Captured boundaries

- xAI text and image generation, including image-prompt rewriting.
- Gemini image generation and one Veo generation, not its polls/downloads.
- Gemini CLI process sessions, reserved before process spawn.
- Application Chat Completions, Responses, streams and each native-tool round.
- Application delegated model calls, structured classifiers and legacy OpenAI.

Each actual application wire turn is recorded independently. Do not insert a
parent caption's accumulated cost as another request receipt.

## Stored data

`ai_usage` contains anonymous event/context/parent UUIDs, event kind,
provider/model labels, operation, timestamps, state, safe HTTP status and a
closed per-model JSONB metrics array. It has no prompt, completion, reasoning
text, tool arguments/results, credential or user/channel identity fields.
Labels reject URLs, known credential forms and supplied configured secrets.
Metrics are bounded nonnegative native counters and finite amounts; absent or
invalid counters/prices remain absent rather than invented zeroes.

HTTP events distinguish a reserved attempt from a known receipt. CLI events are
sessions with up to 32 native model summaries. Actual CLI request counts are
kept when available; missing summaries do not become one request per session.
CLI family-based budget estimates are not treated as dollar bills.

The coverage sentinel is excluded from usage totals. Its original timestamp is
retained across restarts. It describes rollout, not historical reconstruction
or proof of provider-account completeness.

## Aggregation

`db.ai-usage/report!` uses one read-only repeatable-read snapshot, with an
inclusive start and exclusive end. PostgreSQL timestamp precision is accounted
for without changing caller comparisons at nanosecond boundaries.

Global event/session counts are distinct across expanded per-model summaries.
A multi-model CLI session can appear in several groups; those group counts
must not be added as unique sessions. Global totals include all groups even
when the displayed breakdown is limited to 200. Integral counters stay exact;
dollar amounts stay decimal.

Reported USD, estimated USD and unpriced events are separate. Native token
counter definitions can differ by provider, and cached/reasoning counters can
overlap other counters. These are recorded subtotals, not account invoices,
account entitlements or usage from other applications. Opaque external tool
services are not observable unless included in provider/CLI statistics.

The application supplies the trusted-human report command and reviewed frozen
public projection. See its `doc/AI_USAGE.md` for syntax and report semantics.
8 changes: 8 additions & 0 deletions doc/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@

## Unreleased

- Reserve anonymous durable AI usage rows before model HTTP requests and Gemini
CLI spawn. Refuse unrecorded inference, retain completed results if final
ledger accounting fails, and never retry paid work for bookkeeping. Cover
legacy xAI, Gemini image/video and agent sessions; bind anonymous command and
delegated-request contexts without changing the handler API. Add consistent,
bounded timeframe aggregates with separate reported/estimated USD, unknown
usage and an idempotent rollout marker. See [AI usage](AI_USAGE.md).

- Admit reply-scoped AI continuations only from successful, terminally delivered
owned answers. Keep closed routing metadata in the bounded command cache,
tied to its revision and actual same-channel reply IDs. Explicit commands
Expand Down
38 changes: 21 additions & 17 deletions src/yetibot/core/commands/agent.clj
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@
[yetibot.core.models.help :as help]
[yetibot.core.commands.alias :as alias]
[yetibot.core.handler :refer [record-and-run-raw]]
[yetibot.core.util.gemini :as gemini])
[yetibot.core.util.gemini :as gemini]
[yetibot.core.util.ai-usage :as usage])
(:import
[java.nio.file Files]
[java.nio.file.attribute FileAttribute]
Expand Down Expand Up @@ -544,22 +545,25 @@
(.put "GIT_CONFIG_KEY_2" "url.https://github.com/.insteadOf")
(.put "GIT_CONFIG_VALUE_2" "ssh://git@github.com/"))
(info "running gemini agent" (cli-bin) "in" (str workdir))
(let [proc (.start pb)
timed-out (atom false)
;; hard wall-clock cap: kill the run if it overruns
watchdog (future
(Thread/sleep (agent-timeout-ms))
(when (.isAlive proc)
(reset! timed-out true)
(kill-tree! proc)))
stdout (slurp (.getInputStream proc))
exit (.waitFor proc)]
(future-cancel watchdog)
(let [parsed (parse-json-raw stdout)]
{:response (redact (:response parsed))
:stats (:stats parsed)
:exit exit
:timed-out @timed-out}))))
(usage/capture!
{:provider "gemini" :model (model) :operation "agent"
:secrets [(gemini-key) token]}
(fn []
(let [proc (.start pb)
timed-out (atom false)
;; Hard wall-clock cap, including descendant processes.
watchdog (future
(Thread/sleep (agent-timeout-ms))
(when (.isAlive proc)
(reset! timed-out true)
(kill-tree! proc)))
stdout (slurp (.getInputStream proc))
exit (.waitFor proc)]
(future-cancel watchdog)
(let [parsed (parse-json-raw stdout)]
{:response (redact (:response parsed))
:stats (:stats parsed) :exit exit :timed-out @timed-out})))
usage/cli-metrics)))

;; ---------------------------------------------------------------------------
;; Discord thread plumbing (guarded; degrades to plain replies elsewhere)
Expand Down
156 changes: 156 additions & 0 deletions src/yetibot/core/db/ai_usage.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
(ns yetibot.core.db.ai-usage
"Private minimal AI ledger, with bounded transactions and no content fields."
(:require [cheshire.core :as json]
[clojure.java.jdbc :as jdbc]
[yetibot.core.db.util :as db])
(:import [java.sql Timestamp]
[java.time Instant]
[org.postgresql.util PGobject]))

(def coverage-id "00000000-0000-0000-0000-000000000000")

(def schema
{:schema/table "ai_usage"
:schema/specs
[[:event-id "varchar(36)" "PRIMARY KEY"]
[:context-id "varchar(36)"]
[:parent-id "varchar(36)"]
[:event-kind :text "NOT NULL"]
[:provider :text "NOT NULL"]
[:operation :text "NOT NULL"]
[:started-at :timestamptz "NOT NULL DEFAULT CURRENT_TIMESTAMP"]
[:finished-at :timestamptz]
[:state :text "NOT NULL"]
[:http-status :integer]
[:model-usage :jsonb "NOT NULL"]]})

(defn- table [] (db/qualified-table-name "ai_usage"))

(defn- transaction! [read-only? f]
(let [url (:url (db/config))
url (str url (if (.contains ^String url "?") "&" "?")
"loginTimeout=2&socketTimeout=3")]
(jdbc/with-db-connection [connection url]
(jdbc/with-db-transaction [tx connection {:read-only? read-only?
:isolation :repeatable-read}]
(jdbc/execute! tx ["SET LOCAL statement_timeout = '2000ms'"])
(jdbc/execute! tx ["SET LOCAL lock_timeout = '1000ms'"])
(when-not read-only?
(jdbc/execute! tx ["SET LOCAL synchronous_commit = 'on'"]))
(f tx)))))

(defn- jsonb [value]
(doto (PGobject.)
(.setType "jsonb")
(.setValue (json/generate-string value))))

(defn start!
"Persist first rollout coverage, before adapters or background AI start."
[]
(transaction! false
(fn [tx]
(jdbc/execute! tx
[(str "CREATE INDEX IF NOT EXISTS " (table) "_started_at_idx ON "
(table) " (started_at)")])
(jdbc/execute! tx
[(str "INSERT INTO " (table)
" (event_id,event_kind,provider,operation,state,model_usage)"
" VALUES (?,'coverage','system','tracking','coverage','[]'::jsonb)"
" ON CONFLICT (event_id) DO NOTHING") coverage-id]))))

(defn begin! [{:keys [event-id context-id parent-id provider operation
event-kind model-usage]}]
(transaction! false
#(jdbc/execute! %
[(str "INSERT INTO " (table)
" (event_id,context_id,parent_id,event_kind,provider,operation,"
"state,model_usage) VALUES (?,?,?,?,?,?,'pending',?)")
event-id context-id parent-id event-kind provider operation
(jsonb model-usage)])))

(defn finish! [id {:keys [state http-status model-usage]}]
(transaction! false
#(jdbc/execute! %
[(str "UPDATE " (table)
" SET finished_at=CURRENT_TIMESTAMP,state=?,http_status=?,"
"model_usage=? WHERE event_id=? AND state='pending'")
state http-status (jsonb model-usage) id])))

(def ^:private aggregates
(str
"COUNT(DISTINCT event_id) AS events,"
"COUNT(DISTINCT event_id) FILTER (WHERE event_kind='request') AS http_attempts,"
"COUNT(DISTINCT event_id) FILTER (WHERE event_kind='session') AS cli_sessions,"
"COUNT(DISTINCT event_id) FILTER (WHERE state='failed') AS failed_events,"
"COUNT(DISTINCT event_id) FILTER (WHERE state IN ('pending','unknown'))"
" AS uncertain_events,"
"COALESCE(SUM((u->>'requests')::numeric) FILTER"
" (WHERE event_kind='request'),0) AS http_requests,"
"COALESCE(SUM((u->>'requests')::numeric) FILTER"
" (WHERE event_kind='session'),0) AS cli_requests,"
"COUNT(DISTINCT event_id) FILTER (WHERE u->>'requests' IS NULL)"
" AS request_count_unknown_events,"
"COALESCE(SUM((u->>'usd')::numeric) FILTER"
" (WHERE u->>'cost_kind'='reported'),0) AS reported_usd,"
"COALESCE(SUM((u->>'usd')::numeric) FILTER"
" (WHERE u->>'cost_kind'='estimate'),0) AS estimated_usd,"
"COUNT(DISTINCT event_id) FILTER (WHERE u->>'usd' IS NULL)"
" AS cost_unknown_events,"
"SUM((u->>'input_tokens')::numeric) AS input_tokens,"
"SUM((u->>'output_tokens')::numeric) AS output_tokens,"
"SUM((u->>'uncached_tokens')::numeric) AS uncached_tokens,"
"SUM((u->>'cached_tokens')::numeric) AS cached_tokens,"
"SUM((u->>'reasoning_tokens')::numeric) AS reasoning_tokens,"
"SUM((u->>'neurons')::numeric) AS neurons,"
"SUM((u->>'images')::numeric) AS images,"
"SUM((u->>'seconds')::numeric) AS seconds,"
"COUNT(DISTINCT event_id) FILTER (WHERE operation IN"
" ('text','classification','agent') AND"
" (u->>'input_tokens' IS NULL OR u->>'output_tokens' IS NULL))"
" AS token_unknown_events"))

(defn- timestamp-ceiling [^Instant instant]
;; PostgreSQL stores microseconds. Ceiling both bounds preserves >= / <
;; comparisons even when the caller supplies nanosecond instants.
(let [remainder (mod (.getNano instant) 1000)]
(Timestamp/from (if (zero? remainder) instant
(.plusNanos instant (- 1000 remainder))))))

(defn- integral-counts [row]
(reduce (fn [result key]
(update result key
#(when (some? %)
(bigint (.toBigIntegerExact ^java.math.BigDecimal %)))))
row [:http_requests :cli_requests :input_tokens :output_tokens
:uncached_tokens :cached_tokens :reasoning_tokens :images :seconds]))

(defn report!
"One read-only repeatable-read snapshot; no raw events or actor identities.
Global totals include all groups, even when the model breakdown is bounded."
[^Instant start ^Instant end]
(transaction! true
(fn [tx]
(let [cte (str "WITH events AS (SELECT * FROM " (table)
" WHERE event_kind IN ('request','session')"
" AND started_at>=? AND started_at<?),"
"expanded AS (SELECT e.*,m.u FROM events e"
" CROSS JOIN LATERAL jsonb_array_elements(e.model_usage)"
" AS m(u)) ")
bounds [(timestamp-ceiling start) (timestamp-ceiling end)]
coverage (first (jdbc/query tx
[(str "SELECT started_at FROM " (table)
" WHERE event_id=?") coverage-id]))
totals (first (jdbc/query tx
(into [(str cte "SELECT " aggregates " FROM expanded")]
bounds)))
groups (jdbc/query tx
(into [(str cte "SELECT provider,u->>'model' AS model,"
"event_kind AS scope," aggregates
" FROM expanded GROUP BY "
"provider,u->>'model',event_kind"
" ORDER BY provider,model,scope LIMIT 201")]
bounds))]
{:coverage_started_at (:started_at coverage)
:totals (integral-counts totals)
:groups (mapv integral-counts (take 200 groups))
:groups_truncated (> (count groups) 200)}))))
4 changes: 3 additions & 1 deletion src/yetibot/core/handler.clj
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
[yetibot.core.chat :as chat :refer [chat-data-structure]]
[yetibot.core.util.command :refer [extract-command embedded-cmds]]
[yetibot.core.util.public-result :as public-result]
[yetibot.core.util.ai-usage :as usage]
[yetibot.core.interpreter :as interp]
[yetibot.core.models.history :as h]
[yetibot.core.unparser :refer [unparse]]
Expand Down Expand Up @@ -100,7 +101,8 @@
(binding [interp/*current-user* user
interp/*yetibot-user* yetibot-user
interp/*chat-source* chat-source]
(transformer parse-tree)))
(binding [usage/*context-id* (usage/context-id)]
(transformer parse-tree))))

(defn ->handled-expr-info
"Helper to transform a handled user expression (command) and return an info
Expand Down
3 changes: 3 additions & 0 deletions src/yetibot/core/init.clj
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
[clojure.stacktrace :refer [print-stack-trace]]
[nrepl.server :as nrepl]
[yetibot.core.db :as db]
[yetibot.core.util.ai-usage :as usage]
[taoensso.timbre :refer [info warn error]]
[yetibot.core.logging :as logging]
[yetibot.core.webapp.handler :as web]
Expand Down Expand Up @@ -43,9 +44,11 @@

(defn -main [& args]
(do
(usage/require-tracking!)
(welcome-message!)
(start-nrepl!)
(db/start)
(usage/start!)
(logging/start)
(monitoring/start)
(adapters/start)
Expand Down
Loading