TypeScriptPostgreSQLAIMindloft

Moving AI Out of the API Process: Config Fingerprints, Crash Ledgers, and 77 Audit Fixes

How Mindloft extracted LLM execution into a standalone PostgreSQL worker with keyless config fingerprints, separated prepared vs sending crash recovery, added OpenAI and Anthropic dialects with 503 fault injection, and closed 77 AI review issues.

Mindloft (formerly Brainlet / 枝间) originally ran its first AI integration directly inside the main API server process. That was fast to prototype: one HTTP request came in, and the API server read vendor credentials from its environment, called the model, billed credits, and wrote the result to the database.

It broke down in three ways almost immediately. Deploying a new API route killed half-minute document parses in flight. Keeping third-party model keys inside the API environment widened the blast radius of a web-facing process. Worst of all, a crash between sending the HTTP request and recording the charge left the system guessing whether credits had actually been spent — risking silent double-billing or free rides.

Between afbc690d (splitting out ai-worker-main), 66cc0395 / 628bc1a1 (provider dialects and 503 entry fault injection), and 763f0c2d (v0.4.0, clearing 77 review findings), we rebuilt the AI execution path around strict process and ledger boundaries.

Keyless Config Fingerprints Keep API and Worker in Lockstep

Extracting ramilo-ai-worker.service — which only exposes a loopback /ready probe — let us enforce two hard rules over PostgreSQL (plus SQLite and in-memory drivers for tests):

  • Zero model keys in the API process: The API handles auth, upload parsing, quoting, and job persistence. Vendor API keys do not exist in its environment.
  • Keyless config fingerprints (aiRuntimeConfigId): On startup, the worker hashes model name, pricing tier, budget policy, and endpoint mode into a public fingerprint published with every heartbeat. The API only accepts new jobs when a healthy worker matches its own fingerprint. During rolling deploys, in-flight jobs finish under the old fingerprint or refund cleanly via RECOVERY_REQUIRED instead of retrying against a different model.

Why sending Crashes Keep an unknown Ledger State

Process isolation alone does not prevent double-charging. The job state machine draws a bright line at the outbound network boundary:

  • prepared: The request has not left the worker. After a restart, it can be safely resumed or refunded.
  • sending: The HTTP call has crossed the wire. If the worker dies before receiving or persisting the response, recovery never auto-resends the model call. It retains an unknown cost marker and holds the concurrency slot for manual reconciliation rather than spending the user’s credits a second time.

At afbc690d, this behavior passed the workspace check (214 test files, 1,703 tests, 20/20 schema checks), real PostgreSQL 17 integration tests (8 files, 48 tests), and standalone bundle smoke scripts (smoke-ai-bundle.mjs, smoke-api-bundle.mjs, smoke-ai-worker.mjs) covering dual-worker claim races, prepared/sending crash recovery, cross-process cancellation, and SIGTERM draining.

OpenAI / Anthropic Dialects and 503 Entry Resilience

To swap providers via config, services/api/src/ai-model.ts (66cc0395) added RAMILO_AI_PROVIDER (openai or anthropic) and RAMILO_AI_BASE_URL, hashing provider directly into the worker fingerprint:

  • OpenAI dialect: Posts to /chat/completions with Authorization: Bearer and response_format JSON Schema.
  • Anthropic dialect: Posts to /v1/messages with x-api-key, top-level system, and tool_choice: { type: 'tool', name: 'brainlet_output' }, normalizing const, enum, and nullable types into input_schema.

Third-party Anthropic-compatible endpoints tripped us the next day: models with default thinking mode enabled (such as DeepSeek flash) rejected forced tool_choice. Commit 628bc1a1 added RAMILO_AI_DISABLE_THINKING to inject thinking: { type: 'disabled' } only when enabled, leaving native Anthropic and deepseek-chat untouched.

On the client side, the AI workspace loads asynchronously so it won’t slow initial map opens. Under headless Chromium fault injection (8 JS fault shots and 6 CSS fault shots, zero uncaught exceptions), we isolated AIEntrySurface and ai-entry-surface.css from the async AI chunk. Clicking AI opens the 42rem drawer immediately with a working close button (54×44px on 390px mobile) even if the main chunk hangs or returns 503. Forced full-page reload recovery blocks whenever the home screen holds unsaved quick captures or pending writes, and the task list separates tasks-loading, tasks-error, and tasks-empty instead of masking errors as an empty state.

Closing 77 AI Audit Issues and One Pre-Release Deadlock

Right after v0.3.0, a full audit (reviews/2026-11-22-ai-deep-review-remediation.md) logged 77 issues including 14 P0 bugs, resolved across five waves through v0.4.0 (763f0c2d):

  • Server heartbeat, trial abuse, and parsing: AIService.tick() lacked per-account try/catch, letting one oversized legacy doc stall the entire worker tick. Rate limits conflated active sending with disconnected unknown slots, and deleting an account cleared email uniqueness so users could re-claim RAMILO_AI_INITIAL_CREDITS. We added a has_live_work partial index, an ai_trial_claims table storing salted HMAC-SHA256 email digests, DB-driven now timestamps, and an $O(N)$ state machine in ai-docx-worker.ts replacing regex XML extraction.
  • Web drawer deadlocks: app.tsx read stale localStorage via AiStorage after drafts moved to IndexedDB v2; tab conflicts trapped requestClose() behind failedWrites > 0; undoing past round 0 left stale undo(app-0) entries in editor-session.ts that triggered VERSION_CONFLICT on Ctrl+Z. We isolated familyRevisions per record family, preserved a force-discard close path, and rewrote stale undo refs.
  • Mobile queue deadlock caught at the gate: Minutes before cutting v0.4.0, app-ai-integration.test.tsx timed out at 5000ms. In apps/mobile/native-lab/src/App.tsx, applyActiveAiDraft and revertLastAiApply nested runWithReply inside runSerializedStageTask, both chaining onto the same queue.current promise ref — outer waiting on inner, inner waiting behind outer. Moving runWithReply ahead of runSerializedStageTask(() => persistAndSyncStageAsync(...)) resolved the deadlock, bringing all 35 mobile test suites (236 tests) green.
✦

Comments

  • Loading…

Comments are reviewed before publishing; email is visible only to me.