Skip to content

feat(graphile-llm): add inference usage logging to metering plugin#1196

Open
pyramation wants to merge 7 commits into
feat/llm-billing-meteringfrom
feat/inference-usage-logging
Open

feat(graphile-llm): add inference usage logging to metering plugin#1196
pyramation wants to merge 7 commits into
feat/llm-billing-meteringfrom
feat/inference-usage-logging

Conversation

@pyramation
Copy link
Copy Markdown
Contributor

Summary

Adds inline INSERT INTO usage_log_inference to the LlmMeteringPlugin, writing to the parent database alongside the existing billing record_usage calls. This is Approach 1 from the metering architecture discussion — simple, SQL straight up, no new packages.

What changed

config-cache.ts

  • New InferenceLogConfig type (schema + table name)
  • New INFERENCE_LOG_MODULE_SQL query to resolve the inference log module's schema/table from metaschema_modules_public.inference_log_module
  • New resolveInferenceLogConfig() — checks if schema exists, queries module config, returns null if not provisioned
  • getLlmBillingConfig() now resolves inference log config in parallel with billing + API key

metering.ts

  • MeteringContext expanded with databaseId, actorId, inferenceLog
  • MeteringOptions expanded with embeddingModel, chatModel, provider (for log entries)
  • New InferenceLogEntry interface — typed payload matching usage_log_inference columns
  • New logInferenceUsage() — parameterized INSERT, graceful skip if module not provisioned, catch logs warning but never throws
  • meteredEmbed — logs after billing on both success and quota_exceeded paths
  • meteredChat — logs after billing on both success and quota_exceeded paths

metering-plugin.ts

  • buildMeteringContext now extracts actorId from jwt.claims.user_id and reads inferenceLog from the cached config entry
  • Passes embeddingModel and chatModel to MeteringOptions

index.ts

  • Exports logInferenceUsage, InferenceLogEntry, InferenceLogConfig

Design decisions

  • Parent DB only — writes to the database the request is connected to via withPgClient. Child DB / platform dual-write is a TODO comment for future work.
  • Graceful degradation — if inference_log_module is not provisioned, inferenceLog is null and logInferenceUsage returns immediately. If the INSERT fails, it logs a warning but never throws.
  • Cached resolution — inference log config is resolved once per database_id (5-min TTL) alongside billing config, so there's no extra query per request.
  • Quota exceeded logging — both embed and chat log status: 'quota_exceeded' events so the usage table captures denied requests too.

Depends on

Review & Testing Checklist for Human

  • Verify the INSERT column list matches the inference_log_module generator output (16 columns: database_id through error_type)
  • Verify logInferenceUsage never throws — the catch in both call sites + the try/catch inside the function itself should make this bulletproof
  • Confirm that resolveInferenceLogConfig correctly guards against missing metaschema_modules_public schema
  • Test with a database that has inference_log_module provisioned — verify rows appear in usage_log_inference after embedding/chat calls
  • Test with a database without inference_log_module — verify no errors, metering/billing still works normally

Notes

  • The provider field is not yet populated (always null) since the current LlmModulePlugin doesn't expose provider info on the build context. This can be wired in a follow-up.
  • Future: graphile-usage-log plugin for generic multi-category logging with routing (platform/app/dual) — tracked in #901

Link to Devin session: https://app.devin.ai/sessions/2b5a29d83d3f478e8d3d972653b4879c
Requested by: @pyramation

Add per-database billing integration to the graphile-llm package:

- config-cache.ts: LRU cache (5-min TTL, 50 entries) for billing_module
  metadata and API key resolution from app_secrets per database_id
- metering.ts: billing-aware wrappers (meteredEmbed, meteredChat) that
  call check_billing_quota() before and record_usage() after LLM calls
- LlmModulePlugin: exposes metering options on the build context
- LlmTextSearchPlugin: metered embedding with graceful degradation —
  when quota exceeded, skips vector path (text-only search continues)
- LlmTextMutationPlugin: metered embedding that throws QuotaExceededError
  on mutations (can't silently skip writing a vector the user asked for)
- MeteringConfig on GraphileLlmOptions: configurable meter slugs,
  estimated tokens, and skip toggle. Auto-detects billing_module.
- Uses Graphile withPgClient pattern for all billing SQL calls

Billing functions (check_billing_quota, record_usage) are resolved from
the tenant database's billing_module metaschema. When billing is not
provisioned, all calls pass through unmetered.
…Plugin

- Extract all billing/metering logic into metering-plugin.ts
- LlmModulePlugin, TextSearchPlugin, TextMutationPlugin are now pure
  (no billing imports, no metering context building)
- LlmMeteringPlugin uses AsyncLocalStorage to transparently wrap the
  embedder with quota checks — downstream plugins are unaware of billing
- Entity ID resolved via configurable callback (default: jwt.claims.user_id)
  instead of non-existent jwt.claims.membership_id
- Metering is opt-in: only loaded when metering option is truthy
- Add schema-existence guard in config-cache (checks metaschema_modules_public
  exists before querying billing_module table)
- Graceful degradation: missing schema, missing entity_id, or failed
  billing calls all result in unmetered passthrough
- LlmModulePlugin now exposes llmEmbeddingModel and llmChatModel on build
- LlmMeteringPlugin reads model names from build and uses them as default
  meter slugs (e.g. 'text-embedding-3-small' → billing meters table)
- Three-level waterfall: per-model → inference pool → universal credits
  (handled by billing module's category_meter field)
- Remove hardcoded 'embedding_tokens'/'chat_tokens' defaults
- Add docs/spec/llm-metering.md — full architecture reference for
  two-tier billing, model=meter slug convention, and waterfall
…user_module

The table was renamed from metaschema_modules_public.encrypted_secrets_module
to metaschema_modules_public.config_secrets_user_module. Also updated the
JOIN column from private_schema_id to schema_id to match the new schema.
…t length

Removed the configurable estimatedEmbeddingTokens option — token counts
are now estimated directly from the input text length (~4 chars/token).
No tokenizer needed since the billing system uses tokens as abstract
units and the credit_cost per model normalizes relative expense.
@devin-ai-integration
Copy link
Copy Markdown
Contributor

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment and CI monitoring

Adds inline INSERT into usage_log_inference table after billing
record_usage calls in both meteredEmbed and meteredChat functions.

Changes:
- config-cache.ts: Add InferenceLogConfig type and resolution from
  inference_log_module metaschema table (cached alongside billing config)
- metering.ts: Add InferenceLogEntry type, logInferenceUsage helper,
  and calls after billing in meteredEmbed/meteredChat (including
  quota_exceeded events). Add databaseId, actorId, inferenceLog to
  MeteringContext. Add embeddingModel, chatModel, provider to
  MeteringOptions.
- metering-plugin.ts: Wire databaseId, actorId, inferenceLog into
  MeteringContext. Pass model names to MeteringOptions.
- index.ts: Export new types (InferenceLogEntry, InferenceLogConfig)
  and logInferenceUsage function.

Gracefully skips if inference_log_module is not provisioned.
TODO: dual-write to child (generated) database for platform aggregation.
@devin-ai-integration devin-ai-integration Bot force-pushed the feat/inference-usage-logging branch from d2463b7 to df79e9e Compare May 19, 2026 20:54
@devin-ai-integration devin-ai-integration Bot force-pushed the feat/llm-billing-metering branch from 3c6b433 to 3a257e3 Compare May 20, 2026 03:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant