Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

How to use this book

The intent specs own product intent: principles, product specs and owner decisions. Linear tracks scope, work and acceptance. This book documents Rust owners, setup and proof. Code establishes what is implemented; it does not turn an old implementation into an approved product decision. The project owner’s latest explicit decisions take precedence. When an outcome and implementation disagree, Linear tracks the gap, and the responsible owner changes as the work lands.

QuestionCanonical owner
What are we building and why?Intent specs: principles, then the physician, Duet, connected-care and harness specs; Linear tracks the work against them
How should Duet look and read?Design language
Where is it implemented?Crate map, then the owning source file and tests
How do I work here?AGENTS.md and README setup
What has been proved?The scoped test/run evidence linked by each outcome; verification owns formal-design workflow; release and GCP own operational procedures

Find the implementation

AreaNavigation
Accounts, evidence, the doctor workspace and saved careDuet backend, security boundaries, privacy recovery
Patient screens and design referencesDuet UI
Invitations, consent and practice connectionsAccounts and practice connection
Physician client, sign-in and executionPhysician site
The physician clinical skill catalogskills/, read by agent-skills for harness; skills in physician chat
Public marketing sitePublic site
Coda’s Chrome extension and its EHR reads, Hint firstChrome extension
Gym cases, promotion and runscoda-gym AGENTS.md
Shared execution and product boundariesHarness spec, crate map
Feature models and their checksVerification
Captured Hint and FHIR adapter proofRecorded adapters
Synthetic patients for running CodaSynthetic patients
Builds, deployment and diagnosticsRelease, GCP, observability
Dev container setup, ports and storageDev container
Dev shell on an Apple silicon Mac without NixApple container

Keep ticket references, lists, status and acceptance tracking in Linear. This book describes maintained source owners, implemented behavior and operating procedures; it does not mirror the backlog. Product and runtime changes follow the agreed design and verification workflow.

Read the physician product as one workflow

Start with what the physician should experience, then follow that promise through the app and its runtime. These documents answer different questions:

Read in orderWhat it establishes
Physician spec and its decisionsThe agreed behavior: Today, the patient page, conversations, readings, work and communication, including capabilities not built yet.
Harness spec and physician siteThe guarantees left to execution, then the Rust owners and execution paths that implement parts of them. Recovery and scaling support the experience; they do not establish coverage of every product workflow.
Verification and the physician verification recipeThe boundary between graph/model checks, implementation checks and running-app readback. The current physician recipe exercises chat across a local scale stack with a fixed provider.
GCP staging and releaseDeployment. A deployed revision is not itself an accepted physician journey.

For the next implementation slice, use Linear’s current outcome and the physician spec together: choose a complete physician journey, identify missing server data and runtime guarantees, then verify the result through the app. Do not infer the next product priority from the latest infrastructure merge.

Connected-care behavior belongs to the connected-care spec. It does not merge the physician’s and Duet’s accounts, clinical state or runtime owners.

Retiring a surface

Fixtures, generated API contracts, published legal text and active verification work are not obsolete merely because product scope changed. Remove a runtime surface through its outcome with consumer and authority checks, not through a documentation cleanup.

Crate map

Every crate in crates/ is listed here, with the file where it starts and the chapter that covers its behavior. The module docs at the top of each entry file are the maintained description. When this table and a crate disagree, the crate is right and this table needs fixing. boundaries keeps Duet and the physician client from importing each other’s clinical crates. The Shared table below is the list of crates both products may use. One crate sits a level deeper: coda-sandbox, the agent sandbox tool, lives in crates/workspace-tools/sandbox/ and is listed under Tooling and guards.

Shared

CrateEntryOwnsChapter
uisrc/lib.rsCoda’s design, as a catalog of AI-native component families: tokens, icons, and each component’s look, motion, gestures, states and accessibility, with no product rules—
extension-popupsrc/lib.rsThe Chrome extension’s popup, built from ui: where the connection stands, in one line, and its one action. The extension’s worker owns the connectionChrome extension
coda-httpsrc/lib.rsRequest and stream mechanics with no schema knowledgeBackend architecture
gmailsrc/lib.rsPlain-text or HTML messages through the Gmail API or the Workspace SMTP relay, plus the intake primitive, the history.list cursor reader (src/history.rs). Products own the copy, the links, the durable cursor, the polling schedule and the effectsGCP
sprucesrc/lib.rsRead-only Spruce REST reader and change cursor. Products own the cursor store, the effects, and patient linking—
encodersrc/lib.rs, src/main.rsOffline BGE encoder binary that speaks both the Duet and the physician encoder protocols; tests/compare.rs checks it against the existing Python workers. No crate depends on itPhysician site
harnesssrc/lib.rsOne product-neutral bounded provider/tool loop and ordered turn in engine. Chords chat and reply revisions supply a frozen recipe and implement engine::Product. The harness builds each request, emits ordered events and exposes the shared skill_view tool for each job’s visible package. Products keep authority, effects and persistence. The harness reconstructs recovery from their admitted records and messages.Harness spec
agent-skillssrc/lib.rsValidates and reads the physician skill packagePhysician site
clinical-librarysrc/lib.rs, src/bin/clinical-library-migrate.rs, src/bin/clinical-library-pubmed-status.rsThe clinical library’s records and the nightly’s failure rules: article states, night outcomes counted from each night’s ledger, the stop rule, the slot lease and activation, with their Postgres schema; the night runner every source goes through, and the alerts the records raise; and its sources, starting with PubMed’s retraction and correction status read from NCBI’s E-utilities. Depends on no other local crateClinical library nightly
telemetrysrc/lib.rsShared tracing, logging, and OpenTelemetry setup for the Rust services; the testing feature starts the disposable Docker Langfuse and collector for ignored testsObservability

Duet (patient app)

CrateEntryOwnsChapter
duet-appsrc/lib.rs, src/roots.rsStandalone account entry, tab roots and connection controlsUI and design
duet-apisrc/lib.rs, src/main.rsAxum owner for identity, evidence, the doctor workspace, health context, privacy and the existing connection adapterBackend architecture, Patient front door
duet-clientsrc/lib.rsDuet caller over the generated client, adding the app-build headersBackend architecture
duet-wire (package duet_wire)src/lib.rs, generated API indexModels, operations and reference docs generated from the pinned coda-app OpenAPI plus Duet-owned additions. Regenerate with cargo run -p workspace-tools -- generate-duet-wire; do not edit outputs by hand.API generation
duet-healthsrc/lib.rs, src/acquisition.rs, src/outbox.rsOn-device health samples from HealthKit and Health Connect; durable acquisition records, the native source adapter contract and the transactional upload outbox (account fencing and the batch transport live in duet-client::health_upload)Duet backend
duet-notifysrc/lib.rsAlert permissionDuet backend
duet-stubsrc/lib.rs, src/main.rsLocal Duet stand-in for the emulator and tests (cargo run -p duet-stub)Release

Physician product

CrateEntryOwnsChapter
physician-appsrc/lib.rs, src/main.rsThe physician Dioxus shell: sidebar, Today, patient page, and readerPhysician site
physician-wiresrc/lib.rsThe physician read types, following coda-agents’ apiTypes.tsPhysician site
physician-clientsrc/lib.rsThe caller for the Node CodaServer and the sample serverPhysician site
physician-samplesrc/lib.rs, src/main.rsServes the page and the synthetic practice, plus auth and live chat routes; the physician-migrate binary runs the physician schema migrationsPhysician site
physician-demo-dbsrc/lib.rs, src/seed.rsIn-memory and browser turso_core SQLite demo store, build-time fixture seeder (seed_demo_db), chart search, and verbatim citation matchingPublic site
physician-demo-apisrc/lib.rs, src/routes.rsEmbeddable pure-Rust demo API router serving per-visitor turso_core sessions, crates/harness tool loops, physician-bus SSE, DemoTurnBudget, and dual-mode cloud + quantized candle GGUF inferencePublic site
physician-authsrc/lib.rs, src/bin/physician-auth-migrate.rsPhysician identity, membership, panels, and sessionsPhysician site
local-productsrc/lib.rsLocal subscription or API model execution; the physician runtime store, and hosted chat’s instructions and skill_view tool (physician_chat)Physician site
physician-bussrc/lib.rsTelling open physician pages to reread changed state, through a local bus or Redis fan-out. Lossy invalidation, not a durable work queuePhysician site
patient-worksrc/lib.rsThe patient-work dispatcher’s grouping windowPhysician site

Between the products

CrateEntryOwnsChapter
front-doorsrc/lib.rs, src/bin/front-door-migrate.rsInvitation, roster and consent adapter; standalone account authority stays in DuetPatient front door
mobilesrc/lib.rs, src/main.rsThe one Android and iOS shell, with an explicit physician or client mode. It is the only crate that mounts both apps.Release

Public website

CrateEntryOwnsChapter
public-sitesrc/lib.rsThe startup-rendered public marketing site, isolated from the physician runtimePublic site
observability-relaysrc/lib.rsThe staging hop from public-site’s /grafana/ mount to Grafana’s private load balancerPublic site

Tooling and guards

CrateEntryOwnsChapter
patient-banksrc/lib.rs, src/main.rsThe synthetic patient bank: chart authoring checks, the verified code catalog, the FHIR build and its validationSynthetic patients
ui-gallerysrc/main.rs, scripts/ui-gallery.shEvery ui family rendered with its states, each at its own address, the command that builds and serves it, and the browser test that opens every family. Nothing depends on it—
boundariessrc/lib.rsTests that keep product dependencies apart, retain the reference shipping clients, and hold both apps’ raw controls, hand-built cards and library overrides to a checked-in tableThis page
workspace-toolssrc/main.rsWorkspace command entrypoints, including generate-duet-wire, install-doppler, apply-migrations, the observability-drill routes, among them the staging Langfuse drills, and discord (read-only bot discovery, private verified channel and thread backups, offline inspect and search, and an offline publish that writes a static search site of consenting authors’ messages, in src/discord/); supporting checks and generator assets remain in scripts/Build, CI, and release
coda-sandboxsrc/main.rs, src/lib.rsThe agent sandbox tool: its config, doctor and status, worktree (seeded reflink worktrees), ci run (the CI spool client and the spool format the controller shares), ci-controller (the Firecracker CI controller the coda-ci units run), carry, and broker (the token broker that serves the container’s tokens from the host keyring) with its container clients credential and token. A root workspace member nested under workspace-tools, with its own flake (README) that builds only this crate from the root lockfile and ships the NixOS module services.coda-sandbox, which declares the container and CI it checks, so a host deploys it without the product flake. No crate depends on it—
androidsrc/main.rsBuilds the APK, opens the Android emulator (a window, or headless in CI) and runs one UI Automator class (cargo run -p android -- test [--headless] coda.duet.ModeShellTest)Release

Platform bindings

platform/ holds the native code that the Rust crates call. It is not a Cargo crate.

FileBound to
ios/HealthKitBridge.swiftduet-health
ios/NotificationBridge.swiftduet-notify
android/HealthConnectBridge.ktduet-health
android/NotificationBridge.ktduet-notify
android/HardwareKeyDispatch.ktmobile WebView key input, copied in by cargo run -p android -- build (build.rs)
android/ModeShellTest.ktThe UI Automator class that android runs

Chrome extension

extension/ holds Coda’s Chrome extension, which reads the practice’s EHR under the physician’s own sign-in, and its local sandbox bridge and tests. Its popup is the extension-popup crate; the rest is not a Cargo crate. Its README covers loading it and running a sandbox read.

Duet backend

duet-api owns Duet’s Rust service. It has identity, evidence, doctor workspace, health-context and privacy owners. A module’s presence does not establish the complete real-service journey.

Ownership

ResponsibilitySource owner
Startup, configured stores and hosted profilemain.rs, hosting.rs
Duet accounts and authenticationidentity.rs, session.rs; security boundaries
Evidence identity, ingestion authority, exact reads and pagingevidence.rs, evidence_entity.rs, evidence_routes.rs, evidence_paging.rs
Health context and producer grantshealth_context.rs, producer_routes.rs, producer_database.rs
For my doctor preparationworkspace.rs, doctor_routes.rs
Privacy receipts, replay and deletion archivePrivacy recovery
Schema and migrationsdatabase.rs, migrations/
Practice invitations and connection adapterAccounts and practice connection

Canonical evidence ingestion

EvidenceStore is the single mutation owner for canonical health evidence and clinical notes. It applies single and batch mutations under an account-locked transaction. The HTTP routes POST /api/canonical-evidence and POST /api/canonical-evidence/batch always write with device authority. Device authority may not create, correct, revive or remove the originals of the server-owned portal sources (epic, oracleHealth, healow, googleHealth). Those originals can be written only in process, through ingest_with_authority and a matching connector source kind and connection. Such refusals return the stable conflict code source_authority_refused. A record’s source kind, connection and note label are fixed when it is created.

  • A batch holds 1–100 items, each a bounded source object up to 2 MB. Each item runs in its own savepoint and gets an accepted or typed rejected outcome, so no item is skipped silently. An infrastructure failure aborts the whole batch.
  • Retrying an operation returns its first acknowledged address. A new operation identity must name the exact current revision.
  • measured_at or recorded_at is stored only from an RFC 3339 instant the source declared. Otherwise the stored date is unknown (NULL); receipt time is never used, and the literal stays in the payload. Patient-authored notes (Added in Duet) must carry an explicit instant.
  • operation: "delete" is an explicit removal by the owning source, fenced by exact revision and source generation. It keeps the base row and retained revisions, marks membership deleted and source_removed, and leaves earlier revisions readable as non-current citations. Privacy erasure (privacy recovery) deletes base rows and their retained revisions, and remains authoritative.

The Duet spec (D4) owns For my doctor and what it sends to a connected practice.

Duet must not import the physician local-product; the boundaries tests define this boundary.

API and clients

duet-client adds Duet client behavior over duet-wire. Generate wire types with cargo run -p workspace-tools -- generate-duet-wire; additive Rust operations live in openapi/additions.json. workspace-tools::wire orchestrates the composer, OpenAPI Generator and finalizer; their compatibility templates live beside those scripts. The generated API index and model/operation pages are regenerated with the Rust sources. cargo run -p workspace-tools -- generate-duet-wire --check compares sources, the manifest and documentation against fresh output. Use the pinned toolchain in nix develop.

The generator consumes the pinned OpenAPI source. The composer excludes the retired /api/sharing/ person-to-person routes and schemas used only by them. Practice-connection and doctor-workspace contracts keep their own owners. Regeneration clears generated source and documentation directories so removed operations cannot survive as stale files.

Persistence and migrations

The API never owns schema migration at startup. Run duet-migrate with DUET_MIGRATION_DATABASE_URL and DUET_RUNTIME_ROLE. The migration role and pre-existing runtime login must be distinct; the runtime role must not be a superuser, bypass RLS, create roles/databases, or inherit the migration role. The binary applies the Duet-owned chain first and optionally the front-door chain when FRONT_DOOR_DATABASE_URL is supplied. Do not replay the coda-app migration ledger to initialize this service.

Queries go through the typed database API, as AGENTS.md asks. Schema/account transactions use SQLx. src/sql/has_migration.sql is a schema-readiness query, not a CRUD pattern, and duet-migrate keeps the separate reference schema_migrations ledger. Ordinary CRUD belongs to the owning product’s typed entities; products do not share stores.

Proof

Release and GCP explain the build and hosted proof boundaries. Default tests may skip database-gated checks. The check-postgres.sh suites require a disposable PostgreSQL instance with pgvector and all five script URLs (MIGRATION_DATABASE_URL, PHYSICIAN_DATABASE_URL, FRONT_DOOR_DATABASE_URL, DUET_IDENTITY_TEST_DATABASE_URL, PHYSICIAN_RUNTIME_TEST_DATABASE_URL). They create/drop databases. The Duet owner suites, such as fresh_producers, public_budget and evidence_cohort, run against DUET_TEST_DATABASE_URL. These suites and image smoke tests establish their exercised persistence/startup paths, not sign-in, installed-client or clinical qualification.

Duet UI and design

The Duet design language is the design corpus. This page maps that direction to Rust; it does not maintain a second visual specification.

Direction and scope

The Duet spec owns what the app does. The app has two tabs, You and Shared, and opens on You. Shared holds For my doctor and the practice connection, with no People list or person-to-person notices. Use the corpus’s system sans, quieter solid surfaces and green direction.

The corpus’s mockups include states the spec lists as not decided, such as AI preparation, appointment context and sharing with physicians outside Coda. Where a mockup and the spec disagree, the spec is right. Physicians do not approve Duet’s wording.

The design corpus links the mockups, flow sheets and prototypes under “Mockups and interactive prototypes.”

Rust owners

OwnerWhat to inspect
duet-app::rootsTab roots, current copy and navigation
duet-app::account, duet-appStandalone account entry, You and Shared
duet-health, duet-notifyNative health and notification adapters; verify on installed clients under the owning outcomes

Release owns platform checks. A rendered screen or sample fixture does not establish saved state, consent, background delivery or real-model quality; verify the relevant journey through the backend and installed client.

Accounts and practice connection

Duet owns standalone patient identity; the practice connection has a separate invitation and consent boundary. A Duet account does not require an invitation. An invitation attaches the practice to that account; existing accounts and data are not migrated from the old app. The products keep separate data and authority.

Scope

The connected-care spec owns what a practice connection does, from invitation and fixed consent to leaving, discharge and re-invitation. The Duet spec (D4) owns the patient’s For my doctor, including sending marked records and notes to a connected practice.

Implementation

Rust ownerImplemented responsibility and boundary
duet-api::identityDuet identity store and authentication; standalone sign-up/session acceptance requires the whole journey
front-doorExisting account, invitation, connection, consent and premium adapter, with SeaORM/Postgres persistence; its account model is not a decision to make standalone Duet depend on practice admission
physician-sample::authPractice-authorized invitations; cross-practice access stays refused
duet-api and duet-clientJoin, consent and premium router adapters and client calls; the Duet binary does not mount the adapters
duet-app::account, duet-appThe standalone account root owns private access. It offers neither invitation enrollment nor a physician sharing control and does not request practice consent status

The adapter’s consent withdrawal/resume and paid-premium fields are not approved MVP behavior.

duet-api::main mounts Duet-owned identity and durable routes. Its optional front-door store is used by readiness; the separate duet-privacy-delivery operator also uses front-door journals. The physician auth router mounts invitation operations.

front-door-migrate owns the adapter’s schema; see Duet migrations and GCP migration jobs. The existing front_door_postgres.rs proves its invitation and link path.

Privacy and recovery

Rust has its own privacy receipt and replay implementation; the original Python service is historical reference, not its runtime owner.

ResponsibilityRust owner
Receipt types, journal interface, local file journal and replayprivacy.rs
Independent hosted journaljournal_gcs.rs
Archive behavior for privacy operationsprivacy_archive.rs
Persistence and deletion integrationdatabase.rs, privacy.rs
Configured hosted stores and startup checksmain.rs; GCP

Inspect these owners and their tests together when changing deletion or replay. A journal write, database mutation and restore replay are distinct observations; prove the complete affected path before claiming that deleted information cannot return. File-backed local proof does not establish independent hosted-journal recovery. Keep patient account deletion separate from ending a practice connection; see accounts and practice connection.

Isolated restore qualification

A database restore and a privacy replay are separate gates. Keep the restored Duet database disconnected from serving, subscriptions and outbound effects until both have passed. The operator selects a successful backup and retains the independent journal through the recovery cutoff; restoring the journal to the SQL backup’s timestamp would discard restrictions accepted after that backup.

duet-privacy-replay with no receipt arguments calls the product’s full reconcile_inventory path. Passing selected receipt IDs is targeted repair, not full restore qualification. Hosted replay requires the independent GCS journal and its authorized attached identity. An empty replacement bucket or a SQL-derived list cannot establish coverage of the independent inventory. Establish its provenance and completeness separately.

A synthetic rehearsal must retain a backup containing an account and its data, then record deletion or withdrawal in the independent journal. Restore the older SQL into an isolated target and replay the newer inventory. Check the stored restriction and refusal through the product owner, including repeat replay and missing-journal refusal, before any claim that deleted data cannot return. When an account held a Connected Care mapping, public.duet_deleted_identities retains front_door_account_id, and both duet-privacy-replay and startup reconciliation configure FRONT_DOOR_DATABASE_URL or FRONT_DOOR_URL with FRONT_DOOR_OPERATOR_TOKEN so AccountDelete replay idempotently ends front-door connections and scrubs front-door staging even when the front-door database was restored from an older backup. The physician database has its own schema, principals and readback checks; it does not import Duet’s privacy types.

GCP recovery owns disposable cloud targets and operator approval. Record backup identity, target, replay evidence and validation results together. A successful SQL restore operation, a local file-journal test or a ready process alone does not qualify hosted recovery.

Security boundaries maps identity and isolation; observability maps diagnostic content handling.

Security boundaries

This is an implementation map, not a security certification or a release gate readback. Account, privacy and hosted readiness require evidence from the complete affected journeys.

  • Duet identity and authentication live in identity.rs. Inspect the configured store and route admission in main.rs and durable.rs; do not equate an available identity type with a qualified provider sign-in journey.
  • Physician identity, practice membership and panel access have a separate physician-auth owner. Physician site describes its access boundaries.
  • Practice connection maps consent and invitation implementation. The existing withdrawal toggle does not define the current fixed-consent contract.
  • Runtime database roles and migration identities are separate. Backend migrations and GCP identify their owners and configuration checks.
  • Privacy recovery owns receipts, deletion and replay. Observability owns telemetry content handling. Neither is a substitute for access control.
  • Native device/session storage must be checked through the installed client and its platform bindings.

The hosted staging profile, /readyz, an IAP redirect, and a passing local test each prove only their boundary. Real authenticated member/nonmember access, sign-in, account isolation and privacy recovery need their own observed journeys.

The Chords physician site and its harness

The Rust page is the Dioxus client in physician-app, mounting into #main, consuming projections through physician-wire. physician-sample serves the page and the physician routes over the synthetic practice, with chat through the model execution described next; PHYSICIAN_UPSTREAM forwards physician routes to the Node server. Model execution is owned by local-product; api mode is opt-in and never runs without an authorized key. agent-skills reads the clinical skill catalog in skills/ for harness; physician chat loads it (see Skills in physician chat); the encoder runs the offline patient-text inference, and patient-work models the dispatcher’s grouping window.

The web build calls the API at a loopback ?api= URL when one is given, otherwise at PHYSICIAN_API_URL set at build time, otherwise at its own origin (under /physician when it is mounted there).

Product direction and proof

The physician spec owns product intent; each feature’s TLA+ model lives under verification.

Runtime schema cutover

The harness cutover changes the shape of the Chords runtime tables. It is a clean cutover: nothing reads earlier runtime data, so these tables are reset once. Rust staging holds only synthetic physician runtime data. Ordinary releases never reset data, and neither startup nor Store::migrate performs this reset.

This section states what the cutover needs. How staging stops writers, reaches the database, releases images and routes traffic is the infrastructure owner’s procedure and is not described here.

Before the site and the worker start, the settings in Model settings exist for both. Each refuses to start without them.

The reset discards chats, drafts, revision history, response feedback, attempts, command receipts, frozen execution inputs, provider cooldown, retained synthetic chart observations, practice source access, shared source adapter state, and patient source links and pull status. It also drops physician_runtime_migrations, the runtime chain’s ledger, so a reset leaves no ledger behind. It leaves account, session, practice, panel and front-door tables in place.

DROP TABLE IF EXISTS
    physician_runtime_chat_attempts,
    physician_runtime_chat_drafts,
    physician_runtime_commands,
    physician_runtime_conversations,
    physician_runtime_events,
    physician_runtime_migrations,
    physician_runtime_patient_source_status,
    physician_runtime_practice_source_access,
    physician_runtime_provider_quota,
    physician_runtime_recipes,
    physician_runtime_reconnect_commands,
    physician_runtime_skill_packages,
    physician_runtime_reply_drafts,
    physician_runtime_reply_revisions,
    physician_runtime_response_feedback,
    physician_runtime_revision_attempts,
    physician_runtime_source_adapter_state,
    physician_runtime_source_patient_links,
    physician_runtime_source_pulls,
    physician_runtime_source_versions,
    physician_runtime_sources,
    physician_runtime_workspace_practices;

After the drop:

  • The cutover’s migration creates the tables. A migration image from before the cutover creates the earlier tables again.
  • The synthetic charts are loaded again with physician-migrate load-charts, because the reset drops the source tables that hold them. See Staging synthetic charts.
  • A notification sent before the reset names work that no longer exists. The worker’s claim fails with error.type claim and the notification is gone; nothing sends it again, and the due-work read finds nothing of it.
  • The earlier site and worker do not work with the new tables, and the new ones do not work with the earlier tables.

An automatic deploy of the cutover commit does not perform the reset. If the reset is skipped, the runtime migration fails: its first migration creates each runtime table and stops at the first one that already exists. It runs in one transaction, so it leaves the runtime tables as they were. The physician-migrate job then fails, and the release stops at that failed migration.

runtime.sql is the first migration of the runtime chain. The chain records each applied migration in physician_runtime_migrations, like the physician-auth, front-door and clinical-library chains, and Store::migrate applies only the migrations not recorded there. A later schema change is a new migration in the chain. Existing permanent records are not rewritten to add fields. Once a practice holds real data, storage changes must neither refuse to start nor wipe it, as the physician intent requires.

Current execution paths

The page, identity, clinical execution and delivery each have an owner:

ResponsibilityOwner
Physician screens, navigation and command feedbackphysician-app, through physician-client and physician-wire
Sign-in, practice membership and panel accessphysician-auth, enforced at the site routes
Serving projections and accepting chat commandsphysician-sample and its live adapter
Physician model execution and conversation statelocal-product: Postgres runtime::Store for every accepted job
Waking accepted queued turns and executing themdurable and physician-worker, through Postgres NOTIFY and the worker’s due-work read
Telling open pages to reread changed statephysician-bus, using a local bus or Redis fan-out

Chat, saved drafts and reply revisions use the Postgres runtime::Store and the same worker locally and when hosted. The site requires PHYSICIAN_DURABLE_CHAT=1, PHYSICIAN_DATABASE_URL and PHYSICIAN_AUTH=required for this path. With PHYSICIAN_DURABLE_CHAT unset, a set PHYSICIAN_CHAT_TOPIC also selects durable chat: a deployed environment may carry only the topic until the rust-environments root is applied, and that root sets PHYSICIAN_DURABLE_CHAT=1. The topic is not otherwise read. A hosted site refuses to start without durable chat. With neither set, or PHYSICIAN_DURABLE_CHAT=0, a local site can render fixtures or proxy another server, but cannot execute chat. The worker selects API-key or local developer-plan Responses transport; credentials are worker configuration, outside the durable job. Local chat setup describes the plan grant, which refreshes before each request. Scaling across instances describes acceptance, recovery and fan-out.

Patients and the local practice

chart_load.rs is test tooling that loads the synthetic charts through their adapter, and physician-migrate load-charts runs it apart from any deploy. patients.rs is how a patient is read: the auth store says who belongs to the practice and whose panel they are on, and each source’s last pull says who they are and when their records were refreshed. With no database the practice holds no patients. scripts/local-practice.sh runs the practice on a local Postgres database with its worker and Valkey. The database persists between runs; the worker uses the same notes, windows, history and chart tools as staging.

Choose the proof for the claim

CheckWhat it can establishBoundary
Feature model checked by TLCEvery state the modeled steps reach keeps the agreed rules.Covers only the finite model; does not execute the app, its Rust owners or a clinical model.
cargo test -p physician-sample --test siteThe exercised Chromium journeys render and behave correctly against their test setup.Does not qualify every graph state or hosted dependency.
Local physician scale recipeReal site/worker binaries, Postgres and Valkey support the exercised cross-instance chat and recovery journeys.Fixed provider, proof sign-in and a local Postgres; not real model quality, mail delivery, Cloud Run or Cloud SQL behaviour.

Physician sign-in and practice access

physician-auth is one durable owner for who a clinic user or physician is, which practice they belong to, who holds panel-assignment permission, and which patients are on each physician’s panel. Sign-in is a per-user email magic token: the server issues a one-time token (24-hour TTL, stored sha256-hashed), and its verification mints one bearer session (idle for 12 hours, and never past 7 days after sign-in) with a revocation fence (sessions_ended_before) so deactivating an account ends every session it holds.

Access follows three concentric boundaries:

  1. Practice boundary (cross-clinic isolation): Any patient or workspace outside the signed-in user’s practice_id answers 404 — never 403 — and never appears in roster search.
  2. Clinic demographic boundary (same clinic, not on the physician’s panel): Physicians and staff in the clinic can search the clinic’s patient roster and read basic demographic information (display_name, birth_date, age_years, sex_or_gender, medical_record_numbers) on GET /patient-workspaces/{id} for other patients in their clinic, while clinical synopses, citations, chats, follow-ups, Today items, drafts, and commands remain omitted/404.
  3. Panel clinical boundary (Membership::Allowed): Full clinical workspace reads, Today items, chat snapshots, drafts, and commands require the patient to be assigned to the physician’s panel. Clinic admins, secretaries, and physicians holding the admin permission can assign or remove clinic patients on a physician’s panel via PUT /auth/panels/{physician_id}/{patient_workspace_id} (AuthStore::assign_panel).

The store is the AuthStore trait over SeaORM and PostgreSQL: physician-sample holds Arc<dyn AuthStore> and picks the Postgres store (connecting without applying migrations; the migration job owns schema changes) when PHYSICIAN_DATABASE_URL is set, process memory otherwise. With PHYSICIAN_AUTH=required, one Axum middleware guard resolves the bearer session before any physician read and enforces the practice, clinic-demographic, and panel boundaries before any patient read or command dispatch; the auth routes and /health stay open. The physician client in physician-app carries the bearer session on every read through physician-client. The session belongs to the browser, in localStorage, so every tab and a reopened Coda share it while it lasts. The client shows an email form followed by “Check your email” before any physician data renders. Clicking the email’s Sign in button removes the token from the URL, redeems it automatically, and opens Today without a code field or second confirmation. Used or expired links offer a new link; verification transport failures remain distinguishable from an invalid link. Local proof delivery redeems its returned token through the same client path without exposing it in the page.

The retained GKE deployment reference is infra/gcp/physician-runtime: one private GKE Autopilot cluster, one private Cloud SQL Postgres 16 instance with IAM database authentication (no database password), separate keyless site and migration identities, and PHYSICIAN_AUTH=required riding the site’s environment as configuration intent. Rust staging runs on Cloud Run under GCP deployment.

Practice creation and physician account management

Coda staff create practices and manage physician accounts through the dedicated staff setup surface (/auth/staff/* in staff_setup.rs), separate from the staging migration seed (PHYSICIAN_STAGING_ACCOUNTS) and the automated IAP rehearsal route (POST /auth/rehearsal). The routes exist only when PHYSICIAN_AUTH=required and CODA_STAFF_SETUP_TOKEN holds a secret of at least 16 bytes; when unset, /auth/staff/* answers 404, and missing or non-matching bearer headers fail closed with 401 after constant-time SHA-256 comparison (StaffSetupAuth in hosting.rs).

Each staff call sends Authorization: Bearer <CODA_STAFF_SETUP_TOKEN> against the hosted Chords origin:

  1. Create or verify the practice and its time zone: PUT /auth/staff/practices/{practice_id} with {"clock": {"mode": "real_time"}, "time_zone": "America/New_York"} (or {"clock": {"mode": "fixed", "unix_seconds": 1787846400}, "time_zone": "America/New_York"} for a synthetic practice). PracticeTimeZone validates the IANA identifier against the bundled time zone database before saving physician_practices, returning 201 Created on first creation, 200 OK when an existing practice matches (clock, time_zone), 409 Conflict when an existing practice holds a different clock or time zone, and 422 Unprocessable Entity when the time zone or practice identifier is invalid. GET /auth/staff/practices/{practice_id} reads back the saved practice clock, time zone, patient count, and accounts.
  2. Invite a physician: POST /auth/staff/practices/{practice_id}/invitations with {"email": "physician@practice.example", "display_name": "Dr. Example", "role": "admin" | "physician"}. Hosted delivery mails a single-use 14-day sign-in invitation link (https://<origin>/?code=<token>&email=<email>) and omits the token from the HTTP response (502 Bad Gateway if mail delivery fails); local proof mode returns the stored token and sign_in_path. Opening the link redeems the invitation through POST /auth/verify (AuthStore::redeem_invitation), creating the active physician_accounts record and minting a browser session.
  3. Create, deactivate, or reactivate an account: POST /auth/staff/practices/{practice_id}/accounts creates an active physician or practice-admin account directly ({"email": "...", "display_name": "...", "role": "admin" | "physician"}), returning 200 OK only when an existing account in that practice is active and matches both role and display_name (409 Conflict otherwise). POST /auth/staff/practices/{practice_id}/accounts/deactivate ({"email": "..."}) marks active = false, advances sessions_ended_before past every held session, and emits NOTIFY physician_authority so active browser sessions and event streams stop immediately while sign-in is refused, and POST /auth/staff/practices/{practice_id}/accounts/reactivate ({"email": "..."}) restores sign-in without reviving sessions ended by deactivation. Newly created physicians and practice admins start with an empty panel (0 patients) until patients in their practice are registered and assigned, and cross-practice requests return 404.

Each practice’s saved PracticeTimeZone (care.rs ConnectedCare::practice_moment) governs the local calendar date and time_zone returned on GET /practice-day, GET /today, GET /updates, and GET /patient-workspaces/{id}. Practice-scoped clinical source setup, recovery standing, and Spruce backlog state (GET /connections and /connections/{source_id}/* in source_setup.rs) persist in PostgreSQL (physician_practice_source_setups, keyed by (practice_id, source_id)), keeping Connected, RecordsImported, UpToDate, ReadFailed, and AccessLost distinct across server restarts while retaining previously linked chart records and reply drafts. Real-time practices (PracticeClock::RealTime) and production (CODA_ENVIRONMENT=prd) expose Coda-assisted onboarding (CodaAssisted) and answer 404 on /connections/{source_id}/simulate; synthetic fixed-clock practices (PracticeClock::Fixed) outside production additionally expose synthetic walkthroughs and fault simulation for verification.

Public demo profile and isolation

demo_session.rs and hosting.rs define an explicit public-demo profile (CODA_HOSTED_PROFILE=public-demo under CODA_ENVIRONMENT=stg or demo with PHYSICIAN_AUTH=required and PHYSICIAN_DATABASE_URL, or PHYSICIAN_PUBLIC_DEMO=1 in non-production local runs; production refuses to start and ignores demo opt-ins):

  • Dedicated synthetic practice and source boundary: physician-migrate seeds coda-demo-practice (DEMO_PRACTICE_ID, SYNTHETIC_PRACTICE_CLOCK) via seed_demo_practice. SimulationPractices::from_env registers DEMO_PRACTICE_ID (genai::Origin::Simulation), and physician-worker enforces SourceBoundary::SyntheticOnly (model::source_boundary(true, ...)) across chat turns, reply revisions, practice jobs, and visit preparation so non-synthetic patient sources are strictly refused.
  • Per-visitor zero-sign-in sessions: POST /auth/demo-session mounts strictly when is_public_demo and PHYSICIAN_AUTH=required hold (answering 404 under staging-preview, default PHYSICIAN_AUTH=required, open auth, and production). Each call creates an isolated non-admin demo-<uuid> physician account ("Dr. Hannah Alvarez (Demo)"), assigns DEMO_PRACTICE_ID’s registered synthetic patient workspaces to that visitor’s panel (Membership::Allowed), and mints a fixed-TTL bearer token (DEMO_SESSION_SECONDS, defaulting to 7200 seconds via CODA_DEMO_SESSION_SECONDS) so visitors never read another visitor’s chats or notes.
  • Ingress protection and bounded turn budgets: physician_sample::traced wraps HTTP ingress with IngressGuard::from_env at an 8 MiB default request body limit (SAMPLE_MAX_BODY_BYTES), classifying /auth/demo-session and /physician/auth/demo-session as RateLimitTier::AuthSensitive while keeping health probes exempt. Bounded-memory DemoTurnBudget caps (CODA_DEMO_SESSION_MAX_TURNS=20 per session, CODA_DEMO_IP_HOURLY_MAX_TURNS=30 per client IP per hour, and CODA_DEMO_DAILY_MAX_TURNS=500 daily across all demo sessions) guard message.submit, message.queue_send_now, work.resume, reply.revise, follow-up review-now/resume, and POST /dictation before writing Postgres work or calling upstream APIs, returning 429 Too Many Requests (code: "demo_turn_budget_exhausted") with Retry-After.
  • Forbidden demo mutations: Callers authenticated in DEMO_PRACTICE_ID receive 403 Forbidden on patient/colleague invitation endpoints (POST /auth/invitations{,/resend,/cancel}, POST /auth/colleagues/invitations) and practice-wide source setup mutations (POST /connections/{source_id}/{connect,assist,import,refresh,accept-backlog,reconnect,disconnect,simulate} and POST /connections/spruce/rollback/resolve), while GET /connections remains read-only.

Scaling across instances

A turn that finishes on one physician-sample instance has to show up on a stream another instance is holding open. physician-bus is the physician product’s fan-out. It carries workspace_changed, workspace_settled, and resync. resync is what a subscriber gets when it lags or the connection drops, and the Dioxus client refetches on that event. Sign-in and panel changes stay on the existing Postgres NOTIFY feed, which also fires for the migration job and for psql.

RedisBus is the fred client: TLS plus AUTH, PHYSICIAN_REDIS_URL as a rediss:// URL and PHYSICIAN_REDIS_CA_PEM as the Memorystore server CA. With PHYSICIAN_REDIS_URL unset, LocalBus keeps those events inside one process. That is the local and test path.

Hosted message.submit accepts the turn in Postgres. The transaction that saves it also sends pg_notify on the channel physician_work with {scope, input_id}, and nothing else. Postgres delivers a notification only when its transaction commits, so there is no accepted turn whose announcement failed. Try again, Resume, an accepted reply revision and a claim a stopping worker hands back are announced the same way (runtime/delivery.rs).

physician-worker holds one LISTEN connection and starts announced work at once (pull.rs). A notification sent while that connection is down is lost, so the worker also reads the due work every 10 seconds, and again each time it resubscribes: pending work whose retry delay has passed, and attempts whose lease ran out. A notification only names work. The claim in Postgres decides who runs it, so work heard twice, or by two workers, runs once, and work that is committed, stopped, replaced by a newer message or held under another live claim is not claimed. A worker runs at most four attempts at a time. Its HTTP listener serves /health and /readyz only; there is no route that delivers work.

When a newer message steers an executing answer, running calls finish within their 300-second deadline before settlement releases the old claim. Stop does not wait for running calls. Settlement makes the waiting message due at once and announces it in the same transaction, so a listening worker starts the answer without waiting for its next due-work read.

The worker publishes workspace_changed after each committed reply and each failed attempt, including a provider that cannot start and a claim that finds the turn already failed, and after each step the physician sees starts or returns, so an open page shows the steps while Coda works. A step’s notice never waits on the bus: the run only marks it pending, and a task of that attempt publishes, folding the notices that arrive during one publish into a single publish after it, so a slow bus neither delays the run nor drops the last step’s notice. A claim that finds the turn already failed is how a turn whose worker leases all ran out ends: the claim records the fifth failure and nothing is left to run. A held page then refetches and shows “Coda couldn’t finish”. Accepted work lives only in Postgres, so a turn accepted by a site instance that died, or announced while no worker was listening, is found by the next due-work read of whichever worker is up. tests/instance_loss.rs proves both against Valkey and Postgres.

An intentional Stop is work.stop. It holds that turn until work.resume or a newer message, including across a worker restart, and the site publishes workspace_changed so another open tab refetches. The snapshot shows Stop while the turn is still pending or active, and Resume once it is held. Each Stop press is its own command, so Stop after Resume holds the resumed run again, even before a worker claims it; each hold names its own run for Resume. Another press on work that is already held is answered as accepted and changes nothing. A newer message releases the hold and is answered, and the stopped run loses its Resume. A late model result cannot publish over Stop or over the newer message. An infrastructure failure does not end the turn by itself: the worker settles it using the harness failure classification, and a crash before that write leaves the attempt leased so expiry starts a successor. A run that marks no step for 600 seconds is recovered the same way: the worker cancels it, stops renewing its lease and settles nothing. The harness owns the five-failure ceiling. Reached limits and intentional interruptions never consume that allowance. At the run limit, the final request may leave a partial answer. Try again continues the work with a fresh allowance. A structured job keeps its handoff in the run record until its own finish operation publishes. tests/stop.rs proves Stop, the held readback after a worker restart, a second Stop after Resume, and one answer to a message sent while held.

Each published reply has a response id: the id its assistant message is saved with in the commit that publishes it, which names the attempt that answered. It stays the same across restarts, so it is the reply’s durable identity, the one feedback and evaluation refer to, and the team matches it to the attempt’s telemetry. Conversation::responses reads the published replies with their ids. A partial answer kept when a run reaches its limit is not a response and has none. The chat snapshot is a typed transcript (physician-wire), built by Conversation::transcript (runtime/transcript.rs): one exchange per piece of accepted work, with the messages that started or steered it, its steps and its answer. A finished answer carries its response_id and the attempt_id that published it, so an operator can match the reply to its telemetry. Each exchange carries in kept every partial answer a limit kept, in order, whatever its answer’s state now: Try again continues after that text, so it stays before the answer that finishes it. A kept partial carries no response id. Each answer keeps the ending its work had, read from that work’s own run history, and only the current work offers Stop, Resume or Try again, naming the run. A step is typed facts from the tool’s arguments and receipt, never a tool name or model prose, and each shown tool has one function from its call and result to a step, next to the tool (physician_chat::step). Skill reads, working notes, result pages and patient memory calls show no step. An exchange’s steps are either read, in the order Coda started them, or unavailable when one of its saved calls cannot be read as a step; that exchange still shows its messages, kept text and answer, the error is logged, and no partial list stands in for everything Coda did. A repeated message.submit under the same key is answered as accepted and runs nothing again; a different command under that key is rejected. Receipts belong to one physician, so another physician’s command under the same key is theirs alone. The session’s practice and physician scope every read and command, and the panel check answers 404 for a workspace the physician cannot see. A colleague with the same patient on their panel reads and changes only their own chats. tests/durable_access.rs proves a repeated submit runs one turn whose reply carries its response id, and that a colleague, an off-panel physician and another practice can neither read the chat nor Stop, Resume or write into it.

The worker listens on PHYSICIAN_WORKER_LISTEN_ADDR when it is set, otherwise on 0.0.0.0:$PORT when PORT is set, otherwise on 127.0.0.1:8791.

Chat acceptance requires durable chat, the database and required sign-in configuration together. A hosted site without durable chat refuses to start; local fixture pages remain display-only.

Reply revision runs in the worker. Drafts live in physician_runtime_reply_drafts, one JSONB row per practice, physician, workspace and reply, which Store::migrate creates from the fixed runtime baseline. GET and PUT /replies/{id} read and save that row; a save must name the current revision, and a PUT never creates a draft. reply.revise checks the session and workspace, then Store::accept_revision records the instruction, the saved text it applies to and the workspace’s current source revisions with their version, read in its own transaction, and the same transaction announces a reply_revision delivery on physician_work. The same command id returns the same acceptance and announces nothing new. A draft that is missing, belongs to another physician, has moved past the command’s expected revision, or already has a revision in progress refuses with 409.

The worker claims the draft and runs revision.rs through the shared harness recovery and execution path with the physician product’s frozen recipe. Revisions offer the shared working-note, fresh-window, history, skill and retained-result paging capabilities. The accepted draft owns its skill package and events; a successor keeps both. Notes are private work records, never saved reply text. History lists and reads this draft’s accepted physician instructions and completed model revisions under current authority. read_patient_sources answers from the attempt’s pinned sources, and only finish_reply_revision can publish the revised draft. Each model exchange is saved before the next one. A retry reuses the same instruction and base text, pins the newest sources when claimed, and restores the request count and usage already spent, so the shared backstops cover the whole revision.

Anything Coda is still working on takes in what arrives before it finishes, so nothing it produces rests on an older reading. A reply under revision is still a draft; its history is fixed only once something is said or sent. Store::commit_revision therefore compares the attempt’s source version with the workspace’s current one in the transaction that would publish, under the draft lock, the auth owner’s locks and a shared lock on the source version row. If they differ, nothing is published. The attempt records a SourceRefresh (from and to version, added, corrected with the earlier revision kept, and withdrawn sources), the draft re-pins, and the model receives a sources_changed result naming those references. It reads them and finishes again in the same run, under the same request bound; a catch-up is not a failed attempt. A finish whose context does not yet hold an exact read of every added or corrected source, at its current revision, gets sources_unread instead. If the chart keeps changing until the bound runs out, the revision stays held with its handoff in the run record and the saved draft is unchanged. The attempt’s sources stays what it claimed and its refreshes show what it could read afterwards, so the record lists only sources Coda could actually read.

Hosted sources live in physician_runtime_sources and physician_runtime_source_versions (runtime/sources.rs). Charts arrive through Store::record_chart and Store::record_chart_with_receipt, which land a patient’s delivery in one transaction, as one version, keeping saved records that a later pull omits and recording their candidate IDs in missing_candidates; explicit withdrawal goes through Store::withdraw_source. A delivery says what the source holds now, so an earlier revision delivered again becomes current. A site also imports the CODA_PHYSICIAN_SOURCE_SNAPSHOT file at startup through Store::import_sources when one is set; a correction or withdrawal is a new row, never a rewrite, and the workspace’s version moves only when what can be read changes. A revision identity is immutable within its workspace and candidate: different content or provenance under an already recorded identity is refused, including after correction or withdrawal. Replaying any identical historical revision is a no-op, so an older instance’s startup snapshot cannot roll back a correction or resurrect a withdrawal. Restoring a withdrawn candidate requires a previously unseen revision identity; opaque revision strings are not sorted to infer age. Catch-up checks compare the exact native content, hash and provenance as well as revision identity, not just a matching revision label. Store::record_source owns individual immutable revisions and is also used by the startup import. Projection prose and model output never become sources. Completion commits under the physician’s current session authority and the draft revision accepted with the command. If the physician saved a newer draft in between, the late completion is refused and their text stays. A failed attempt returns the revision to pending, due again after its retry backoff; the fifth failure ends the revision as failed. The draft GET returns revision_run, the latest accepted command id and its status (pending, active, completed, failed or superseded), so a failed revision is visible, not only stored. Accepting another revision moves the previous one, with its sources and every attempt’s records, into physician_runtime_reply_revisions in the same transaction, one row per earlier revision. The draft row holds only the current revision, so its size does not grow with history. A history row changes only when a superseded attempt’s worker records a late exchange, observation or failure; that record is appended to the archived attempt and cannot publish or alter the current draft. Each row carries a per-draft ordinal assigned under the draft lock, and Store::earlier_revisions reads one physician’s draft oldest first by that ordinal. The worker’s due-work read finds due revisions and expired revision leases just as it does turns.

The composer saves the physician’s unsent chat text through GET and PUT /physician-state/drafts/{workspace}/{chat}. With no chat open the page saves under the chat id draft. chat_draft.rs serves both. The draft is a row of physician_runtime_chat_drafts, keyed by practice, physician, workspace and chat, with typed text and revision columns, which Store::migrate creates from the fixed runtime baseline. Store::save_chat_draft checks the physician’s session and panel in the save’s own transaction. It inserts revision 1 only when the page names revision 0, and otherwise updates only the revision the page names. A stale save writes nothing and answers 409 with {outcome: "conflict", current}, so one instance’s save is read and fenced by every other instance. A missing session answers 401. A patient outside the physician’s panel answers 404, and another physician on the same patient has a separate draft. The fixture router answers 409 because its projections are read-only.

Each of Coda’s responses in a hosted chat carries a thumbs up and down, and once rated an “Add details” dialog with four reasons, a text box and its own Save. Feedback names a response by its response id, the response_id the snapshot carries on each of Coda’s published turns, so a rating stays on the reply it was given to. feedback.rs serves one route, PUT /physician-state/feedback/{workspace}/{chat}/{response}, whose body is the rating with optional details; it replaces both, so details never exist without a rating. Each rated response is a row of physician_runtime_response_feedback, created by the runtime chain’s second migration and keyed by practice, physician, workspace, chat and response, holding the rating, the details, the time of the latest save and a revision: 1 on the first save, one more on each later one. Store::save_feedback refuses an id that names no published reply in that chat, including a partial answer (404) and details over the length limit (422). There is no un-rate. The save checks the physician’s session and panel in its own transaction and answers 409 when the auth owner refuses. A missing session answers 401 and a patient outside the panel 404. The chat snapshot carries the signed-in physician’s saved feedback, with its revision, on each of Coda’s turns they rated, so a physician sees only their own feedback. A failed feedback read never withholds the conversation: the site logs the cause and the snapshot carries every turn with "feedback": "unavailable" and no turn’s feedback, and each response the page has neither saved nor read feedback on shows disabled thumbs saying “Couldn’t load your rating” rather than showing as unrated, while the rest of the chat works. Feedback an earlier snapshot read still shows, at its revision, and an open details dialog stays open with its unsaved words. A failed conversation read answers 503, with its cause logged, and the page keeps showing that chat’s last conversation, marked as not refreshed, until a reread succeeds. The fixture site has no feedback route and its turns carry no response id, so it shows no controls. physician-app/src/feedback.rs keeps one state per response, across chats: saved, saving or failed. It shows the highest revision it has seen, from any snapshot or a save’s answer, so an older answer never replaces a newer one. A thumb sends the new rating with the saved details, so a rating change keeps them; after a failed details save it sends those unsaved details instead, since they are what the physician last wrote. The dialog’s Save sends the details with the shown rating. A failed save says “Couldn’t save”, shows the saved rating again and keeps its draft to retry. A response takes one save at a time, which keeps going when the physician closes the dialog or leaves the chat.

Coda staff read feedback for evaluation with physician-migrate feedback, which prints one JSON line per rated response, in each chat’s order: the practice, physician, workspace and chat it belongs to, the response id, its rating, reasons, details, the time of the latest save, its revision and the rated response’s text, from the database at PHYSICIAN_DATABASE_URL. The response id names the attempt that answered, the link to that reply’s telemetry. It only reads. The output is clinical text, so it runs on an operator’s terminal and refuses to run as a Cloud Run job, where stdout would reach Cloud Logging. No HTTP route serves feedback to anyone but its author. tests/feedback.rs proves both: the author’s saves, snapshot readback and refusals over HTTP, a snapshot that keeps the conversation when a feedback row can’t be read, and the staff read’s rows, its refusal as a Cloud Run job and the cause it prints when the database is unreachable.

composer.rs holds the page’s draft state as pure, unit-tested transitions: autosave, one save in flight per draft, and the conflict choices, where the physician either retries over exactly the revision shown or takes the newer text. A bare or malformed 409 is an ordinary failure and never authorizes an overwrite.

The Send button and Cmd/Ctrl+Enter share one path. Acceptance removes only the submitted text, and the saved draft is cleared only over the revision that save produced, so newer text from another tab stays.

local_draft.rs keeps unsent text across a reload of the same tab, in sessionStorage only.

PHYSICIAN_SYNTHETIC_REPLY=<patient workspace id> turns on a synthetic reply source in synthetic_reply.rs. It is off by default and applies only to a signed-in physician of the synthetic practice (roger-synthetic-practice) on that patient. The workspace read then carries one fixed-ready reply with a stable server-owned id and non-PHI wording. If the physician has no draft for it, the site opens revision 1: through Store::open_draft_authorized, which holds the physician’s session, account and panel locks in the insert’s own transaction. Opening again, from any instance and concurrently, keeps the saved text and revision history. PUT /replies/{id} and reply.revise still refuse a reply that has no opened draft, and nothing is created from a browser payload. The reply card shows the saved text, its exact draft_revision and the latest revision run’s status: pending, active, completed, failed (the saved draft is unchanged) or superseded (a newer saved edit won). Ask Coda to revise names the revision on screen. The hosted worker announces workspace_changed after completing or failing an attempt, and the page rereads the workspace; a missed notice is recovered by the existing resync after the bus reconnects. The card does not offer Send to the patient, and closing it is not supported in this mode. With the switch off, no reply appears.

GET /patient-workspaces/{id} lists the signed-in physician’s runtime chats for that workspace, newest activity first, each titled by its first physician message (cut to about 60 characters). Durable chats come from Store::chats over physician_runtime_conversations, scoped by practice, physician and workspace. Postgres orders them by latest activity, then chat id, before taking the newest 200, so a chat that just got a message lists however many older chats the workspace has. The page’s New conversation button, in the Conversations sidebar and the empty Conversation region, opens a new chat-… id. The navigation owner keeps ?patient= and ?chat= aligned with the selected conversation, including sidebar selection and patient changes, and removes both when leaving the patient page. A chat is listed after a reload once its first message is accepted.

Spruce message matching and reply editing

matching_reply.rs and physician-app/src/matching_reply.rs serve practice-scoped unmatched Spruce routing (GET /spruce-matching/messages, GET /spruce-matching/filtered, POST /spruce-matching/messages/{message_id}/confirm, POST /spruce-matching/messages/{message_id}/leave-unlinked, POST /spruce-matching/filtered/{message_id}/this-is-a-patient, and POST /spruce-matching/unreadable/{message_id}/done) together with patient-scoped Spruce reply cards (GET /patient-workspaces/{id}/spruce-replies, GET /patient-workspaces/{id}/spruce-replies/{conversation_id}, and command routes for saving a private draft, requesting a Coda revision, restoring the physician’s version, choosing a newer Coda proposal, recording a clipboard copy, closing with no reply needed and undo, moving a wrong-patient conversation and undo, and completing a disconnected-channel card), backed by runtime/spruce_matching.rs and runtime/reply/proposals.rs. Messages to match places clinically urgent unmatched messages (Now) ahead of ordinary items, filters suggested patients to the signed-in physician’s panel (Membership::Allowed) without numeric confidence scores, offers sender address confirmation (remember_sender) across both single-suggestion and candidate-list confirmations, and drives Choose another patient and Wrong patient? through practice-scoped /patient-roster search so failed lookups state explicit unavailability rather than reporting no matching patients. On Today and on the patient page, reply rows (Review reply) and Spruce reply cards name the channel sender rather than attributing incoming messages to the linked patient, keep messages and proposed reply text on one observed version while newer arrivals show Coda reviewing, pin the physician’s expected version on first edit while offering newer Coda proposals (Choose update) without overwriting edits, display other physicians’ copy attributions until a practice message is observed on the channel, keep linked messages visible on the destination chart during an active wrong-patient Undo window without leaking origin details, and withhold reply text once a wrong-patient move settles.

Patient follow-ups

follow_ups.rs and physician-app/src/follow_ups.rs serve durable patient-page follow-up commitments (GET and POST /patient-workspaces/{id}/follow-ups, PUT /patient-workspaces/{id}/follow-ups/{follow_up_id}, and command routes for review-now, stop, stop-and-discuss, resume, complete, cancel, and resolve-cannot-restart) backed by runtime/follow_ups.rs. Every mutation checks current panel membership (Membership::Allowed), persists under an idempotent CommandKey, and returns the saved follow-up row; failed mutations surface "Not saved" and keep unsaved edits in place. Review now marks the follow-up due immediately and queues a patient chart review; Stop and discuss holds the follow-up and opens a durable patient conversation seeded with that follow-up’s context while keeping the follow-up held until Resume (answering "Not saved" if starting the discussion conversation fails); open follow-ups offer Cancel follow-up; and recurring follow-ups in CannotRestart offer New date, Complete, or Cancel.

The physician site sets cpu_idle = false so the Redis subscriber and the Postgres listener keep running between requests. The worker also sets cpu_idle = false and keeps one instance up, because its listener, its poll and its lease renewals run outside any request. Duet has no Redis instance and no worker.

nix develop provides valkey and Postgres, which is all the physician scale tests need.

Skills in physician chat

Chat in physician-worker offers skill_view, working notes, fresh windows, history and result paging, together with search_patient_information, read_patient_sources and the patient memory tools. Discovery searches retained source content, decoded text and metadata within the authorized workspace. A blank query browses records. The model receives references and dates on demand and opens a specific revision for evidence. A changed or withdrawn revision requires a new search. Large reads return exact UTF-8 passages with a continuation into the same revision, including its decoded text. Local developer-plan chart calls are restricted to the synthetic bank. The physician site loads its skill catalog from PHYSICIAN_SKILLS_DIR at startup. A local site defaults to the workspace catalog. Hosted admission requires a packaged catalog. The site saves the package with accepted work so each attempt or replacement worker opens exactly the bodies and resources named in that work’s index.

Each model request carries the physician-owned system prompt followed by the catalog metadata: names, descriptions and resource paths, but no bodies. Then come the skills the job loads at its start, each in full: chat loads patient-record-retrieval, a reply revision loads none. Every Chords job lists the whole package. The accepted work retains that exact package and recipe. The model opens an approved skill by name. An optional file_path opens a registered supporting resource. The exact body is retained; large results use the shared preview and range reader. An unknown tool or malformed arguments come back to the model as {"executed": false, "error": ...} without running; an unknown skill comes back unavailable. An unknown skill name also returns the names of the skills the package has. A bad call does not stop a valid read in the same turn. A skill is guidance only; it grants no tool, patient read or action. The Responses request carries an opaque cache key scoped to the conversation.

Chords uses the shared run budgets. Each work retains one frozen recipe. A provider dispatch references saved items, records its new input or send-time projections and carries the IDs of newly included physician messages. Recovery reconstructs the exact request from those parts; a transport retry records a separate attempt to send it unchanged. New steering or source feedback makes a new request. A large source result stays with the work and can be read in pages.

Chat and revision events are appended to physician_runtime_events, scoped to their product owner and attempt. Status, revision, accepted session and attempt leases use typed control columns. Appending execution evidence does not rewrite authored history; status transitions update their own control state. Readback and recovery join the event rows to their attempts; archiving a revision keeps those same rows, including evidence that arrives late.

The worker streams provider events through the shared Responses adapter. The run record retains usage and completed messages; reply fragments use the live-text callback and Chords neither saves nor displays them. Chords publishes the assembled whole answer. The provider’s silence timeout measures gaps between complete events, so a stream that stops making progress can retry within the run before an answer is published.

Hosted chat supplies its retained authored messages to the harness’s shared history tools. The model can list in either order, search exact text and read a message in character chunks. List and search previews leave the stored originals unchanged; each chunk carries its original message identity, offset and full length. Result paging also applies to history reads, under the same current physician authority.

Chat and reply revisions read and change the patient’s memory through list_patient_memory, read_patient_memory, search_patient_memory, add_patient_memory_note and edit_patient_memory, and both instructions carry the same paragraph on memory. The patient is always the run’s authorized scope. The store sets a note’s time and number, and the run sets its work, its call and the physician message the note comes from: the newest message of a chat’s work, or a revision’s one instruction. The model sets none of them. A note keeps the model’s quote on one line.

The summary, the direction, the person page and each subject page are stored as the markdown text exactly as the model wrote it, one row for each version, and code gives no meaning to the text’s structure. edit_patient_memory names a file by its path and takes a list of edits: create, replace, append and delete. A replace names text that is in the file exactly, in one place, and changes only that text. An edit that cannot apply is left out with its reason, and the others are saved as one new version. A log day is generated from its notes and the rounds marks on every read.

Patient rounds are the regular pass that tidies the summary, the direction and the pages. rounds::run runs one patient’s rounds on the background role with no physician present. It reads memory and the chart with the same read tools and writes with the same edit_patient_memory. A finished run saves a rounds mark. A run that stops early saves none, and what it wrote stays. Nothing schedules rounds: the physician-rounds command runs one patient once, and the code marks with Infra seam: what production must supply around a run.

Memory loads once per conversation. Every request and fresh window of a chat, or of a reply and its revisions, opens with one developer message that Store::memory_at_start builds from the patient’s memory as the conversation started: the summary up to 16,000 characters, cut at a line end; the whole direction; and the whole notes saved since the last finished rounds run started, newest first, up to 8,000 characters. A line names what did not fit and the file that holds it. A patient with no summary, direction or note then gets no message. A chat starts when its first physician message is accepted, and a reply when its first revision is accepted. The memory tables are insert and select only, so the message is read again from rows saved before that second and is the same text each time; no copy is stored. It is the first item, before any earlier conversation, and the instructions stay the same for every patient. Memory saved later reaches the next conversation, and a run reads it with the memory tools.

Model settings

Every enabled Chords runtime requires CODA_<ROLE>_MODEL, CODA_<ROLE>_EFFORT, CODA_<ROLE>_CONTEXT_WINDOW_TOKENS and CODA_<ROLE>_INPUT_LIMIT_TOKENS for CHAT and BACKGROUND. Missing or invalid settings refuse startup. Hosted revisions select the background role. The site freezes each recipe when it accepts the work: model settings, system prompt, tools and skills. Workers read that saved recipe through retries, steers and recovery.

Local process settings and the product’s hosted Doppler configuration own the values. The synthetic stack declares its settings in scripts/physician-scale-stack.py.

The shared token backstop counts output plus input not reported as cached. Missing counts use the existing context and content estimate; recorded provider usage stays distinct from those estimates. Billing belongs to the provider’s usage records. The budget survives recovery through the product’s retained run events.

The working window is separate from the provider input limit. The harness estimates the first request and each fresh window, then uses reported input and output usage plus an estimate for added content. It requests a handoff near its named threshold, reserving room for the reply. Chords sets no output-token cap. Dispatch events retain those counts. When context is full, or the provider refuses it as too long, the harness opens a fresh window from exact accepted inputs and pending results. The fresh window carries the exact text of the newest note saved in this work, says when work done after that note is not in it, and points to earlier notes in the order saved. A refused fresh window gets one retry with smaller pending results, then the run is held at a limit. The shared response transport bound is separate from context pressure.

Large tool results appear as short previews of their start and end. The exact original stays in the product’s run record. read_tool_result reads a byte range or finds a literal match under current authority. Previously sent results stay unchanged within their window, and a partial read never establishes full source coverage. The harness owns presentation bounds; those bounds do not reject writes.

Chords publishes only the answer the model hands in through finish_answer, after checking the saved candidate, current lease, input revision and physician authority. Earlier tool narration stays in the run record. An empty ordinary model turn gets feedback, and so do plain text, a finish beside other calls and a finish without its Basis. citations.rs checks each citation’s label against the versions this work’s reads gave and saves the answer without labels, with each citation’s version, every place its optional quotes occur in the text the model is working from, and the Basis, as the citations spec describes. A description Coda hands in, in its own words, is saved with the finish only for a version the answer or the Basis cites, at most one per version; any other description is dropped and never refuses the finish. At a run limit, Chords keeps the handoff text, without labels, as a partial reply and offers Try again. A revision that reaches its limit stays held with its handoff in the run record. Only its explicit finish operation can update the draft.

Retention

The physician runtime keeps clinical history and the evidence Coda can learn from; only disposable copies expire, after 90 days. HIPAA sets no single record period, so clinical history follows the practice’s own record schedule. No automatic deletion runs until that schedule exists. The rows below are the hosted Postgres copies, plus the copies kept outside the runtime.

CopyOwnerPurposeRule
Conversations (physician_runtime_conversations)runtime::StoreClinical history: what the physician asked and what Coda answeredKept under the practice’s record schedule. No automatic deletion.
Chat drafts (physician_runtime_chat_drafts) and reply drafts (physician_runtime_reply_drafts)chat_draft.rs, reply.rsThe physician’s unsent text; for replies, the current revision with its instruction, base text, pinned sources and attempts with their source refreshesKept under the practice’s record schedule, including a reply’s last revision when no later one replaces it.
Response feedback (physician_runtime_response_feedback)feedback.rsEvaluation evidence: each physician’s rating and details on one of Coda’s responsesKept with clinical history. No automatic deletion.
Earlier reply revisions (physician_runtime_reply_revisions)reply.rsLearning evidence: what Coda could read, what it read and produced, and what the physician changedAppend-only: a superseded attempt’s late records are added, nothing is rewritten; kept with clinical history until the de-identified learning export exists.
Patient sources (physician_runtime_sources) and their versions (physician_runtime_source_versions)sources.rsEvery revision of each source a reply revision could read, and each workspace’s observation versionAppend-only: corrections and withdrawals are new rows. Kept with clinical history, since pinned and refreshed revisions on drafts and earlier revisions refer to them.
Each source’s last pull (physician_runtime_source_pulls)sources.rsPatient directory identity per source, when a source last delivered a complete chart (or null when only partial records have landed), which “Records as of” reads, plus candidate IDs omitted on that pullOne row per patient and source; partial pulls preserve any prior complete timestamp and a later complete pull replaces it.
Source patient links, practice access, pull status, reconnect commands and shared adapter state (physician_runtime_workspace_practices, physician_runtime_source_patient_links, physician_runtime_practice_source_access, physician_runtime_patient_source_status, physician_runtime_reconnect_commands, physician_runtime_source_adapter_state)source_status.rsPractice workspace ownership, stable source-patient links per practice, practice-level connector access state, each patient’s latest pull outcome and preserved last good read time, durable execution state and receipts for reconnect commands, and shared adapter connector state across instancesKept with the practice’s patient records; status, access and adapter state rows update as pulls and reconnects occur.
Practice source setup (physician_practice_source_setups)physician-auth, source_setup.rsEach practice’s per-source connection standing, Spruce backlog decision, and retained recovery stateOne row per (practice_id, source_id); updated in place as standing changes, with linked chart records and reply drafts kept on disconnect.
Execution records (attempt records on conversations and drafts)runtime::StoreModel requests and responses, tool reads, failures, and the evidence retries and recovery replayKept with the record they belong to.
Command receipts (physician_runtime_commands)receipt.rsIdempotency: a repeated command id returns the same answer; a different command under that id is refusedFull command for 90 days from accepted_at, then reduced to a salted digest.
Langfuse tracesObservabilityDebugging model runsThe Langfuse HIPAA cloud project keeps them for 90 days.

Command receipts duplicate input the runtime already keeps: a chat message lives in its conversation, and a reply instruction lives in its draft or archived revision. After 90 days, Store::compact_receipts replaces the stored command with {"salt", "sha256"}: a random salt kept on the row, and the SHA-256 of that salt followed by the command’s canonical JSON (keys sorted). A repeated command still gets its original answer, and a different command under the same key is still refused. The hosted site’s recovery sweep runs compaction on start and then hourly, in batches of 100 receipts, at most 2,000 per run.

Sources carry their own limits. Under Google’s Workspace user-data policy, Gmail-derived content cannot train shared models, even when it is de-identified or rewritten. Duet’s data stays with Duet’s owners; its separate consent rules apply, and nothing here reads it.

Public site

crates/public-site is the Rust public marketing site and static showcase builder. The live server serves coda.dabney.moe (and staging.coda.dabney.moe behind IAP in staging), while static exports via scripts/build-pages-site.sh (default ORIGIN=https://dabney.moe) power subpath showcases such as dabney.moe/coda/. It is separate from the physician runtime and Duet: no database, physician accounts, model execution, or clinical types are introduced by the site. Sign-in exists only where PHYSICIAN_APP_URL is configured: that one setting mounts the same-origin /physician/ proxy and renders the nav’s Sign in link. Production leaves it unset, so production offers no sign-in and /physician/ is an ordinary 404.

Application contract

The application design is Dioxus route components prerendered at startup, served by a stateless axum binary. The sitemap lists only current documents; archived versions stay reachable from their policy pages. /physicians and /api/physician-waitlist are 404.

Startup builds the page/asset tables and their identity, gzip and Brotli representations once; requests do not render Dioxus or query a database. The server serves content-addressed immutable assets and HTML with bounded public/shared-cache lifetimes, encoding-specific ETags, conditional requests and bodyless HEAD responses. Every response carries Strict-Transport-Security: max-age=63072000. Motion is /homepage/site.js on / and /duet. It also paints the landscapes, and the browser proof fails if the hero pointer jumps instead of gliding. The other stylesheets and scripts are layout or fallback only, never motion, and tests/stylesheets.rs holds stage.css and noscript.css to that: stage.css reserves and scales each product frame before the script runs (it then sets the same values inline), noscript.css reveals content when scripts are disabled, and chrome.js floats the nav after 8px of scroll. Reduced motion is decided by site.js at load.

Chords, the physician product, and Duet, the patient product, are presented the same way. The Chords lockup on / introduces the physician product as the Duet lockup introduces the patient one: each product’s mark and wordmark (brand/chords/, brand/duet/) with its audience, in the product lockup styles, through one component (ProductLockup in src/pages/brand.rs). The footer’s link columns are Chords, Duet and Coda Health: each product’s pages under its name, and the company’s contact, privacy policy and terms, which cover the site and both products, under Coda Health.

The Duet story (src/pages/phones.rs) shows Duet on / and /duet as one story across three phones. It reuses site.css phone hardware and the stage scaling and landscapes site.js applies to every frame, but its classes (duet-story, ds-*) are its own, so the phone loop in site.js never binds to it. Its styles are css/duet.css, every selector scoped to .duet-story (tests/stylesheets.rs checks this); its motion is homepage/duet.js, which plays only while the stage is on screen. The markup is the story’s last frame, which reduced-motion and no-script visitors see.

Every page shares chrome.css, which owns the tokens, type, page opening, cards, nav and footer. Pages belong to one of two families (Route::shell) that differ in the stylesheets they load and the layout around their content. / and /duet add site.css, the motion script and the Duet story. Every other page, the legal documents and not-found, adds css/document.css, a hand-written stylesheet with its own reset and named classes for those pages, and sits in the .page layout, which keeps the footer at the foot of a short page. A trailing slash is removed with a 308 that keeps the query.

Static export mode (public-site --export-dir <dir> --base-path <prefix> --origin <url>) renders the same startup pages, 404.html, sitemap.xml, robots.txt, .nojekyll, and hashed/raw assets to disk for subpath hosting such as https://dabney.moe/coda/ or GitHub Pages (with the architecture book and WASM SQLite physician demo built alongside by scripts/build-pages-site.sh with ORIGIN defaulting to https://dabney.moe). When physician-app runs with PHYSICIAN_DEMO_DB="./demo.sqlite", it boots live-first against the configured API base (/coda/physician/api on /coda/physician/ or a loopback ?api= override): it probes POST /auth/demo-session, switches to Live harness with an ephemeral in-memory Bearer session and SSE updates when available (hiding Sign out and invitation controls, and showing Live turn limit reached with Use local chart preview on 429 demo_turn_budget_exhausted), and falls back to Local chart preview over browser-side pure-Rust turso_core SQLite + IndexedDB (physician-demo-db) whenever no live backend answers or the visitor chooses local preview. Embeddable deployments mount physician-demo-api as a pure-Rust axum::Router, giving each visitor an isolated in-memory turso_core snapshot, crates/harness chart search/read and workspace tool execution (memory_read, memory_save, follow_up_list, follow_up_create, briefing_read), physician-bus (LocalBus or RedisBus via VALKEY_URL/REDIS_URL/PHYSICIAN_REDIS_URL) invalidation streams, DemoTurnBudget enforcement, and dual-mode inference (OPENAI_API_KEY, GEMINI_API_KEY, or ANTHROPIC_API_KEY when configured, otherwise pure-Rust candle quantized_qwen3 / quantized_qwen2 GGUF defaulting to Qwen3-1.7B Q4_K_M).

Legal documents are data. Each current document is one record in data/<document>.json holding every word of it: heading, title, intro, date and sections. That covers Duet’s privacy policy, terms and consumer health data policy, Coda Health’s privacy policy and terms, and Clinical Transparency. Each archived version is its own record in data/archive/<document>/<slug>.json, named by its slug, and does not change. Each block of a section’s body is an object with one key naming its kind: paragraph, linked, list, table or source. src/legal.rs types and loads the records, listing each archive’s versions newest first, and src/pages/legal.rs renders them. Startup stops, naming the file and the fault, when a record has a missing, renamed or repeated field or a link that isn’t one of the site’s pages. Legal pages’ titles and descriptions are in src/route.rs, with every other page’s. Legal wording changes with its normal legal review.

Staging applies its origin IAP gate to pages, assets, redirects, health routes and errors. Responses force private, no-store, max-age=0, CDN-specific no-store headers, Vary: * and X-Robots-Tag: noindex, nofollow. IAP authenticates the user in front of Cloud Run. The origin still verifies the signed x-goog-iap-jwt-assertion header on every request in access.rs, against the exact audience /projects/NUMBER/locations/REGION/services/NAME. That is the direct Cloud Run signed-header audience, not an OAuth client ID or URL. It does not trust the signature-free x-goog-authenticated-user-* headers, and it does not let IAP’s presence stand in for verification. When a key refresh fails, cached keys are not used, so the request is denied.

Missing or invalid assertions return 403. A staging process with a missing or malformed audience refuses to start. Cloudflare Access variables, headers and service tokens authorize nothing. An optional separate loopback-only probe listener serves no site content. Local tests prove this application boundary with a public test-only key. They do not prove a deployed IAP configuration; member, nonmember and direct-origin checks are deployment checks.

Runtime configuration:

  • PUBLIC_SITE_LISTEN_ADDR: local default 127.0.0.1:8791; the image and Cloud Run root explicitly set 0.0.0.0:8080.
  • PHYSICIAN_APP_URL: optional fixed upstream origin for /physician/, not the browser navigation link. When set, the site mounts /physician/ and the nav offers Sign in; when unset, neither exists. There is no default: a local run against the sample physician server sets http://127.0.0.1:8790. Deployed values must use HTTPS; credentials, non-root paths, queries and fragments are rejected.
  • OBSERVABILITY_RELAY_URL: staging only, optional. It is the fixed HTTPS origin of the observability relay. When set, the site mounts /grafana/ (see Observability mounts); when unset, it is 404. It has the same validation as PHYSICIAN_APP_URL.
  • PHYSICIAN_PROXY_SERVICE_ACCOUNT: service identity used for keyless upstream IAP authentication. Required in staging whenever PHYSICIAN_APP_URL or OBSERVABILITY_RELAY_URL is set. No browser credential supplies this value.
  • PUBLIC_SITE_ORIGIN: optional exact browser origin for the physician proxy’s unsafe-method Origin validation. Defaults to https://staging.coda.dabney.moe in staging, https://coda.dabney.moe in production, and the local listener origin otherwise. Unspecified local bind addresses (0.0.0.0 or ::) map to the corresponding loopback browser host. Alternate hosts or mapped container ports must set this origin explicitly so unsafe-method Origin checks match the browser.
  • APP_ENV: deployment root permits only staging or production; staging selects the origin IAP gate. Do not use a misspelled environment to disable it.
  • RELEASE_SHA: full Git revision, supplied at runtime for the health response.
  • PUBLIC_SITE_IAP_AUDIENCE: required for staging. The deployment root sets it from the project number, region and service name, and it is not a secret. Production and local runs do not read it.
  • STAGING_HEALTH_TOKEN: when configured, /api/health requires it in addition to a valid IAP assertion; it is not an IAP bypass.
  • PUBLIC_SITE_MAX_CONCURRENCY: default 1024, accepted range 1–65536; excess concurrent requests receive 503 with Retry-After: 1.
  • PUBLIC_SITE_REQUEST_TIMEOUT_MS: static-site response deadline; default 5000, accepted range 100–30000. /physician/ and /grafana/ requests have one 60-second deadline through authentication, upstream startup and response headers. The proxy does not impose a second deadline, and streaming response bodies are not capped by this header deadline.
  • PUBLIC_SITE_INTERNAL_PROBE_ADDR: optional, loopback-only probe address.
  • Shared HTTP ingress protection (ingress.rs): CODA_RATE_LIMIT_RPM (default 240; 0 disables rate limiting), CODA_AUTH_RATE_LIMIT_RPM (default 20 for /auth/*, /physician/auth/*, /api/auth/email/*, /api/auth/email-change/*, /api/connected-care/sync, /front-door/sign-in/*, and /front-door/invitations/*), CODA_MAX_REQUEST_BODY_BYTES (64 KiB default on standalone public-site, 8 MiB when /physician/ or /grafana/ proxy mounts are active), CODA_MAX_CONCURRENT_REQUESTS (default 64 on the ingress guard), CODA_TRUSTED_PROXY_HOPS (default 1 rightmost X-Forwarded-For hop across all header lines), and CODA_RATE_LIMIT_ENFORCE_LOOPBACK (1/true or non-empty K_SERVICE, CODA_HOSTED, APP_ENV, or CODA_ENVIRONMENT enforces quotas on loopback clients too). Health probes stay exempt.

Local startup (from the workspace root):

nix develop --command cargo run -p public-site --bin public-site

Use the shell’s Chromium (or set CHROMIUM to the approved browser executable). The default startup uses port 8791; choose another PUBLIC_SITE_LISTEN_ADDR if a preview already owns it rather than stopping that preview.

Physician entry point

Production configures no physician upstream. Configuring one there requires qualified production physician authentication first; production must not expose unconfigured proof-token delivery.

The proxy must preserve physician bearer authorization, query strings and streamed responses without forwarding browser cookies, caller-supplied service credentials or IAP identity assertions to the upstream. Upstream IAP authentication is a separate service-account credential in Proxy-Authorization, not a replacement for the physician Authorization header. The public origin’s verified IAP gate remains mandatory for all staging proxy requests. Missing service credentials or failed refreshes fail closed; neither IAP boundary may be disabled to make the proxy work.

The credential flow is keyless: IAM Credentials signJwt, using the public-site runtime identity, a short-lived JWT scoped to the configured physician origin, and a self-scoped signing permission. The custom role publicSitePhysicianProxySigner (iam.serviceAccounts.signJwt only) is bound runtime-to-itself; the staging admin bootstrap’s --physician-proxy flag creates it. This permission is identity-signing authority, not an IAM restriction to one audience. The physician infrastructure owner grants that runtime identity IAP access to only the physician service through its authoritative physician_proxy_invokers binding; public-site infrastructure does not compete with that binding. No service-account private key or token belongs in source, URLs, browser state or logs.

/physician/ is not a browser security boundary: marketing scripts on the same origin can access the physician session stored in local storage. The entire origin must therefore be treated as trusted physician-session code. Proxy responses must never enter public or CDN caches. Cloud Run streams are finite; clients reconnect rather than relying on a longer request timeout.

Observability mounts

In staging, /grafana/ is proxied to the IAP-protected observability-relay Cloud Run service (crates/observability-relay), which forwards it to Grafana’s internal load balancer (observability README). Langfuse is the hosted HIPAA cloud project and has no mount. Each mount is a policy in proxy.rs; /grafana/ differs from /physician/ as follows:

MountPathCookiesIdentity forwarded
/physician/prefix stripped; Location rewritten back under itnonenone
/grafana/prefix kept; Location must stay under /grafana on the public origin, otherwise 502none, because Grafana signs in from the assertion on every requestthe caller’s verified IAP assertion as X-Coda-IAP-Assertion
The site drops any X-Coda-IAP-Assertion that the client sent before it forwards
the verified one. It also drops every x-goog-* header and the hop-by-hop
headers. Like /physician/, the Grafana mount authenticates to the relay with a JWT
signed for the site’s own service account, sent as Proxy-Authorization. The
responses are no-store with Vary: *. The relay’s own IAP admits only the
engineering group and the accounts in rust-environments’
observability_proxy_invokers. The relay checks its own IAP assertion again
before forwarding. The proxy carries no WebSockets, so Grafana Live is off.

Image

crates/public-site/Dockerfile builds a static x86_64-unknown-linux-musl binary and copies it into distroless static Debian 12 as UID/GID 65532. Builder/runtime images are digest-pinned, Cargo uses --locked, and no mutable OS package installation occurs during the build. Only workspace manifests/crates are copied, not reference submodules, local credentials, or Terraform state. The binary is checked for a dynamic ELF interpreter during the build. Pinned inputs improve repeatability; bit-for-bit image reproducibility is not claimed without a repeated-build comparison.

The server embeds assets/, including the motion script /homepage/site.js, so docker build alone produces the complete site; there is no separate motion build.

The site reads no secrets, so it has no Doppler config, token or Secret Manager access. Cloud Run runs the image’s own /public-site entrypoint, exactly as the local smoke tests do, with the deployment-controlled environment values above set directly. The dedicated service account has no database, physician or secret access.

Private registries only

No image is pulled from or pushed to a public registry. The three staging repositories are private Artifact Registry Docker repositories in coda-health-staging, us-east1, with Google-managed encryption. Production has one, public-site in coda-health-prod, which holds digests copied from staging’s. The admin bootstraps create them and refuse to continue if any grants allUsers or allAuthenticatedUsers.

RepositoryModeHoldsReaders / writers
public-sitestandard, immutable tagssite release imagesCI deployer writes; runtime SA public-site-staging@ reads
public-site-dockerhubremote, preset upstream docker-hubpull-through cache of library/rustCI deployer and gcp-engineering@ read
public-site-basestandard, immutable tagsdigest copy of gcr.io/distroless/static-debian12:nonrootCI deployer and gcp-engineering@ read

The Dockerfile names each base image by registry path (a build ARG) plus a fixed digest, and the defaults are the private repositories. An override changes only where a base image is fetched from. The digest stays fixed, so a different registry must serve identical content or the build fails.

Distroless is a one-time copy by digest into a standard immutable repository rather than a remote repository, so builds never contact gcr.io and the copy cannot later change.

The bootstrap grants the runtime SA reader on public-site alone, so that identity’s image access is explicit and limited to that repository. OpenTofu rejects any image outside REGION-docker.pkg.dev/PROJECT_ID/public-site/ that is not digest-pinned (see Checks).

Local builds. Engineers in gcp-engineering@dabney.moe read the two base-image repositories. Authenticate Docker once through gcloud’s credential helper; no key file or password is involved:

nix develop
gcloud auth login
gcloud auth configure-docker us-east1-docker.pkg.dev
docker build --platform=linux/amd64 \
  -f crates/public-site/Dockerfile -t public-site:local .
docker run --rm -p 127.0.0.1:8791:8080 public-site:local

Where *.pkg.dev does not resolve, a developer can build from the same digests at their public origin. This is for local use only and must never publish a release:

docker build --platform=linux/amd64 \
  --build-arg RUST_REPO=docker.io/library/rust \
  --build-arg RUNTIME_REPO=gcr.io/distroless/static-debian12 \
  -f crates/public-site/Dockerfile -t public-site:local .

Infrastructure: staging IAP, production load balancer

infra/gcp/public-site is an isolated OpenTofu root. It owns public-site staging and production state through a partial GCS backend, one file per environment (see Staging state and deployment and Production state and deployment). Both environments get a separate Cloud Run service and a dedicated service account. The root creates no DNS records, project, API enablement, service identity, Google Group, database, or physician runtime dependency. Production’s one certificate is the Certificate Manager certificate described below. Its scaling defaults are bounded configuration, not demonstrated load capacity. Startup uses a TCP probe on port 8080 rather than an unauthenticated HTTP health route.

Staging (environment = "staging", the default) uses direct Cloud Run IAP and no load balancer:

  • iap_enabled = true, ingress INGRESS_TRAFFIC_ALL, the run.app URL enabled (output staging_url) and invoker_iam_disabled = false.
  • The only roles/run.invoker member is the project’s IAP service agent, service-PROJECT_NUMBER@gcp-sa-iap.iam.gserviceaccount.com. It is set through an authoritative binding on this service only. There is no allUsers grant, and CI or deployer identities get no implicit website access.
  • The only roles/iap.httpsResourceAccessor member is group:gcp-engineering@dabney.moe (variable iap_group). This is also an authoritative binding on this service only, not a project or domain grant.
  • PUBLIC_SITE_IAP_AUDIENCE comes from project_number, region and the service name, and it is set directly on the container. The output iap_audience exposes the same value.
  • staging_domain optionally maps a verified hostname to this same service. env/staging.tfvars sets it to staging.coda.dabney.moe. Cloud Run manages TLS; the Cloudflare staging.coda record is a DNS-only CNAME to ghs.googlehosted.com, as staging_domain_records returns. Native IAP remains the access owner on both hostnames.

Production (environment = "production") serves the same image behind a load balancer. Ingress is INGRESS_TRAFFIC_INTERNAL_LOAD_BALANCER and the run.app URI is disabled. It uses a serverless NEG, a global external managed HTTPS load balancer, an HTTP frontend on the same address that answers every request with a 308 to HTTPS (host, path and query kept), a MODERN / TLS 1.2 policy, Cloud CDN, and the Cloud Run invoker check turned off (invoker_iam_disabled), because the ALB does not authenticate and the organization’s domain restriction forbids an allUsers grant; ALB-only ingress and the disabled run.app URL are the boundary. TLS comes from one Google-managed Certificate Manager certificate for domains (apex and www), attached through a certificate map with an entry per hostname. It is authorized by the DNS records the certificate_dns_records output lists, not by serving traffic, and those records also renew it. Production without domains is rejected. IAP is off. No Cloud Run custom-domain mapping is created for production.

Cloud CDN and staging safety

IAP and Cloud CDN cannot be enabled together on one backend. That is one reason staging uses direct Cloud Run IAP with no backend service.

  • Production: Cloud CDN is enabled with USE_ORIGIN_HEADERS, no forced caching and no negative caching. The server emits the cache headers described above; the infrastructure does not manufacture application cacheability.
  • Staging: there is no load balancer or Cloud CDN, and no variable can add them. Origin responses are no-store, so no upstream layer may cache protected content. There is no Cloudflare dependency.

Checks

Site checks, from the workspace root:

nix develop --command cargo test --locked -p public-site
nix develop --command cargo test --locked -p public-site --test site -- --ignored --nocapture
nix develop --command mdbook build book

Routine CI does not launch browsers. The site browser test is ignored by default; run the explicit command above or manually dispatch the CI workflow for browser qualification.

Infrastructure checks initialize without the backend (-backend=false), so they need no ADC credentials and make no live GCP API calls. Do not initialize the other GCP roots from this workspace.

nix develop --command tofu -chdir=infra/gcp/public-site init -backend=false -input=false
nix develop --command tofu -chdir=infra/gcp/public-site fmt -check -recursive
nix develop --command tofu -chdir=infra/gcp/public-site validate
nix develop --command tofu -chdir=infra/gcp/public-site test

The generated .terraform.lock.hcl belongs in version control. These checks validate resource contracts, not cloud permissions, API enablement, IAP brand/OAuth configuration, group membership, regional quotas, autoscaling behavior, application health, or a real deployment.

The image smoke builds and runs the image locally:

nix develop --command docker build --platform=linux/amd64 \
  -f crates/public-site/Dockerfile -t public-site:deployment-check .
nix develop --command python infra/gcp/public-site/smoke.py public-site:deployment-check

smoke.py runs the image in disposable, locked-down containers three ways: as production does, with a physician upstream, and in staging mode. It has no signed positive path: signed allow, key rotation and fetch failure are proven only by Rust tests with a public test key. It does not replace the browser animation tests, a deep secret scan of embedded source assets, a load test, cloud ingress verification, or a deployment.

Local load check

crates/public-site/load_check.py starts only disposable loopback listeners. It neither targets arbitrary URLs nor starts model/data services.

nix develop --command env -u RUSTC_WRAPPER -u RUSTC_WORKSPACE_WRAPPER \
  -u RUSTFLAGS -u CARGO_ENCODED_RUSTFLAGS \
  cargo build --locked --release -p public-site --bin public-site
nix develop --command python crates/public-site/load_check.py

Output goes under target/public-site-load/ (--output chooses another directory). The results are closed-loop, fixed-concurrency numbers from the machine that runs them, with no TLS, CDN, browser or Brotli. They don’t establish Cloud Run capacity, behavior above the request-permit limit, or a single-digit-millisecond p99.

Staging state and deployment

This root owns public-site staging state. The physician roots under infra/gcp keep their product-repository apply authority; this ownership covers only infra/gcp/public-site with environment = "staging".

  • State. backend "gcs" {} is partial. backend/staging.gcs.tfbackend selects a dedicated staging bucket. Staging state never lives in a coda-health-prod bucket, so the CI deployer needs no production-project IAM.
  • Inputs. env/staging.tfvars holds the non-secret staging inputs: the last operator-reviewed image digest in the private public-site repository, release SHA, and physician_app_url, the physician preview service in coda-rust-staging behind its own IAP. Setting it mounts /physician/, renders Sign in and gives the runtime its proxy signing identity. observability_relay_url (staging only) is rust-environments’ observability_relay.url; setting it mounts /grafana/ with the same signing identity.
  • No Doppler. The running site and its deploy read no Doppler config and no secret; these files and the CI inputs are the only deploy values.

Staging admin bootstrap

infra/gcp/public-site/scripts/staging-admin-bootstrap.sh is run by an administrator of coda-health-staging, not by the deployer. It prepares only what the root deliberately does not own: APIs, the state bucket, the private repositories and their base images, the keyless CI deployer with resource-scoped roles, and GitHub Workload Identity Federation limited to this repository’s main branch and staging environment. Each create step checks first, so it is safe to rerun. It prints every command and never touches coda-health-prod. Review it with --print first; that mode makes no gcloud calls.

# From the workspace root, inside the dev shell, as the staging admin:
nix develop
gcloud auth login                     # the admin's account
bash infra/gcp/public-site/scripts/staging-admin-bootstrap.sh --print
bash infra/gcp/public-site/scripts/staging-admin-bootstrap.sh   # needs docker (buildx)
# OPTIONAL, only if DEPLOYER_USER should run a first apply (expires in 24 h):
bash infra/gcp/public-site/scripts/staging-admin-bootstrap.sh --temporary-deployer-grant
# After a first apply, rerun once to add the service-scoped CI bindings:
bash infra/gcp/public-site/scripts/staging-admin-bootstrap.sh

--physician-proxy also creates the proxy signing role and binds it runtime-to-itself. Expired temporary grants grant nothing; remove them afterwards with remove-iam-policy-binding ... --all.

CI gets no iam.serviceAccountAdmin (it never creates or edits the runtime account: a first apply is a human apply), no project-wide run.admin, iap.admin or actAs, and no run.invoker or iap.httpsResourceAccessor, so it has no website access. The service-scoped grants need the service and runtime account to exist; the script skips them until then and adds them on a rerun. Tofu’s authoritative bindings cover only roles/run.invoker and roles/iap.httpsResourceAccessor, so they do not remove these grants.

A Google Workspace or Cloud Identity admin can confirm the IAP group exists and whether DEPLOYER_USER is in it (read-only):

bash infra/gcp/public-site/scripts/staging-admin-bootstrap.sh --check-group

CI deploy on push to main

The deploy-public-site-staging job in .github/workflows/ci.yml redeploys staging from pushes to main selected for full validation, after CI result passes. Engineering-skills/docs-only pushes skip deployment. It runs only when the repository variable PUBLIC_SITE_STAGING_DEPLOY is enabled; unset it to stop deploys without editing the workflow. The GitHub staging environment allows only the main branch to deploy, which matches the provider’s attribute condition. The job:

  1. Builds crates/public-site/Dockerfile with the private base-image defaults and runs smoke.py on the result.
  2. Pushes the image to public-site/public-site:<sha>. Tags are immutable, so a rerun of the same commit reuses the digest it already published.
  3. Runs tofu plan with env/staging.tfvars plus -var image=<digest> and -var release_sha=<sha>, and fails unless the saved plan is empty or an in-place update of google_cloud_run_v2_service.site alone. Then it applies that saved plan.
  4. Requires the latest revision to be Ready, serve 100% of traffic and report the new digest. It also requires anonymous requests to the run.app homepage and /health and to staging.coda.dabney.moe to redirect to Google sign-in.

CI and deployment identities have no website-access grant, so the job checks only that anonymous requests are sent to sign-in; an authenticated render is a manual check by a member of gcp-engineering@dabney.moe.

env/staging.tfvars keeps the last operator-reviewed digest; a local plan run from it after a CI deploy shows the image going back. Pass the current digest with -var image=... (read it from gcloud run services describe) when planning by hand. A plan that changes anything beyond the service, such as IAM or the domain mapping, stops at the CI guard and needs an operator apply from a reviewed saved plan.

Operator apply

Run from the workspace root as the staging admin, or as DEPLOYER_USER while a temporary grant is valid:

nix develop
export GOOGLE_OAUTH_ACCESS_TOKEN="$(gcloud auth print-access-token --project=coda-health-staging)"
tofu -chdir=infra/gcp/public-site init -input=false -reconfigure \
  -backend-config=backend/staging.gcs.tfbackend
tofu -chdir=infra/gcp/public-site plan -input=false \
  -var-file=env/staging.tfvars -var image=CURRENT_DIGEST_REF -out=staging.tfplan
# Review the saved plan, then apply only that plan; never apply production here.
tofu -chdir=infra/gcp/public-site apply staging.tfplan
tofu -chdir=infra/gcp/public-site output staging_url

After a first apply, rerun the bootstrap so CI gets its service-scoped roles. A new staging environment is live only when a member of the engineering group is allowed, a nonmember denied, an unauthenticated direct run.app request redirected to sign-in, and no protected content served from a cache, on both staging.coda.dabney.moe and the run.app URL.

Production state and deployment

Production serves the image staging tested, without sign-in, at coda.dabney.moe and www.coda.dabney.moe from coda-health-prod. Operator applies and DNS changes require explicit operator authorization.

  • State. backend/production.gcs.tfbackend selects a dedicated state bucket, as staging has its own. The deployer has no access to the shared production state bucket: Cloud Storage cannot narrow object listing to a prefix with an IAM condition.
  • Inputs. env/production.tfvars holds the non-secret production inputs: the project and number, and domains. It sets no physician_app_url, so production has no Sign in link and no /physician/ mount. image and release_sha are supplied per release: the digest staging tested and its commit.
  • DNS. In the dabney.moe Cloudflare zone, coda.dabney.moe and www.coda.dabney.moe are DNS-only A records to the root’s load_balancer_ip. The _acme-challenge CNAMEs from certificate_dns_records stay in place: Certificate Manager renews the certificate through them. The zone’s other records belong to other owners.

Production admin bootstrap

scripts/production-admin-bootstrap.sh prepares what the root does not own: APIs, the state bucket, the private image repository, the keyless public-site-prod-deployer account, and a Workload Identity Federation provider accepting only tyler274/coda-rust on refs/heads/main in the production environment. An administrator of coda-health-prod runs it with explicit operator authorization; one step needs an administrator of coda-health-staging. --print shows every command without calling gcloud. It is safe to rerun, and a first apply is followed by a rerun for the bindings that need the service and runtime account to exist.

The deployer gets no compute, certificate or IAM admin role: promotion cannot change the load balancer, TLS or identities, only clear the CDN. The GitHub production environment admits only main and has no required reviewer.

Promotion

promote-public-site.yml is manual (workflow_dispatch on main, input release_sha) and runs in the production environment. Starting a run is the approval: anyone with write access to the repository can promote a commit staging already built and tested. It:

  1. requires a full SHA that is on main and a successful “Deploy public site to staging” job for that push, so the image was deployed and verified on staging, not only built. Skills/docs-only pushes skip that job, so promote the latest commit staging actually deployed;
  2. finds the image the staging deploy tagged with that commit (tags are immutable) and copies that digest into the production repository unchanged;
  3. plans the production root with env/production.tfvars, that image and that SHA, and fails if the plan changes anything but an in-place update of the Cloud Run service. Load balancer, certificate, IAM and identity changes are operator applies;
  4. applies the saved plan and checks the Ready revision serves the digest with all traffic;
  5. clears the CDN and waits for it to finish;
  6. pins coda.dabney.moe and www.coda.dabney.moe to the load balancer IP with curl --resolve and checks each: /api/health reports production and the SHA, the homepage sends production’s HSTS and offers no Sign in, /physician/today is 404, and plain HTTP answers 308 to the same HTTPS URL.

The CDN is cleared because its cached HTML names hashed CSS and JS the new image no longer serves, which would load unstyled pages. Clearing the CDN does not clear browsers, so a returning visitor may see one unstyled load before the next load is current.

Recovery

Recovery is a promotion of an earlier staging-tested commit: run the promotion workflow with that commit’s SHA.

Rebuilding production

Each step requires explicit operator authorization at the time it runs.

  1. Run the production admin bootstrap.

  2. Copy the staging-tested digest into the production repository as the workflow does, then, as an administrator:

    tofu -chdir=infra/gcp/public-site init -backend-config=backend/production.gcs.tfbackend
    tofu -chdir=infra/gcp/public-site plan -var-file=env/production.tfvars \
      -var image=IMAGE@DIGEST -var release_sha=SHA -out=production.tfplan
    tofu -chdir=infra/gcp/public-site apply production.tfplan   # after review
    

    Rerun the bootstrap for the bindings that need the service and runtime account.

  3. Add the certificate_dns_records CNAMEs in Cloudflare, DNS only, and wait until gcloud --project=coda-health-prod certificate-manager certificates describe public-site-production reports the certificate ACTIVE.

  4. Run the promotion workflow for the same SHA. Its plan is a no-op and its readback checks both hostnames through the load balancer before DNS points there. Also look at the site in a browser pinned to the load balancer IP.

  5. Point the apex and www A records at load_balancer_ip, DNS only, and check public DNS answers and the live responses.

Synthetic patients

The patient bank is a set of fictional adult patients of one primary-care practice, each a longitudinal chart in FHIR R4. Coda runs against them where it needs realistic patients. Nothing in it is real patient data, and no physician has reviewed it.

Where the patients come from

  • The people: synthetic_hospital (benchmark_v1.3.db, MIT, fully synthetic). Each of its 1,020 adult patients is the source of one patient in the practice. Because they are in the bank, Coda is never evaluated on synthetic_hospital’s own benchmark.
  • The method: coda-gym’s. A chart is written from a requirements file that says what it may hold, so every clinical fact comes from the source or a listed addition, and nothing is invented.
  • Lab labels and reference ranges: coda-gym’s lab_reference_ranges.xlsx.
  • The format: FHIR R4 as render.rs builds it, with its MRN system and note header, and the catalog’s code systems.

What a chart is

The practice is a membership internal medicine practice in western Massachusetts, and its today is 2026-08-27 12:00 Eastern. Each source becomes the primary-care chart the same person would have there:

  • What the source says stays: its diagnoses, medications, results and events, rare ones included. Its internal and family medicine visits become the practice’s own; specialist, emergency and hospital care arrives as outside records, and how complete those records are varies by patient.
  • The practice adds what primary care does over the years: regular visits, preventive care, medication management, labs over time, notes in its own voice and visits booked after today.
  • A source diagnosis with no treatment gets its standard care. After the source ends, the patient follows the ordinary course, with no new diagnoses.
  • Dates move so the history ends before today.
  • How long ago the practice last saw the patient varies as in a real panel, from weeks to years. Outside records that arrive after that visit are filed but not reconciled, and only some patients have a visit booked.
  • A source who cannot be a living primary-care patient has no chart.

Vitals, lab values and calculated results are made by code from the patient’s state, never typed by an author.

Where it lives

WhatWhere
The tool: import from synthetic_hospital, authoring, checks, FHIR build and validationcrates/patient-bank; its README has the commands and what the code owns
The patients, one folder each: the seed, the source, the requirements, the author’s drafts and the accepted chartpatients/units/<unit>/
The FHIR bank, previews and caches, all derivedtarget/patient-bank/, ignored and rebuilt

Charts are written in batches; a unit folder without ledger.json has no chart yet.

Recorded Hint and FHIR adapter verification

This proof starts at acquired source data. Hint sections contain items, section failed_parts, and each item’s native body and unavailable_parts. FHIR inputs are native NDJSON records. Acquisition credentials and recorded sandbox/corpus inputs stay outside Git. A small synthetic capture in test support guards malformed siblings. The acquisition owner prepares the Hint envelope and applies the explicit exclusions in the mapping contract.

Run in the development shell against a disposable Postgres server:

PHYSICIAN_RUNTIME_TEST_DATABASE_URL=postgresql://postgres@127.0.0.1:5544/postgres \
SOURCE_REPLAY_ROOT=/absolute/path/archived-selection \
HINT_CAPTURE_ROOT=/absolute/path/hint-captures \
scripts/check-record-adapters.sh

Input contracts:

  • SOURCE_REPLAY_ROOT: hint-bodies.json, hint-replayed.json, mimic/, mimic-expected.json and input-provenance.json. The preparation script at crates/physician-sample/tests/support/prepare_recorded_sources.py --help describes its external capture, corpus and research-manifest inputs. It selects the archived twelve-section, thirteen-record Hint selection and the fixed 57 MIMIC research cases plus their patient and referenced supporting records.
  • HINT_CAPTURE_ROOT: live-proof.json, live-proof-multipage.json, and worker-0-{0,1,2,3}.json / worker-3-{0,1,2,3}.json. These are acquisition receipts and paired reader outputs for the ordinary and repeated-identity captures. The adapter tests consume them without starting an extension.

The command assembles a fresh target/verification/record-adapter-inputs.* directory from the four worker-0-* captures and the prepared MIMIC selection, recording input digests for inspection. Input directories are never modified; readback artifacts go to target/verification/record-adapters.

The filer requires this acquired-envelope contract. The checked-in extension’s raw bridge responses are not this envelope; the acquisition lane must supply it before connecting that producer to the filer. This unit does not implement that transport or the source exclusion policy.

The app test implements only acquisition from these captures. It invokes the existing application loader for patient linking, enrollment and transactional record delivery, then refreshes through authenticated HTTP source-check routes. It reconnects to Postgres and reads stored evidence through the shared tools. No test writes source records directly along that app path. Missing inputs fail the command rather than silently skipping qualification.

The other suites cover mapping precedence, malformed siblings, unavailable attachments, Other, retained revisions and persisted citation identity. The citation provider is scripted. Chromium qualifies the baseline physician site; opening citations in a browser additionally requires the citation UI implementation. Real-model behavior and that UI integration are separate proof targets.

The bounded Hint appointment window remains a partial acquisition under the current source contract. The adapter retains that limit; this proof does not qualify connection health, Chrome reconnect/retry behavior, or hosted transport.

Observability

The observability stack has selectable operations destinations (traces, logs, metrics, alerts) and Langfuse for agent runs. Destinations are Datadog (APM, logs, Error Tracking, monitors), a self-hosted Grafana stack (Tempo, Loki, Prometheus, Grafana). Both use the same OpenTelemetry trace. The operations backend gets every span with agent content removed. Langfuse gets only model generations, in the hosted project at https://hipaa.cloud.langfuse.com, which Langfuse’s BAA covers. The collector strips content from the operations pipelines unconditionally, so no content depends on an operations vendor’s BAA scope.

This page describes configuration and verification, not live deployment status. Infrastructure, Datadog and Grafana changes require separately authorized, reviewed plans; the observability operator owns their application.

Choosing a backend

datadog is the compatibility default. both runs Datadog and Grafana concurrently with independent bounded exporter queues. Datadog owns operational notifications; Grafana rules evaluate in shadow mode without service paging. See concurrent qualification for the default-off compatibility metrics source, separately gated synthetic notification route, storage review and rollback requirements.

datadoggrafana
TracesDatadog APMTempo
LogsDatadog LogsLoki (OTLP ingestion)
Request metricsAPM trace metricsTempo metrics-generator span metrics, remote-written to Prometheus
Platform metricsDatadog GCP integration (optional)Cloud Monitoring datasource in Grafana (optional)
AlertsFour datadog_monitors to alert_notifyThe same four rules, evaluated in shadow mode without notifications
Where it runsDatadog SaaS, via the in-cluster AgentStatefulSets in the observability cluster, ClusterIP only

The choice lives in three places that must agree:

  • Collector. One backend overlay, collector.datadog.yaml, collector.grafana.yaml or collector.both.yaml, is merged last and sets only the exporters of the traces/ops and logs/ops pipelines. Without an overlay those pipelines export to nop, so a missing choice drops data rather than sending it somewhere unintended. The privacy and caller processors are the same for both.
  • Services. CODA_TELEMETRY_BACKEND (datadog, grafana or both) only changes the correlation keys in JSON log lines. OTLP export is identical.
  • Infrastructure. telemetry_backend in both observability and rust-environments. The first deploys the Datadog Agent and monitors or the Grafana stack and picks the collector overlay; the second sets CODA_TELEMETRY_BACKEND on the product containers. The switch procedure is in the root’s README. telemetry_content works the same way: both roots set it, rust-environments puts it on the product containers as CODA_TELEMETRY_CONTENT, and observability refuses full without Langfuse.

Data flow

Cloud Run (staging): physician, duet, physician-worker    crates/telemetry (tracing + OTLP/HTTP)
        │  OTLP/HTTP localhost:4318 (spans and log records)
        ▼
otel-collector sidecar  (dev/observability/sidecar.yaml)
        │  OTLP/HTTP to the internal gateway, Google ID token (googleclientauth)
        │  Cloud Run Direct VPC egress → rust-private
        ▼
otel-gateway  internal passthrough LB, port 4318, source range = Cloud Run egress subnet
        ▼
otel-collector  GKE observability cluster
  │  collector.yaml + collector.gke.yaml [+ collector.gke-no-langfuse.yaml] + collector.<backend>.yaml (last)
  │  oidc: Google issuer + audience; caller allowlist of runtime service accounts
  ├─ traces/ops       … → transform/strip_content     → batch ─┬ datadog: Datadog Agent (OTLP 4317) → Datadog APM
  │                                                            └ grafana: Tempo (OTLP 4317) ── metrics-generator ─→ Prometheus
  ├─ traces/langfuse  … → filter/langfuse_generations → batch → Langfuse /api/public/otel (Basic auth)
  └─ logs/ops         … → transform/strip_log_content → batch ─┬ datadog: Datadog Agent (OTLP 4317) → Datadog Logs
                                                               └ grafana: Loki /otlp (OTLP/HTTP 3100)

Grafana (grafana or both) reads Tempo, Loki and Prometheus; operational rules remain shadow-only
Cloud Run stdout/stderr → Cloud Logging only (not forwarded to either backend)
Cloud Run and GKE platform metrics → Datadog GCP integration, or Grafana's Cloud Monitoring datasource (optional, project-scoped)

Locally, services export straight to the compose collector (dev/observability/collector.yaml plus the debug, Datadog or Grafana overlay) with no sidecar or gateway.

Langfuse can be switched off on its own (no langfuse_host in infra/gcp/observability). The gateway then merges collector.gke-no-langfuse.yaml before the backend overlay, and traces/langfuse ends in nop. The ops pipelines and every privacy and caller step are unchanged.

Per signal:

  • Traces. Every span goes to the operations backend (Datadog APM or Tempo) with content deleted. Generation spans also go, with content as the service sent it, to the Langfuse project at langfuse_host.
  • Logs. Services emit their log events as OTLP log records over the same sidecar path. Every HTTP response emits one info record with status, latency_ms and the request’s trace id, and every finished worker attempt emits one info record (physician.worker.attempt_finished) with coda.job, coda.outcome, coda.run_id and the attempt’s trace id, so a request or worker attempt with a span and no log record means the log path is broken. The gateway deletes the same content keys from log record and resource attributes and sends them to the operations backend only (Datadog Logs or Loki); log records never go to Langfuse. Loki indexes only service.name and deployment.environment as labels (service_name, deployment_environment); trace_id, coda.run_id and the other attributes are structured metadata. Cloud Run’s own stdout capture stays in Cloud Logging, so a service with export off still has its logs there.
  • Metrics. Under datadog, request rate, error rate and latency per service come from APM’s trace metrics. Under grafana, Tempo’s metrics-generator derives span metrics (traces_spanmetrics_calls_total, traces_spanmetrics_latency_bucket) and a service graph and remote-writes them to Prometheus. Their only extra dimensions are coda.job, gen_ai.system and deployment.environment; run ids never become metric labels. Cloud Run and GKE platform metrics (instances, cold starts, container CPU and memory, requests answered before the product container) are optional under either backend and off by default: the Datadog GCP integration (datadog_gcp_integration_enabled), which Datadog reads by impersonating a read-only service account, or Grafana’s Cloud Monitoring datasource (grafana_cloud_monitoring_enabled), which reads through Workload Identity as a roles/monitoring.viewer service account. Neither has a key.
  • Release. DD_ENV comes from OpenTofu (staging) under both backends; it becomes deployment.environment. DD_VERSION is baked into each image at build time from its source revision, so a revision’s spans and logs name the image that produced them and no apply can revert it.

The infra/gcp/observability README details the gateway’s transport, authentication and rotation.

  • Spans. crates/telemetry installs one tracing subscriber. When OTEL_EXPORTER_OTLP_ENDPOINT is set, it exports OTLP/HTTP spans with service.name, deployment.environment (DD_ENV), and service.version (DD_VERSION). http_layer traces each request and continues an inbound W3C traceparent.
  • Generations. telemetry::genai::generation_span opens a gen_ai.generation span in Langfuse’s OTel mapping (langfuse.observation.type=generation, gen_ai.system, gen_ai.request.model, gen_ai.usage.*). It also carries the run contract: coda.run_id, coda.job, coda.recipe_version, coda.origin (simulation or real, also written to langfuse.environment), coda.scenario_id, langfuse.session.id, and langfuse.trace.tags.
  • Logs. When an OTLP endpoint is set (or CODA_LOG_FORMAT=json), stdout logs are JSON lines with the W3C hex trace_id and span_id. Under CODA_TELEMETRY_BACKEND=datadog they also carry dd.trace_id, dd.span_id, dd.service, dd.env and dd.version; under grafana they carry no dd.* keys. Exported log records carry the trace and span ids under both, so a Datadog log or a Loki line opens its trace. A log event carries its own fields, never span fields, so content recorded on a generation span never reaches log storage.

Sidecar lifecycle and outages

The sidecar is a second container in each Cloud Run service. The product container does not depend on it: Cloud Run starts and health-checks the product on its own probes, and the sidecar has its own startup probe on the collector’s health_check port with 1 vCPU and 256 MiB limits. Startup order is independent, but revision readiness is not: a collector image-pull or startup failure can prevent the new revision from serving.

  • Gateway or backend outage. The sidecar keeps a bounded in-memory queue and retries for a bounded time, then drops. The product never blocks on export, and its requests keep succeeding.
  • Sidecar crash. The product’s exporter fails fast against localhost and drops; Cloud Run restarts the sidecar. Telemetry from that window is lost.
  • CPU and shutdown. Enabling observability disables CPU throttling for the product and sidecar so export can drain between requests. Both containers receive 1 vCPU, increasing per-instance allocation and billing. This cost belongs in the reviewed deployment plan. On scale-in, the product makes a bounded flush through TelemetryGuard and the sidecar flushes on SIGTERM within Cloud Run’s 10-second grace period; remaining queued telemetry is lost.

Working-window timing

The shared harness retains the opening time in Unix milliseconds on each WindowOpened event, alongside its reason and optional note reference. ProviderStarted retains the request’s admission time. Products store both in their existing run journals. These wall-clock timestamps let inspection relate a window opening to surrounding requests without a second timing store. Cross-process comparisons depend on the hosts’ clock synchronization. The records contain model context and stay with the product; they are not exported to Datadog as raw logs.

Content policy

The policy applies identically to both backends: it lives in the shared collector processors, and the backend overlay changes only the exporters.

WhereRule
ServiceCODA_TELEMETRY_CONTENT=none (default) records no prompt or completion text. full attaches it as langfuse.observation.input/output. Simulation traffic may use full anywhere. Real traffic may use it only when spans go to the Langfuse project under the BAA.
Collector → ops tracestransform/strip_content on traces/ops keeps only an allowlist of operational attributes on resources, spans and span events, so prompt and completion text (langfuse.observation.input/output and any other key) never leaves for the operations backend. It also clears status messages and renames unknown span names. The policy setting does not change this. Model, usage, run, scenario and origin attributes stay.
Collector → Langfusefilter/langfuse_generations keeps only spans with langfuse.observation.type or the gen_ai.* attributes the crate sets. HTTP and infrastructure spans stay in the operations backend.
Collector → ops logstransform/strip_log_content on logs/ops applies the same kind of allowlist to log record and resource attributes and replaces every body. No log pipeline exports to Langfuse.
Datadog Agent (datadog)Tails no container logs and excludes the observability namespace, because Langfuse can log payloads on errors. It receives logs only as OTLP from the gateway.
Tempo, Loki, Prometheus (grafana)Only the gateway collector writes to Tempo and Loki; Prometheus receives only Tempo’s span metrics. Nothing scrapes container logs. All ClusterIP only.
GatewayAccepts only Google ID tokens with the gateway audience from the listed Cloud Run runtime service accounts, over the internal load balancer restricted to the Cloud Run egress range.
LangfuseThe hosted HIPAA cloud project at langfuse_host, reached over HTTPS with the project’s key pair. People sign in at https://hipaa.cloud.langfuse.com as members of the Coda organization; nothing in the cluster serves Langfuse. Retention is the project’s 90-day setting.
GrafanaClusterIP, plus the same relay-only internal load balancer. In staging it serves under https://staging.coda.dabney.moe/grafana/ and signs people in from the forwarded IAP assertion (X-Coda-IAP-Assertion) after checking its signature, issuer and the public-site audience; otherwise kubectl port-forward. Grafana-stack retention is 14 days of traces, 30 of logs and 30 of metrics by default.

tofu test in infra/gcp/observability reads the deployed collector config and asserts that every content key is deleted on both span contexts and that model and run ids survive. The local debug overlay runs the same processor, so what it prints is what either backend would receive.

The full path is tested end to end by an ignored test in physician-sample, content_reaches_langfuse_and_never_the_operations_backend. It runs physician-worker with CODA_TELEMETRY_CONTENT=full on a rehearsal practice, through otelcol-contrib on collector.yaml, to a real Langfuse in Docker (dev/observability/test). It reads the generation back through the Langfuse API (environment simulation, the chat as session, the run id, the prompt and reply), and asserts that the operations pipelines delivered the same generation, with its model, to the test’s OTLP sink with neither text anywhere in what they sent:

PHYSICIAN_RUNTIME_TEST_DATABASE_URL=postgres://... \
  cargo test -p physician-sample --test worker content_reaches -- --ignored

Environment variables

VariableSet onMeaning
OTEL_EXPORTER_OTLP_ENDPOINTservicesCollector OTLP/HTTP base. Unset means no export (tests and the default sample server). Locally and on Cloud Run http://localhost:4318 (the compose collector, or the service’s sidecar).
DD_ENVserviceslocal or staging, exported as deployment.environment under either backend; on Cloud Run set by OpenTofu. Falls back to CODA_ENV.
DD_VERSIONservicesRelease version (service.version), baked into each image’s environment at build time from its source revision. Never set by OpenTofu.
CODA_TELEMETRY_CONTENTservicesnone (default) or full.
CODA_TELEMETRY_BACKENDservicesdatadog (default), grafana or both. Under datadog and both, JSON log lines add the dd.* correlation keys. An unknown value warns once and falls back to datadog. On Cloud Run set from rust-environments’ telemetry_backend.
CODA_LOG_FORMATservicesjson forces JSON logs without an OTLP endpoint. Cloud Run sets it.
DATADOG_OTLP_ENDPOINTcollector (datadog)Datadog Agent OTLP gRPC host:port.
TEMPO_OTLP_ENDPOINTcollector (grafana)Tempo OTLP gRPC host:port.
LOKI_OTLP_ENDPOINTcollector (grafana)Loki OTLP/HTTP base ending in /otlp.
PROMETHEUS_REMOTE_WRITE_URLTempoWhere the metrics-generator remote-writes span metrics (Prometheus /api/v1/write).
TEMPO_BLOCK_RETENTIONTempoTrace retention, default 336h; GKE sets it from grafana_traces_retention_days.
LOKI_RETENTION_PERIODLokiLog retention, default 720h; GKE sets it from grafana_logs_retention_days. Prometheus retention is a flag from grafana_metrics_retention_days.
GRAFANA_SLACK_WEBHOOK_URLGrafanaSlack incoming webhook the provisioned contact point posts to. A Doppler secret on GKE; the local sink locally.
OTEL_GATEWAY_AUDIENCEgateway collector, sidecarThe ID-token audience both sides use.
OTEL_GATEWAY_ALLOWED_CALLERSgateway collectorComma-separated runtime service-account emails whose data is kept.
LANGFUSE_OTLP_ENDPOINTcollectorLangfuse base ending in /api/public/otel.
LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEYcollectorLangfuse project keys for Basic auth. In GKE they sync from Doppler.

Secrets

Doppler holds every observability secret: the Datadog API and app keys (under datadog), GRAFANA_ADMIN_PASSWORD and GRAFANA_SLACK_WEBHOOK_URL (under grafana), and the Langfuse project keys (LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY, with LANGFUSE_BASE_URL beside them). Only the selected backend’s keys are synced, so the other backend’s keys need not exist. The Doppler Kubernetes Operator syncs them into the observability namespace; infra/gcp/observability says how its token arrives and maps each key.

Local runbook

nix develop
scripts/observability-up.sh            # Langfuse + collector, ops spans and logs to the debug exporter
scripts/observability-up.sh --datadog  # adds the Datadog Agent, DD_API_KEY from Doppler dev
scripts/observability-up.sh --grafana  # adds Tempo, Loki, Prometheus, Grafana and a webhook sink; no secrets

OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 DD_ENV=local CODA_TELEMETRY_CONTENT=full \
  CODA_LOCAL_MODEL_EXECUTION=subscription scripts/local-practice.sh

With --grafana, also set CODA_TELEMETRY_BACKEND=grafana on the service. Send one physician chat. The trace then appears in Langfuse at http://localhost:3000 (dev@coda.local / coda-local-dev, project coda-agents). The content-free copy of the same spans prints in docker compose -f dev/observability/compose.yaml logs -f otel-collector (debug), shows in Datadog APM under env:local with --datadog, or opens in Grafana Explore at http://localhost:3300 (admin / coda-local-dev) with --grafana. Prometheus is on http://localhost:9091. Grafana’s Slack contact point posts to a local sink instead of Slack; received alerts are listed at http://localhost:3301/received. scripts/observability-up.sh down -v removes the stack and its volumes. The compose credentials are fixed local development values, and every port binds to 127.0.0.1. See dev/observability.

Downtime notification qualification

Datadog is the primary staging operational route to #engineering-observability. An independent Cloud Monitoring watchdog covers missing monitoring/probe heartbeat outside GKE. Concurrent Grafana service alerts must stay shadow-only; its contact/evaluator qualification uses a separately labeled test route, not duplicate operational pages.

The local qualification rehearsal prints bounded synthetic failure/recovery, reminder, grouping and maintenance steps and checks timestamped observations without making any external calls. It extends the existing collector/sink tooling but does not substitute a local webhook acknowledgment for a Slack receipt or a fixture for an actual evaluator.

Before live work, read back the exact account/contact/channel mapping and the synthetic evaluator’s signal selector and windows. Obtain explicit approval for the labeled routing send, bounded synthetic failure/recovery and maintenance window, and independent watchdog heartbeat-loss exercise. Include source and deployed revisions, UTC start/end, maximum sends, dedicated target, abort and cleanup steps. Infrastructure changes require their own reviewed saved plan and authorization; approval for a Slack drill does not authorize an apply or IAM change. Restore synthetic healthy signals and end only the drill’s mutes at timeout or abort, verify evaluator recovery, and retain evidence even when delivery fails.

Capture original signal, evaluator Pending/Firing (where exposed), provider notification, human-confirmed Slack alert, evaluator recovery and Slack recovery times. Record provider last_notified separately from the user’s confirmed Slack message timestamp/permalink. Measure detection and delivery intervals with actual ingestion/evaluation delays. Prove absence of duplicate service paging, maintenance silence and expiry behavior, and the independent watchdog route. No downtime-to-Slack claim is valid until those live artifacts are inspected.

Qualification and incident ownership

Datadog owns primary staging service notifications to the confirmed #engineering-observability integration. Grafana evaluates service rules in shadow mode; only the separately authorized, exactly labeled synthetic test can notify. Cloud Monitoring owns the independent probe-heartbeat absence path outside GKE and Grafana. Its heartbeat demonstrates probe execution and direct publication, not collector health or clinical workflow success.

The product on-call owner handles service and overdue-work symptoms. The runtime infrastructure operator handles probe authentication, scheduler execution and state publication; the observability operator handles collection, backend freshness, routing and storage. Use the affected service/environment and stable resource identity in the alert, never patient, conversation or run IDs as metric labels. Correlate a run only in the authorized trace/log investigation surface.

  1. For readiness alerts, inspect the probe’s fixed outcome and freshness first. Authentication failure or login redirect is not application success. Check IAP audience and caller grants without exposing tokens; do not bypass IAP or internal worker ingress to make a probe green. To check reachability on demand, run workspace-tools observability-drill probe --output-dir DIR. It executes one probe slot as the probe identity, the only rehearsal caller IAP admits, and fails unless every target’s readiness sample and the heartbeat read back as successful. A workstation identity token carries gcloud’s own audience, so IAP answers it with 401 by design.
  2. For physician work, read the worker’s queue gauges. Each physician-worker instance writes them every minute from the Postgres rows that own the work, on the global resource and labelled only with its instance id: custom.googleapis.com/coda/physician/queue/oldest_due_seconds (how long the longest-waiting due turn or reply revision has been runnable), .../due (how many are runnable now) and .../failed (how many ended failed and wait for the physician’s Try again). worker_oldest_due alerts when due work has waited past 300 seconds throughout five minutes, and its absence means no worker is reporting; worker_due alerts when due work persists for 30 minutes; worker_failed alerts on any failed work. Datadog imports these gauges only with datadog_gcp_global_location_enabled; Grafana Cloud reads them from Cloud Monitoring directly. Compare them with the worker processing/retry contract and the attempts saved on the rows before acting; do not retry work automatically. Investigate Redis using the configured exact resource scope and the cloud console.
  3. For Cloud SQL, each alert names its instance: physician_* is rust-physician, duet_* is rust-duet. Start from the instance’s overview and Query insights in the cloud console.
    • *_sql_up: Cloud SQL itself reports the instance down for five minutes. Check its operations log for maintenance, a restart or a failover before touching the services that use it.
    • *_sql_cpu and *_sql_memory: the fraction stayed above 0.9 for 15 minutes. The staging tier is shared-core, so a long query, a vacuum or a backlog of worker turns can hold it there; find the statement in Query insights first, and resize the tier only for sustained load the product should carry.
    • *_sql_connections: open backends across the instance’s databases stayed above 80 of its max_connections of 100 for 15 minutes. New connections fail at 100. Compare each service’s pool size and instance count with the limit, and look for connections left idle in a transaction.
    • *_sql_storage: the disk is more than 85% full. Look for unexpected table growth before raising the disk size.
    • *_sql_up telemetry absent: Datadog stopped receiving the instance’s metrics. That is monitoring loss, not an outage; check the GCP integration’s permissions and namespace settings, and the instance’s state in the console, before acting on the database. The instance’s other SQL monitors raise no absence alert of their own, so the loss pages once; an alert of theirs already firing keeps its state and reminders until its data returns.
  4. For missing telemetry, inspect Cloud Scheduler/job execution and the direct Monitoring series separately from collector availability, exporter failures, queues and Datadog ingestion. Keep heartbeat absence distinct from a failing target. A cleared sparse counter or retired pod is not confirmed recovery.
  5. For Grafana/collector loss or storage pressure, inspect stable workload readiness, restart/OOM evidence and mounted PVC used/capacity series. Do not resize from host-memory percentage alone or retain stale node groups as current workload failures. Use the private stack access procedure and provisioned dashboards; preserve IAP and private access.

Follow the infrastructure README’s maintenance and rollback procedure for scoped, expiring mutes and reviewed saved-plan rollback. Keep the independent watchdog active during collector or Grafana maintenance. Image-only releases must preserve sidecars, environment, IAM and networking; an ordinary release’s before/after assertion is part of qualification, not an infrastructure override.

Periodic qualification and every material monitoring change need revision-bound proof. Local mock plans, synthetic OTLP, isolated Grafana evaluation and offline receipt validation prove regression contracts only. They do not prove cloud IAM/token handling, Datadog query/ingestion, real Slack delivery, real dependency failure, deployed volume retention or production evaluation delay. Record those as separate gates and label each exercise simulated signal or actual component failure. An authorized live drill must capture signal → pending → firing → exact Slack receipt → recovery with UTC timestamps and cleanup, plus the independent monitoring-loss route. Do not claim downtime notification readiness until those observations exist. Production is outside this procedure.

From alert to run

  1. Open the primary Datadog notification from the confirmed alert_notify destination. Grafana evaluates equivalent operational rules in shadow mode; it does not send service notifications. Both evaluate the same four alerts (service 5xx rate, service p95 latency, physician chat generation errors, asynchronous failures) with the same thresholds. Check the environment, service, release version and incident time window. HTTP failures and latency cover service requests; asynchronous worker failures need a separate signal because the originating request can already have succeeded.
  2. Follow the error log’s trace link. The worker attempt and generation spans carry canonical correlation; a broker message ID identifies a delivery, not an attempt. Copy coda.run_id, coda.work_id, any predecessor ID, and the trace ID. Preserve the query window and release version with the evidence. Under grafana, reach Grafana with kubectl -n observability port-forward svc/grafana 3000 and use Explore over the alert’s window:
    • Loki to Tempo. Query the failing service, for example {service_name="physician-worker"} | severity_number >= 17. Expand the line and follow its trace_id field’s “Open trace” link into Tempo.
    • By run. {service_name="physician-worker"} | coda_run_id="<run id>" finds a run’s log lines that carry it (Loki turns dots in attribute names into underscores); in Tempo, TraceQL { span.coda.run_id = "<run id>" } finds its spans.
    • Tempo to Loki. From a span, “Logs for this span” queries Loki on the same service and trace_id.
    • Rates and latency. Prometheus traces_spanmetrics_* series by service; exemplars open the matching traces.
  3. An authorized product operator reads back the matching persisted attempt from physician Postgres, scoped to the intended practice and physician. Chat attempts are in the state.attempts collection of physician_runtime_conversations; current reply-revision attempts are in physician_runtime_reply_drafts, and earlier accepted revisions are archived in physician_runtime_reply_revisions. Match the exact attempt ID, its work and any persisted predecessor relationship, and its terminal status. Project only those operational fields into the evidence: do not export the surrounding conversation, chart, instructions or model records to Datadog or Grafana. Never use a retry’s newer attempt as proof for the originally alerted attempt.
  4. In Langfuse (https://hipaa.cloud.langfuse.com), find the generation with the same trace ID and coda.run_id. A trace may contain several attempts, so verify both identifiers. The environment is coda.origin, and tags include coda.job. Input/output exists only when content capture was explicitly enabled; absent content is expected under the default policy. A failure before a model call must not be presented as a completed model generation.
  5. Restore healthy operation and confirm recovery at the notification destination. Retain the notification, trace/log query, scoped attempt readback and Langfuse observation against the tested release. Collector configuration or an empty vendor search is not evidence of delivery or privacy.

workspace-tools observability-drill langfuse alert-to-run walks steps 2 and 4 on a rehearsal turn it sends itself. The chat snapshot names the attempt that answered (runs holds the run once a turn is answered, held or failed, and an answered run’s attempt_id names the attempt); the drill finds that attempt’s span in Datadog by coda.run_id, reads its trace’s generation span, then the Langfuse trace, and fails unless the attempt id and the trace id (Datadog’s 64-bit id is the low half of the 128-bit one) agree across all four.

Langfuse drills

Staging physician chat sends its generations to Langfuse with content, because its rehearsal traffic is synthetic. workspace-tools observability-drill langfuse proves that on the deployed stack, one action per run, each writing langfuse-<action>-<UTC stamp>.json with the deployed revisions it ran against:

ActionWhat must hold
rehearseA canary turn sent as the rehearsal physician answers, and Langfuse holds its generation in environment simulation, with the scenario, the chat as session, coda.run_id, a 128-bit trace id and the canary in its input or output.
alert-to-runThe same turn found from Datadog: the snapshot’s attempt id, the attempt span, the generation span and Langfuse agree on coda.run_id and the trace id, and the attempt span records coda.trace_relation link: the attempt started its own trace linked to the request that accepted the turn.
isolationLangfuse holds the canary (the positive control) under the snapshot’s attempt; the operations spans of the same trace exist in Datadog, and in Tempo under grafana, with model and usage, and no canary anywhere; Datadog Logs, and Loki under grafana, hold the physician logs of the same trace (their positive control) and no physician log event since the turn carries the canary in any field.
chat-failureThe physician chat failure monitor is OK, then the drill sends one more canary turn than its threshold, each marked [fail:1]. Every turn answers on a retry and the monitor fires. For one turn, the answering attempt’s span names the failed attempt as its predecessor in the same coda.work_id; the failed attempt’s span has error.type rehearsed; the monitor’s own query, narrowed to that attempt, finds the error generation in the failed attempt’s trace; and Langfuse holds that attempt’s generation in the same trace at level ERROR, with the canary. Both attempts’ spans record coda.trace_relation link to the accepting request. Datadog holds no canary in either attempt’s trace, and the monitor recovers after its 10-minute window.

The rehearsal physician is the physician-rehearsal service account. Its turns belong to a practice in physician_simulation_practices (rust-environments), so the worker labels them simulation; a turn in any other practice stays real whatever it sends. The operator signs in with gcloud as one of physician_rehearsal_signers, which may mint the account’s IAP token through IAM signJwt; POST /auth/rehearsal then admits exactly that principal. Every kubectl call names the staging context gke_coda-rust-staging_us-east1_rust-observability, so an ambient context is never used; the drill opens its own port-forwards to Tempo and Loki, reads Langfuse at LANGFUSE_BASE_URL with the project keys, and reads those and the Datadog keys from Doppler coda-rust/stg without printing them. Every receipt records the Langfuse origin it read as langfuse_host.

Every wait runs under the exercise’s 40-minute cap and the operator’s Ctrl-C. A readback request that times out or cannot connect, as a port-forward may, counts as one of the wait’s polls; an error status or a malformed answer ends the run at once, and a wait whose every poll failed reports the last failure. The Langfuse export monitors in langfuse-monitors.tf, behind langfuse_monitors_enabled, page when the collector cannot deliver to the hosted project; no drill takes the hosted project down to fire them.

chat-failure pages #engineering-observability, so it needs --confirm, and runs only with the operator’s approval for that window. Its failure is the worker’s own: a rehearsal turn marked [fail:K] fails its first K attempts before any model call, with error.type rehearsed, and the worker runs it again once its retry backoff is due. Only a practice in physician_simulation_practices on the staging-preview profile honours the marker; a real practice’s turn answers whatever it says. The monitor is chat_generation_errors in datadog.tf, on in staging through chat_failure_monitor_enabled while the other service monitors stay off. The drill writes its own exercise, group staging/physician-chat-failure, to the same observations-langfuse-<stamp>.json ledger: the first marked turn, the monitor’s firing, the restore right after it (every marked turn has answered by then, so the failures have stopped), and the monitor’s recovery; a person adds the Slack alert and recovery.

Validation

The observability job in CI validates, inside nix develop .#observability, the collector and OpenTofu shell, the base collector alone; the base with each local overlay (debug, Datadog, Grafana); the authenticated GKE gateway with each backend, with and without Langfuse; and the inline sidecar. It checks the compose file with each profile, verifies the Tempo, Loki and Prometheus configs with their pinned images, and validates and runs mocked OpenTofu tests for both observability and rust-environments. Backend-free initialization belongs in a fresh test checkout, never over an operator’s initialized backend.

Run the synthetic collector behavior test separately:

nix develop .#agent --command python scripts/test_collector_privacy.py          # both backends
nix develop .#agent --command python scripts/test_collector_privacy.py grafana  # one backend

It runs the production file order with the datadog or grafana overlay last and exercises content stripping with positive controls, authenticated caller filtering, and bounded queues during exporter outages. The generated evidence under target/verification is local proof, not evidence of deployed delivery.

The Grafana alert rules fix their thresholds in dev/observability/grafana/provisioning/alerting/rules.yaml, because Grafana provisioning has no defaults for unset variables. A precondition in infra/gcp/observability fails the plan under grafana unless they equal the threshold variables the Datadog monitors use, so change both together.

Build, CI, and release

This page links the owners of each release path. Each owner keeps its own procedure.

Continuous integration

  • .github/workflows/ci.yml owns pull-request and main checks plus the existing staging deploys. Every run checks engineering skills and documentation. CI selection adds the full Rust, database, infrastructure and image suite for product/build or mixed changes, and the runtime clinical skills/ count as product; unavailable comparisons also select full. A change under crates/workspace-tools/sandbox/ selects only the sandbox job, which runs nix flake check ./crates/workspace-tools/sandbox; a root Cargo.toml or Cargo.lock change selects it beside the full suite, and CI result requires it whenever it is selected. Browser tests are ignored by the ordinary test harness; their explicit targets run on workflow_dispatch. A green routine CI run does not establish browser qualification. The workflow and its comments own the exact step list.
  • main takes pull requests through GitHub’s merge queue, set in the repository’s main ruleset. A pull request passes CI result on its own branch and need not be level with main. Merging it, or auto-merge, adds it to the queue, which builds a candidate from main, the entries ahead and this pull request, and runs the workflow on that candidate as a merge_group event. The pull request merges when the candidate’s CI result passes, so other merges do not send it back for another branch update and run. A candidate is scoped by what it adds to the commit it was built on, runs no deployment, and saves no build cache.
  • The other jobs are foundations (offline cloud foundation contracts and mocked release adapters), images (the locked Nix images, built and run but not pushed), postgres (fresh migrations and the Postgres proofs), observability (the collector config and its OpenTofu roots), and cargo-deny (which applies deny.toml).
  • deploy-public-site-staging applies the public site’s reviewed staging plan after full validation on pushes to main only when the repository variable PUBLIC_SITE_STAGING_DEPLOY is enabled (public site).
  • .github/workflows/promote-public-site.yml is a manual workflow that promotes the image staging tested for one main commit to public-site production, with the production environment’s approval (promotion).
  • .github/workflows/doppler-watch.yml is a separate daily workflow that watches the pinned Doppler CLI for releases and advisories.
  • PStack skill updates pushes codex/update-pstack-skills when the vendored verification skills differ from upstream and opens or refreshes a review PR when Actions PR creation is enabled, or opens or refreshes a tracking issue with a compare link when repository settings disable Actions PR creation. It deletes the update branch and closes any open tracking issue once main is current. A maintainer with write access approves CI runs on any resulting PR.
  • deploy-staging runs after full validation on pushes to main only when the repository variable RUST_STAGING_DEPLOY is enabled. It downloads the successful image proof’s archives from the same run, verifies their commit and checksums, and publishes those exact images without rebuilding. It runs both migration jobs and moves the coda-rust-staging services to Ready revisions on the new digests. physician-worker is updated once the scaling plan has created that service; direct staging rollout describes the three-day artifact retention, retry behavior and how to turn it off.
  • The staging release command in workspace-tools owns rollout receipts and final-state reconciliation. It updates only each service’s product container image and refuses a rollout that moves a sidecar or any other infrastructure-owned field (direct staging rollout). A partial rollout or unknown traffic is not success. Operating limits and failure investigation distinguishes declared resource limits from verified spending controls; privacy recovery describes the additional Duet restore gate. Mocked release tests and successful image checks do not qualify a hosted database restore.
  • Skills/docs-only main pushes skip both deployments. A successful CI result confirms the selected checks passed, not that a deployment occurred.
  • rust-toolchain.toml is the one Rust pin. The Nix packages and dev shells read it through nix/rust-toolchain.nix, the ci job installs it with rustup, and cargo-deny runs on it. A toolchain bump is its own PR, and ci_scope.py treats it as a dependency change. The Rust cache key includes the version, so it only changes in that PR.
  • A weekly schedule run on main takes the full path without browser qualification or deployments. Restoring the rust-v2-* and postgres-*-shard* entries keeps them from being evicted after seven idle days, so the first PR after a quiet week starts warm. The private Nix cache has no idle expiry, so only main pushes publish to it. workflow_dispatch also runs the full path, plus browser qualification.
  • Postgres shard caches save one entry per main or scheduled commit, so concurrent merges don’t race for a key. Restores fall back from the same dependency set to the same shard. A PR saves only when main had nothing for its dependency set.
  • Rust build caches are best effort. A restore, save, or cache-size failure can make the next build slower; it does not invalidate passing checks.
  • CI installs wasm-bindgen, mdBook, and lychee from pinned, checksum-verified release archives, not with cargo install. The comments next to each install step give the reason for its pin.
  • CI makes no anonymous GitHub downloads that it can authenticate, because GitHub throttles anonymous traffic first. Release archives (release-archive, with curl, since the act image has no gh) and the Doppler CLI come through the GitHub API with the job token; github.com download URLs ignore the token. OpenTofu fetches providers from those URLs and cannot send a token, so tofu-providers caches them per job, keyed on the committed lock files.
  • CI runs on GitHub-hosted ubuntu-24.04 runners and serves actions/cache from GitHub’s workflow cache. .actrc maps ubuntu-24.04 and custom runner labels to the act image, and .github/actionlint.yaml declares self-hosted labels outside GitHub’s hosted set.
  • The repository variable CI_JOB_RUNNER moves the ci job to another runner label (such as cyrene-coda); deleting it returns the job to GitHub-hosted ubuntu-24.04.1
  • Run the workflow locally with act from nix develop; it needs the host’s Docker daemon, which the shell does not provide. .actrc selects the runner image and the ci job. Check the workflow with actionlint .github/workflows/ci.yml. Where there is no Docker, coda-sandbox ci run [<repo-path-or-commit>] --job <job> from crates/workspace-tools/sandbox/ runs the job of a committed revision the same way on a self-hosted CI spool, with no secrets, and exits with its status.1
  • .githooks/pre-commit runs the same rustfmt and clippy steps before a commit.

Private Nix binary cache

infra/gcp/nix-cache owns an isolated private GCS bucket and bucket-scoped reader/writer identities. Select its project and remote-state backend explicitly; apply only an operator-approved saved plan. It does not own product deployment permissions. Nix uses GCS’s S3 interoperability endpoint, so its HMAC credentials are distinct from the WIF credentials used by deploy jobs.

Keep HMAC and signing secrets in Doppler, outside OpenTofu state. Deliver the reader credentials to CI separately from the writer credentials. The reader HMAC pair is a repository secret, because every Nix job reads the cache and most run outside any environment; it grants only object reads on this bucket. The GitHub nix-cache-write environment must restrict deployment branches to main before installing any writer or signing secrets. Never put those secrets at repository scope: a workflow condition alone cannot protect secrets from edited PR code. Only the nix-cache-publish job enters nix-cache-write. It runs on a main push after images passes, rebuilds the allowlisted roots from the cache, and uploads them. images itself holds no cache-writer secrets on any event. Changing cache trust or rotating its signing key requires operator review. Publishers share the nix-cache-main-writer concurrency group because create-only object permissions cannot safely handle simultaneous uploads of the same object. An active publisher is not cancelled; GitHub may replace an older pending one with a newer one, whose closure supersedes it. The image proofs, CI result and deployments stay outside that group and do not wait for publication, so a burst of merges cannot cancel them. Any additional publisher must use the same serialization policy rather than weakening the bucket permissions.

The cache retains compiled dependency artifacts as well as application outputs; final image closures alone do not retain the intermediate Rust compilation work. Native server, WebAssembly and patient-bank builds keep separate dependency artifacts in nix/packages.nix. Cache reads preserve Nix’s signature verification and the upstream substituter. A cache miss or outage must still run the build and all image proofs. Disabling NIX_CACHE_ENABLED restores the uncached workflow without changing the proof commands.

The cache contains private build inputs and outputs. Do not make the bucket public or copy credentials into the Nix store. Object-age deletion is not a safe cache garbage collector: deleting a NAR while retaining its metadata or references can break substitution. Retention changes must account for the reference graph.

Local cache warming with act

The local workflow builds the same allowlisted roots as the hosted writer: three dependency artifacts, six runtime, migration and job images, and the three dev shells CI enters (agent, release, observability). It only warms the binary cache; it does not load or push images, deploy services, or replace the hosted image proofs. Hosted publication remains a protected main-push operation. Local publication is an explicit operator-authorized exception for a reviewed, full commit SHA. Serialize it with every other writer: do not run it while a hosted or another local publication is active. act does not participate in GitHub’s writer concurrency group.

Use a clean, standalone checkout containing the reviewed commit, not a linked worktree: act copies files into the container, and a worktree’s .git file points outside that copy. A local git clone --no-hardlinks /path/to/repository /path/to/cache-warm-checkout provides a standalone checkout without a GitHub token; check out the reviewed SHA there. Commit the reviewed changes before running; do not bypass cleanliness checks. The workflow verifies HEAD and tracked/untracked changes before installation and credentials, and the publisher rechecks the revision. Never pass unreviewed local code signing credentials.

From that checkout, enter nix develop .#agent. First check workflow selection and syntax without credentials or a build:

EXPECTED_SHA="$(git rev-parse HEAD)"
act workflow_dispatch -W .github/workflows/nix-cache-local.yml -j nix-cache-local \
  --var ACT=true --input expected_sha="$EXPECTED_SHA" \
  --env-file /dev/null --secret-file /dev/null --var-file /dev/null --input-file /dev/null \
  --container-daemon-socket - --list
# Repeat the command with --dryrun instead of --list to validate step planning.

The explicit -W and -j nix-cache-local are required: .actrc defaults to -j ci. Both the manual event and the local ACT checks are required; a hosted manual dispatch cannot publish. The installer uses cachix/install-nix-action@v31 with --no-daemon: its single-user branch clears build-users-group and exports the user profile, without systemd. The container uses its own disposable /nix, with sandboxing disabled inside Docker. Do not add host /nix, systemd, home, credential or Docker-socket mounts, --bind, --privileged, or --reuse. The Docker daemon is needed by act on the host, not inside the job. A cold build can need substantial time and disk space.

For an authorized write, first record the current NIX_CACHE_ENABLED repository variable, set it to false with operator approval, and wait for active hosted writers to finish. This pauses private reads as well as writes. Restore the exact previous value after the local run, including failures. Do not assume a local lock coordinates with GitHub’s concurrency group.

The launcher fetches only seven named settings from Doppler: bucket, public key, writer HMAC pair, signing key, and reader HMAC pair. It passes names rather than values on act arguments; no unrelated Doppler secrets are forwarded. The writer HMAC remains bucket-scoped and create-only.

# Inside nix develop .#agent, with a clean reviewed standalone checkout
# and hosted publishers paused/drained under operator authorization:
python scripts/nix-cache/warm_nix_cache.py \
  --expected-sha "$(git rev-parse HEAD)" \
  --doppler-config stg_nix_cache --acknowledge-exclusive-writer

Do not use broad Doppler export/forwarding, .secrets files, literal secret arguments, shell tracing, --verbose, --insecure-secrets, or environment dumps. Only publication receives writer/signing credentials; the subsequent fresh-reader step receives only reader credentials and the public key. Publication first sends a leaf-derivation smoke closure, then the full closure twice to prove safe reuse. The reader copies the server-dependency closure into an empty disposable store from the private cache alone, without builds, and verifies contents and trust. All temporary credential files and the reader store are removed on normal failure or completion; act --rm also removes the job container on failure. Abrupt host termination can require removing that specific stopped act container/volume; do not prune unrelated Docker resources.

The helper reports stages, elapsed heartbeats, exit codes, and fixed error categories without printing raw SDK output. A heartbeat means the process is alive, not that an object was uploaded. It seeds repeated NAR content before the parallel copy to avoid create-only HEAD/PUT races within one publisher. This does not make multiple publishers safe. Unknown errors remain withheld; reproduce with synthetic local transport credentials rather than enabling verbose real-secret logs. Failures are fatal locally. No cache credentials are needed for list, dry-run, checkout verification, installation, or building from the upstream cache.

CI timing reports

scripts/ci_timings.py collects GitHub job and step timings through gh api and renders inspectable graphs with raw data. The CI result job retains a report artifact and links it from the step summary. Reporting is best effort and does not replace the required result gate. Its live snapshot excludes unfinished jobs; deployments occur after validation and must not be counted as PR validation latency. Historical comparisons separate full successful validation from lightweight, failed, cancelled and manual runs.

Secrets: Doppler

The rule is in AGENTS.md.

  • Doppler project coda-rust has the parent configs dev, stg and prd. Locally, log in once with doppler login and prefix a command with doppler run --; doppler.yaml selects dev, and the shell loads it when a login exists and continues when it does not. Creating a config is an operator step, and this repository stores no token and no secret value.
  • scripts/doppler-fill.sh names the secrets dev holds and what reads each one. It asks for each missing value at a hidden prompt and saves it to Doppler; --check lists which are set.
  • Physician and Duet services read per-product, per-role child configs, never a parent, because a parent-scoped token would carry the other product’s secrets. GCP deployment lists those configs and how each image starts under doppler run.
  • The public marketing site reads no secrets and runs without Doppler. CI installs the pinned CLI only to verify it and fetches no secrets through it; GitHub jobs reach GCP through Workload Identity Federation.
  • cargo run -p workspace-tools -- install-doppler OUTPUT_PATH (doppler.rs) installs the pinned, checksum-verified CLI for images and runners.

Retained physician infrastructure references

RootOwnsOwner document
infra/gcp/physician-runtimeThe private GKE Autopilot cluster, Cloud SQL with IAM authentication, and the site and migration identities for physician-sample and physician-authREADME, including its tofu test and validate commands
infra/gcp/foundationShared project foundationmain.tf
infra/gcp/stagingThe hosted synthetic integration platform on Cloud RunREADME
infra/gcp/clinical-evidenceThe production Clinical Evidence runbookREADME

This workspace does not run init against a backend and does not apply these roots. Apply authority stays with the product repositories and the operator of the target project. GCP deployment says what runs Duet production.

Workspace-owned roots

RootOwnsOwner document
infra/gcp/public-sitePublic-site Cloud Run: staging behind IAP, production behind the load balancer without sign-in. This workspace owns both states and applies each only from a reviewed saved plan; production applies require explicit operator authorization.Public site
infra/gcp/rust-environmentsThe isolated Rust Cloud Run environments for the physician and Duet services. It needs an administrator bootstrap before its first apply.GCP deployment
infra/gcp/shared-mailProduction mail only in coda-health-prod, with separate state and operator-approved saved-plan applies.Production shared mail
infra/gcp/observabilityThe shared collector deploymentObservability

iPhone and TestFlight

Android and Google Play

  • nix develop .#android (nix/android-shell.nix) provides the Android SDK, NDK, emulator image, JDK and a Rust toolchain with the Android standard library. Run the commands below inside it.
  • cargo run -p android -- build (crates/android) builds the debug APK for the mobile mode shell. cargo run -p android -- avd creates the duet AVD once, as CI does.
  • cargo run -p duet-stub serves the host stand-in that the emulator calls. cargo run -p android -- window opens the emulator, and cargo run -p android -- test coda.duet.ModeShellTest builds the APK and runs UI Automator (see crates/android).
  • CI’s Android emulator job runs cargo run -p android -- test --headless coda.duet.ModeShellTest on a headless emulator. For now it runs only when CI is dispatched by hand: Actions, CI, Run workflow, choosing the branch (or gh workflow run ci.yml --ref <branch>). Setting MOBILE_ON_CHANGE in scripts/ci_scope.py makes pull requests and main pushes run it whenever a change touches the APK’s build.
  • A debug APK is not a Play upload.

  1. The cyrene-coda label is a disposable Firecracker microVM on Cyrene, the developer workstation. It runs the job in the act image (catthehacker/ubuntu) rather than GitHub’s, so a step that passes under act passes there, and it starts without GitHub’s runner cache, so actions/cache restores miss. On Cyrene, agents work in the coda-agent container: Cursor connects to it with Remote-SSH, the main checkout is /agents/coda/src/coda-rust (snapshotted hourly), and git, gh and doppler get a token limited to this repository (and a read-only dev Doppler token) from a token broker on the host, which reads them from the developer’s keyring, so no token sits in a file in the container. The container cannot reach the host, the LAN or Tailscale and has no Docker; coda-sandbox ci run queues its jobs on the same Firecracker runner. coda-sandbox worktree new <slug> makes each worktree under .worktrees/<slug> with a target/ that is a reflink clone of a seed of third-party build output on the build root its config names (/agents/coda/build on Cyrene), so a worktree costs its source until a build diverges; coda-sandbox worktree --help lists the commands. Where coda-sandbox is not installed yet, run it from the checkout as nix run ./crates/workspace-tools/sandbox -- worktree new <slug>. The container, runner and their limits are described in crates/workspace-tools/sandbox/README.md, whose NixOS module declares them. ↩ ↩2

GCP deployment

Duet production is still the Python service released from coda-app; this workspace does not deploy it. The physician OpenTofu roots in this workspace are foundation, staging, clinical-evidence, and physician-runtime. The last one is the GKE Autopilot and Cloud SQL target for physician-sample and physician-auth. This workspace does not apply those reference roots. Public-site staging and production (the marketing site only) and the isolated Rust staging root are workspace-owned and require separately authorized saved-plan applies. Build, CI, and release says what each root owns.

The mail-only shared-mail root is owned here for production SMTP in coda-health-prod, with separate state and explicit saved-plan approval. This exception grants no authority over the referenced production application or clinical-evidence roots.

Staging observability spans two workspace-owned roots, applied in order by an operator from reviewed saved plans:

RootOwnsState
rust-environmentsBehind observability_cluster_enabled: the private observability Autopilot cluster on rust-private, its subnet and secondary ranges, and the reserved internal gateway address. Behind observability_relay_image: the IAP-protected observability-relay Cloud Run service, its rust-relay Direct VPC egress subnet and the reserved address of the Grafana internal load balancer. Behind observability_enabled: the collector sidecars on the Cloud Run services and their telemetry environment, including CODA_TELEMETRY_BACKEND from its telemetry_backend, which must match the observability root’s.rust-environments/stg
observabilityInside that cluster: the OpenTelemetry gateway collector and its internal load balancer, one operations backend chosen by telemetry_backend (the Datadog Agent and monitors with, off by default, the project-scoped Datadog GCP integration; or self-hosted Tempo, Loki, Prometheus and Grafana with, off by default, a Cloud Monitoring datasource), the otlphttp/langfuse exporter to the Langfuse HIPAA cloud project at langfuse_host, Grafana’s internal load balancer, which admits only the relay subnet so people reach Grafana only at staging.coda.dabney.moe/grafana/ through public-site, and the Doppler operator. It reads the cluster and network through variables fed from rust-environments outputs and manages neither. Staging only.observability/stg in the same state bucket

Observability describes the per-signal paths and the content policy.

Grafana shows telemetry that can carry PHI, so people reach it only through Google IAP, and IAP admits only group:gcp-engineering@dabney.moe plus the named service accounts a route needs to hop between services. It is not granted to allUsers, allAuthenticatedUsers, a domain: or a single user:, and it has no listener that skips IAP. Langfuse is the hosted HIPAA cloud project, under Langfuse’s BAA; access to it is membership of that Langfuse organization, not IAP. Production keeps that rule: no production observability exists yet, and the roots refuse a production cluster, relay or observability environment until a production route is designed under it. The observability boundary says how staging meets it.

Run every command on this page inside nix develop from the repository root. The shell provides gcloud, tofu, doppler, timeout and jq; do not use host copies. Commands that read Doppler secrets need the default shell after doppler login, not .#agent, which loads no credentials.

Public marketing site

The separate infra/gcp/public-site root runs the stateless Rust public-site server on Cloud Run, while static showcase exports (ORIGIN=https://dabney.moe, BASE_PATH=/coda) live under dabney.moe/coda/. Live hosted backends target coda.dabney.moe (staging.coda.dabney.moe behind direct Cloud Run IAP). The root shares no physician/Duet databases. CI deploys staging from main; production receives staging-tested images through manual promotion, and operator applies require explicit operator authorization. Public site owns the architecture, IAP and cache controls, runtime configuration, checks, and the staging and production procedures.

Rust container images

nix/packages.nix builds the Rust Cloud Run images from Cargo.lock and flake.lock. Each image tag is the git revision, and the build sets created to the epoch, so a revision always produces the same archive.

Flake outputImageRoleEntrypoint binary
physician-sample-imagecoda-physician-sampleruntimephysician-sample serving PHYSICIAN_SITE_DIR (Dioxus WASM bundle)
physician-worker-imagecoda-physician-workerruntimephysician-worker, which claims chat turns and reply revisions from Postgres
observability-relay-imagecoda-observability-relayruntimeobservability-relay, which forwards public-site’s /grafana/ requests to Grafana’s internal load balancer. It reads no secrets and starts without Doppler
duet-api-imagecoda-duet-apiruntimeduet-api, the mobile Duet API and auth service
physician-migration-imagecoda-physician-migratemigrationphysician-migrate: physician-auth, front-door, then runtime chains; packaged synthetic charts for explicit load-charts
duet-migration-imagecoda-duet-migratemigrationduet-migrate: Duet-owned chain and runtime grants, then optional front-door chain
duet-privacy-delivery-imagecoda-duet-privacy-deliveryjobduet-privacy-delivery, a bounded Luna receipt job
  • The runtime servers never migrate. They bind 0.0.0.0:$PORT, where PORT defaults to 8080. /health reports liveness. Hosted startup accepts only the explicit stg / staging-preview profile with its required stores and identity configuration; other hosted profiles refuse to start. /readyz checks the configured schemas. The startup owners are physician-sample/src/hosting.rs and duet-api/src/main.rs.
  • Each image contains the binary and the libraries it links, Doppler, CA roots, tzdata and a passwd entry for uid 65532. The image has no shell or toolchain. It runs as 65532:65532 with working directory /tmp.
  • Every entrypoint except the secret-free images (secrets = false, such as observability-relay) is doppler run --no-fallback --preserve-env=PORT -- <binary>. The Doppler CLI is the static release pinned in crates/workspace-tools/src/doppler.rs. Nix reads the version and SHA-256 from that file, so the runners and the images run the same verified binary. Cloud Run mounts DOPPLER_TOKEN from Secret Manager. No secret is in a layer or in Env, and --no-fallback keeps secrets off the filesystem.
  • scripts/check-images.sh (run with nix develop .#release) builds every image and inspects each archive. It loads them into Docker and checks rejection of missing credentials or an unconfigured hosted profile. Against disposable PostgreSQL it runs both migration images twice and explicitly imports the packaged physician chart bank twice, checking its manifest totals, zero failures and an unchanged reload. It then starts the servers to check /health 200, schema readiness 200, the WASM assets and a clean SIGTERM exit. The images CI job runs this script. Nothing is pushed.

Rust staging bootstrap and deployment gate

The isolated project is coda-rust-staging in us-east1. It is separate from coda-health-staging, which hosts the public marketing site. The root owns its GCS state under rust-environments/stg; the reviewed nonsecret inputs are env/staging.tfvars and backend/staging.gcs.tfbackend.

Review and apply a staging plan

From an authorized engineering account, inside the Doppler-authorized default nix develop shell at the repository root, with current Google application default credentials (gcloud auth application-default login). staging-reconcile reads the four existing role passwords from Doppler and passes them only to the OpenTofu child that needs them, never in arguments or output; it rotates no credentials. It refuses a failed or empty lookup before OpenTofu runs.

dir=$(mktemp -u /tmp/staging-plan.XXXXXX)
cargo run -p workspace-tools -- staging-reconcile plan --output-dir "$dir"
less "$dir/review.txt"

plan creates the owner-only directory outside the repository, saves the plan, its review text and a manifest binding the plan’s digest to the root’s configuration digest and the fixed staging backend. The plan, review and diagnostics.log can contain credentials: never publish or attach them.

STOP: review every change and obtain operator approval before continuing. Unexpected deletes, replacements, IAM/network changes, image changes, or new billable resources require investigation and explicit approval. Coordinate with releases so no deployment races the saved plan. Do not use -target or -refresh-only to hide differences. Image digests remain release-owned.

cargo run -p workspace-tools -- staging-reconcile apply --plan-dir "$dir" --authorize-staging-apply
cargo run -p workspace-tools -- staging-reconcile verify --plan-dir "$dir"

apply refuses a plan whose bytes, root inputs or backend changed since review, and applies a plan at most once. A failed, timed-out or interrupted apply is uncertain: inspect state, the lock and live resources rather than retrying. verify runs a fresh plan that must report no changes, then requires the physician service’s scaling, CPU and egress settings from the reviewed plan, a Ready latest revision and all traffic on it. It writes a nonsecret *-verification.json receipt and exits 3 on any difference. Securely dispose of the directory when no longer needed.

Review the saved plan before any separately authorized apply. Engineering-group access owns routine infrastructure administration and state access. Project IAM, custom-role changes and billing administration remain with Dev. The administrator bootstrap installs conditional database IAM grants before databases exist, so later database activation does not itself need another project-IAM grant.

Engineering-group access includes Identity Platform administration for Duet’s hosted sign-in setup. This root does not create domain mappings.

The foundation comprises the private network and SQL peering, five service accounts, GitHub WIF, immutable application registry, four empty Doppler bootstrap secret slots with separate readers, CI grants and 30-day logs. Budgets sit outside this state so an engineering plan does not need billing-account access. The committed staging inputs enable a staging-preview: two db-f1-micro SQL instances (rust-physician, rust-duet, private IP only), both migration jobs and the physician and duet Cloud Run services behind direct IAP for iap_group. Each service reaches Ready only through its /readyz startup probe against its own database.

A new environment needs these operator steps, in order:

  1. Create the per-role Doppler configs stg_physician_runtime, stg_physician_migration, stg_duet_runtime, stg_duet_migration and stg_sql_admin, each with a generated DB_PASSWORD. Plans read the four application passwords into TF_VAR_database_passwords; no value is committed. Database-enabled plans reject missing or blank values. Foundation-only plans need no database credentials. Password rotation is explicit through database_password_versions.
  2. Apply the databases, then set the postgres password from stg_sql_admin.
  3. Run bootstrap-grants.sql once per database from a one-off postgres:17 Cloud Run job on rust-private, with the admin password mounted from a temporary secret. Before the script, revoke cloudsqlsuperuser from both application users (Cloud SQL grants it to API-created users) and grant the migration user to the administrator so it can transfer schema ownership. Delete the job and temporary secret afterwards.
  4. Write the database URLs into the four role configs, mint a read-only Doppler service token per config into the matching *-doppler-token secret, and record the versions in doppler_token_versions.
  5. Apply the migration jobs, execute both (a second execution is a no-op), then apply the services.

Reconcile staging configuration

Do not patch Cloud Run flags by hand. Use the saved-plan procedure for approved corrections; its verify compares live physician settings with the reviewed plan, which follows env/staging.tfvars and the physician scaling and SMTP relay contracts. Repeat verify after the next separately approved release. If settings regress, fix the release owner rather than reapplying in a loop.

A Ready revision is not database or journey qualification; use the existing rollout, scaling verification and isolated recovery procedures. Correct and rerun failed browser qualification; an infra apply does not waive it.

Staging sign-in accounts

physician-migrate ensures the accounts listed in PHYSICIAN_STAGING_ACCOUNTS (email|Display Name|admin or …|physician, comma-separated) exist in roger-synthetic-practice. Each email gets its own physician id. The list and CODA_HOSTED_PROFILE=staging-preview come from migration_environment in env/staging.tfvars; any other profile refuses the list. A rerun never reactivates or edits an existing account, so an administrator’s deactivation sticks. This is the staging physician-account bootstrap. /auth/invitations invites roster patients to Duet; it does not create physician accounts.

Sign-in and invitation mail uses the shared gmail transport. The Workspace relay option uses these values in stg_physician_runtime:

PHYSICIAN_MAIL_TRANSPORT=smtp-relay
PHYSICIAN_MAIL_FROM=signin@dabney.moe
PHYSICIAN_PUBLIC_ORIGIN=https://staging.coda.dabney.moe/physician

The sender is Coda Health <signin@dabney.moe>. It requires no mailbox, Gmail settings change, OAuth grant, or SMTP password. Delivery connects to smtp-relay.gmail.com:587 with mandatory STARTTLS. A configured but invalid transport stays in mailed mode: the sign-in API does not return the token. The existing Gmail API option remains available through PHYSICIAN_GMAIL_FROM and its credentials. With neither transport configured, local proof mode still returns the code.

Enable the relay in this order:

  1. Review a saved plan with enable_physician_smtp_relay=true and obtain separate apply authorization. It adds one regional IPv4 address, a Cloud Router and Cloud NAT on rust-run, and moves only the physician runtime to ALL_TRAFFIC. The release contract carries that choice so later image releases preserve it.
  2. In Workspace Admin, add an SMTP relay rule for domain-owned addresses, authenticated by only the exact physician_mail_egress_ip output, with TLS required. Do not enable SMTP authentication or add a Workspace user.
  3. Deploy the relay-capable image through the staging release path, then set the three Doppler values above and start a revision that reads them. The site builds its mail transport at startup.
  4. Send an explicitly approved test message and verify recipient delivery, the branded sender, sign-in, reload, sign-out, and rejection of a reused link.

Staging synthetic charts

The physician migration and site images carry the charts and manifest from the synthetic patient bank, built offline from accepted ledgers and their seeds at the image’s revision. PHYSICIAN_SYNTHETIC_CHARTS names the packaged folder: physician-migrate load-charts imports the practice’s initial records into physician Postgres, and the staging site (CODA_HOSTED_PROFILE=staging-preview) registers the synthetic adapter against that folder so live source checks and reconnect commands run against the packaged bank and persist deliveries and source standing in physician Postgres.

After a successful schema migration and account bootstrap, a staging operator with run.jobs.runWithOverrides loads the charts explicitly. The CI release role does not have this permission.

gcloud run jobs execute physician-migrate --project coda-rust-staging \
  --region us-east1 --args=load-charts --task-timeout=30m --wait

Read the summary in Cloud Logging using the execution name returned by that command:

gcloud logging read \
  'resource.type="cloud_run_job" AND resource.labels.job_name="physician-migrate" AND labels."run.googleapis.com/execution_name"="EXECUTION_NAME"' \
  --project coda-rust-staging --format='value(textPayload)'

The longer deadline applies only to this full-bank import execution; the job’s default schema-migration deadline stays unchanged. The execution must report the packaged bank’s patient and record totals and zero failures. After a completed import, repeating the same image’s import must report zero changed records. A failed or timed-out import can be retried: completed patients remain stored, and a retry can still report changes for the rest. The command requires the staging-preview profile and preserves panel choices. The execution override leaves the job’s default schema-migration command unchanged; ordinary deploys do not load charts. Verify imported patients and their charts through the normal signed-in physician roster before treating the staging journey as qualified.

Direct staging rollout

The harness cutover needs a one-time reset of the Chords runtime tables before its first release. The automatic deploy below does not perform it. After the cutover, each physician runtime schema change is a new migration in the runtime chain, and the migration job applies each one once.

The deploy-staging job in .github/workflows/ci.yml runs on pushes to main, after every check job, when the repository variable RUST_STAGING_DEPLOY is enabled. It authenticates through the GitHub staging environment’s GCP_WORKLOAD_IDENTITY_PROVIDER and GCP_DEPLOYER_SERVICE_ACCOUNT (with GCP_PROJECT_ID and GCP_REGION), then:

  1. downloads the successful images job’s tested archives by immutable artifact ID from the same workflow run. staging_images.py checks the complete manifest, source revision and archive checksums before cloud authentication. It pushes those archives to apps/ tagged with the commit, checks that each published image’s configuration digest (including its uncompressed layer identities) matches the tested image, and records the registry digest. It never rebuilds an image;
  2. checks the shape of the physician and duet services before any migration runs, then for physician, then duet: updates <app>-migrate to the migration digest and executes it to completion, then for physician updates physician-worker once that service exists, then updates the <app> service’s product container to the runtime digest and requires its latest Ready revision to serve that digest with all traffic. The update is submitted with --async and readiness is polled every 5 s for at most 10 minutes, within the release’s overall command budget. Polling stops early when the submit failed and two consecutive reads, 5 s apart, still show a different image in the service spec. The release then stops with an unconfirmed rollout rather than waiting out the poll bound;
  3. updates observability-relay to its digest once the service exists, with the same checks. physician-worker moves before the physician site in step 2, so a site that announces turns in Postgres never serves ahead of a worker that listens for them. Until a service exists the release reports the digest to record as images.physician.worker or observability_relay_image for the infrastructure apply;
  4. finalizes and uploads the structured receipt.json, tested-archive manifest and digest files as the release-receipt-* artifact, including failed runs. staging-release initializes the receipt before publication and checkpoints before rollout mutations. It retains previous and observed final service states, migration execution IDs, explicit worker bootstrap skips and sanitized failure codes. Missing receipts and failed uploads fail visibly. Reconciliation is observational: it never reexecutes an uncertain migration or silently rolls traffic back.

The tested archive artifact is produced only while staging deployment is enabled and retained for three days. A failed-job rerun uses the original successful image job’s artifact ID; rerunning the image job creates a new artifact for that attempt. A missing, expired or invalid artifact stops the release; rerun the image proof to produce a new handoff.

Cloud Run moves traffic only to a revision that passes its /readyz startup probe. This protects an individual failed candidate, not the whole release: the worker can already be serving a new revision when the physician site or Duet fails. A timed-out update can also have completed remotely. Inspect each service’s observed traffic before deciding what to do; an unavailable read means unknown, not unchanged. Fix forward by default. Returning traffic to a previous digest requires proof that it can use the migrated schema; never reverse migrations automatically. OpenTofu ignores the image fields, so a later saved-plan apply does not roll the services back. Unsetting the variable stops staging deploys without editing the workflow:

gh variable set RUST_STAGING_DEPLOY --body enabled   # on
gh variable delete RUST_STAGING_DEPLOY               # off

The release changes one field per service: the product container’s image. staging-release checks each service’s template around its gcloud run services update:

  • Before. Before any migration runs, each existing service’s template must have one unnamed container (observability-relay: one container named after the service), or exactly the product container (named after the service) and an otel-collector sidecar. With the sidecar, the product carries the telemetry environment (DD_ENV, OTEL_EXPORTER_OTLP_ENDPOINT, CODA_LOG_FORMAT=json, CODA_TELEMETRY_CONTENT of none or full, CODA_TELEMETRY_BACKEND), the sidecar carries its gateway configuration and takes no port. Any other shape stops the release. A two-container service is updated with --container <service>, so the image never lands on the sidecar, and the served image is read from the container named after the service.
  • After. Once the new revision serves the image, the template must equal the old one except for that image and gcloud’s client annotations and labels: same containers, environment, resources, CPU allocation, probes and scaling. A lost sidecar or any other moved field fails the service’s rollout and stops the release before the next service.

Sidecars, telemetry environment, CPU and scaling belong to rust-environments and change only through a saved-plan apply. The release accepts either well-formed shape, so before that apply it keeps releasing the single-container services unchanged.

Telemetry sidecars and CPU allocation

With observability_enabled, each service runs an otel-collector sidecar (1 vCPU, 256 MiB) that forwards to the observability gateway. The sidecar does not change how CPU is allocated:

Servicecpu_idleMinimum instancesWhy
physicianfalse0Its Postgres authority listener and Redis subscriber run between requests while an instance is up; the worker owns accepted turns, so none has to stay up
duettrue0All work happens inside a request
physician-workerfalse1Its Postgres listener, 10 s poll and lease renewals run outside any request

Telemetry is best effort, as the sidecar’s own configuration states. Under request-based CPU, a batch queued after the last response waits until the next request or until shutdown, when Cloud Run gives the instance CPU again. At shutdown, Cloud Run sends SIGTERM to the product and the sidecar together, so the product’s final flush can race the collector’s own exit. The collector’s queue is bounded and drops on overflow, and its retries give up after 5 s. Telemetry still queued in either process when the instance stops is lost. Services never wait on it.

Cost at Cloud Run tier-1 prices ($0.000018 per vCPU-second, $0.000002 per GiB-second, instance-based) for an instance kept warm for a month:

  • physician with the sidecar: 2 vCPU and 1.25 GiB, about $101 a month instead of about $53 without it, for each instance kept up all month. It scales to zero, so it bills only while an instance is up, including up to 15 idle minutes after its last request.
  • physician-worker has the same shape, instance-based CPU and its own minimum instance, so it is kept warm all month as well.
  • duet stays on request-based billing and scales to zero, so idle time costs nothing. Instance-based CPU would have billed each warm instance for up to 15 idle minutes after every request, up to about $101 a month at continuous low traffic.

Database backup policy and RPO

database.tf and monitoring.tf enforce the database backup and recovery-point policy across stg and prd (prd adds REGIONAL high availability and requires explicit operator authorization plus configured alert notification channels before databases can be planned):

Policy itemRequirementEnforcement in rust-environments
Frequency and windowAutomated daily full backup of both product databases (rust-physician and rust-duet)backup_configuration.enabled = true, start_time = "03:00" (UTC)
Backup locationUnited States multi-region storage surviving a primary-region outagebackup_configuration.location = "us" (sql_backup_location), paired with a US-region precondition on google_sql_database_instance.app
Physician data RPOTarget 5 minutes, never more than 15 minutesContinuous PostgreSQL Write-Ahead Log (WAL) archiving (point_in_time_recovery_enabled = true), not scheduled incremental backups
Retention7 retained daily full backups and 7 days of transaction logsretained_backups = 7 (retention_unit = "COUNT"), transaction_log_retention_days = 7
Scoperust-physician owns durable physician clinical state; rust-duet pairs SQL backups with independent journal replayMemorystore (rust-physician-cache) holds only ephemeral fan-out events, Langfuse holds disposable generation trace copies, and Gmail and Spruce retain their own external source records; Duet restores require privacy recovery

monitoring.tf routes Cloud SQL backup and physician RPO alerts to database_backup_alert_channels (defaulting to availability_watchdog_channels):

  • Daily backup older than 26 hours (sql_backup_stale). Per-instance coda/sql_backup_succeeded_<app> counts STATUS_SUCCEEDED entries in cloudaudit.googleapis.com/system_event (protoPayload.methodName="cloudsql.instances.automatedBackup"), scoped by resource.labels.database_id so one product’s daily backup cannot mask the other’s. sql_backup_stale alerts when absent_over_time(...[24h]) holds continuously for 7200s (26 hours total, keeping the PromQL lookback plus 300s evaluation interval inside Cloud Monitoring’s 25-hour limit for user log-based metrics).
  • Daily backup failed or skipped (sql_backup_failed). Per-instance coda/sql_backup_failed_<app> and sql_backup_failed notify immediately when cloudsql.instances.automatedBackup reports STATUS_FAILED or STATUS_SKIPPED, rather than waiting out the 26-hour absence window.
  • Physician WAL archiving and disk backpressure (physician_sql_wal_archive_failed, physician_sql_disk_pressure). coda/physician_sql_wal_archive_failed matches archive command failed and archiving write-ahead log file .* failed in rust-physician’s cloudsql.googleapis.com/postgres.log and pages on the first failed archive cycle so low-traffic 5-minute archive_timeout cycles notify before 15 minutes of committed data are unarchived. physician_sql_disk_pressure alerts when rust-physician exceeds 0.85 disk utilization for 10 minutes from local pg_wal accumulation.
  • Cloud SQL PITR lag metric boundary. Google Cloud SQL (cloudsql.googleapis.com) exposes no Cloud Monitoring metric for point-in-time recovery-point age, latest recoverable timestamp, or silent asynchronous WAL offload lag into Google-managed Cloud Storage (write_ahead_log/*_bytes_count tracks local WAL flush and sits at zero when idle; bytes_used_by_data_type tracks stored bytes rather than lag; replication/replica_byte_lag exists only on read replicas). Automated alerts therefore catch daily backup failures or >26-hour absence, PostgreSQL archive_command failures, and pg_wal disk pressure, while actual recovery-point lag against the 5-minute target and 15-minute limit is measured only through isolated point-in-time clone rehearsals.

Disposable database recovery rehearsal

workspace-tools staging-restore is an operator command, not part of automatic deployment. It accepts only the canonical staging physician or Duet source, a successful backup and a fresh rust-restore-<product>-<run> target. Its default is read-only cloud preflight; cloud writes require both explicit execution and authorization flags. The operator must separately authorize the billable target and cleanup. The normal release identity receives no SQL administration privileges.

Run cargo run -p workspace-tools -- staging-restore --help for the command interface. Use a fresh receipt path for execution after preflight. The command creates a private PostgreSQL target sized from the source’s data disk (preflight refuses sources outside 10-50 GB), records its creation identity, restores the selected backup and waits for bounded operations. It refuses an existing target rather than trusting its name or labels. Receipts retain operation IDs, backup age, elapsed restore time and cleanup state; an interrupted create may leave a billable resource whose identity requires manual investigation. Never blindly retry or delete a target solely by its name.

When cleanup refuses because the receipt has no target_created_at (the create failed or timed out before its identity was recorded), the authorizing operator owns the investigation. Describe the receipt’s create_operation, then describe the instance and match its coda-run label to the receipt’s run_id, and its project, network and create time to the receipt. Delete it only under a separate explicit authorization, and record the result beside the receipt.

Cloud restore completion is explicitly unqualified. Before a rehearsal:

  1. Establish synthetic sentinel records through each product’s existing owners and record their identities without clinical content in the evidence bundle. Select a successful backup containing them. For Duet, retain independent privacy receipts for a deletion/withdrawal accepted after that backup.
  2. Review the target resources and operator access. Keep restored databases out of service routing, workers, subscriptions and outbound effects. Do not reuse a managed staging or production instance as a restore target.
  3. Restore each product separately. Through an isolated validation process, check the owning migration ledger, synthetic saved-state readback and runtime versus migrator permissions. Run Duet’s complete independent journal replay and check deletion/withdrawal refusal as described in privacy recovery.
  4. Record validation commands/results beside the cloud receipt, tied to the target and revision. Record measured recovery duration and recovery-point age against the backup policy; retention settings alone do not establish measured RPO or RTO. For physician PITR measurement, clone rust-physician with gcloud sql instances clone ... --point-in-time into a fresh private rust-restore-physician-pitr-<run> instance that is never attached to serving, workers, queues or external channels, verify the sentinel record timestamp, and clear the clone’s inherited deletion protection only under the separate cleanup authorization for that exact disposable target.
  5. After separate cleanup authorization, use the receipt-bound cleanup command. It checks project, creation identity, private network and drill labels before deleting only its disposable target. Record deletion completion; unresolved or uncertain creation/deletion remains an operating obligation.

Neither local Postgres recovery tests nor mocked cloud operations replace an actual authorized Cloud SQL restore and product readback. Keep those proof types separate in the release handoff. Do not reopen serving based only on a successful cloud operation or a manually asserted status.

Operating limits and failure investigation

The environment root owns resource bounds, not an aggregate spending ceiling. Its runtime and worker instance caps apply per revision, so overlapping revisions can consume more than one revision’s cap. CPU, memory, request concurrency and timeouts bound individual executions; migration jobs have one task, a 600-second timeout and no automatic retries. SQL disk growth is capped and backups/PITR are retained for seven days. Redis, SQL, minimum instances and networking can incur charges while no requests run.

On coda.dabney.moe and staging Cloud Run services, physician-sample, duet-api, and public-site share one HTTP ingress abuse boundary in ingress.rs (IngressGuard). It enforces fixed-window per-client IP rate limits (429 Too Many Requests with Retry-After and Cache-Control: no-store) keyed from the rightmost trusted X-Forwarded-For hop, strictly tightens quotas on unauthenticated auth/magic-link/OTP/invite/sync paths, rejects oversized bodies fast (413 Payload Too Large + DefaultBodyLimit), bounds concurrent in-flight non-probe requests (503 Service Unavailable), caps tracked client buckets in memory, and exempts health/readiness probes (/health, /healthz, /readyz, /api/health). Runtime knobs are CODA_RATE_LIMIT_RPM, CODA_AUTH_RATE_LIMIT_RPM, CODA_MAX_REQUEST_BODY_BYTES, CODA_MAX_CONCURRENT_REQUESTS, CODA_TRUSTED_PROXY_HOPS, and CODA_RATE_LIMIT_ENFORCE_LOOPBACK (automatically enforced when K_SERVICE, CODA_HOSTED, APP_ENV, or CODA_ENVIRONMENT is set, exempting local loopback tests otherwise).

Before a rehearsal, compare the deployed Cloud Run services/jobs, SQL settings and worker settings with the reviewed root inputs. Record identifiers and nonsecret limits, not full service descriptions containing environment values. Have the billing administrator verify the project budget’s thresholds and notification recipients, and the model-provider owner verify account limits. A budget alert is not a hard cap; a per-turn bound is not an aggregate provider limit. Record inaccessible settings as unverified rather than treating them as absent or effective. Changes to budgets, IAM or capacity need their owners’ authorization.

For a failed release, start with its workflow run and release receipt. Use the recorded execution name to find migration logs, and the recorded revision names to find runtime/worker logs. Inspect current traffic independently before a retry. Do not copy raw environment values, tokens or clinical content into a receipt or public diagnostic. For worker failures also read the attempts saved on the turn in physician_runtime_conversations: each failed attempt is recorded there with its time, and a turn that failed five times stays failed until the physician chooses Try again. A deployment check and a ready process do not establish that a clinical journey succeeded.

Physician scaling (Redis fan-out and the chat-turn worker)

enable_physician_scale lets the physician site run on more than one instance. It takes effect only together with enable_workloads. Applying it writes project IAM bindings that engineering can’t write alone. Everything it creates belongs to physician; Duet gets no cache, worker, grant or setting, and the root’s tests check this. No Pub/Sub topic, subscription or push identity exists, and the root does not enable the Pub/Sub API: turns are announced and claimed in Postgres, as the physician site chapter describes.

  • cache.tf creates the Memorystore instance rust-physician-cache: Basic tier, 1 GB, Redis 7.2, AUTH and TLS (SERVER_AUTHENTICATION). It sits on the existing rust-sql-private peering, so it has no public endpoint. It carries workspace_changed and workspace_settled between instances. Clients use fred with TLS and AUTH (PHYSICIAN_REDIS_URL, PHYSICIAN_REDIS_CA_PEM). Lag or a reconnect is a resync, and the page refetches. Sign-in and panel notices stay on the Postgres physician_authority triggers.
  • workloads.tf adds the physician-worker Cloud Run service. It has internal ingress and no IAP, IAM invoker checks stay on, and only the availability probe may invoke it: nothing pushes work to it, and its only HTTP surface is the readiness probe. The worker runs as physician-worker-runtime, which may reach only the physician SQL instance. It reads the physician-runtime-doppler-token slot and runs on stg_physician_runtime, because it needs exactly those secrets; a second token on the same config would add a rotation step without narrowing anything. It has cpu_idle = false and one minimum instance, because no request carries its work. It listens on Postgres for accepted turns, reads the due work every 10 s, claims the leased turn, runs the model, commits, and publishes workspace_changed. A turn whose worker died is taken again when its lease runs out, so recovery belongs to the worker. Every minute each worker instance also writes the queue gauges the worker monitors read, which is why its identity holds roles/monitoring.metricWriter.
  • The physician site gets PHYSICIAN_DURABLE_CHAT=1 and cpu_idle = false, and scales to zero like Duet. PHYSICIAN_DURABLE_CHAT=1 is what hands turns to the worker. CPU stays allocated because its Postgres listener and Redis subscriber must keep running between requests. Its hourly receipt compaction sweeps once when each instance starts and needs no warm instance. Duet keeps cpu_idle = true. runtime_environment may not set any of the scaling keys, and Duet may not set any PHYSICIAN_* key.

PHYSICIAN_REDIS_URL embeds the AUTH string, so it lives only in Doppler, as does PHYSICIAN_REDIS_CA_PEM. Neither value is committed.

Connection budget

The physician site and physician-worker both connect as the physician-runtime role, whose CONNECTION LIMIT is 40 (bootstrap-grants.sql). Each process opens one Postgres pool, local_product::runtime::Store::connect, and every store in it reads through that pool: the runtime store, auth, the front door and /readyz. The pool holds at most MAX_CONNECTIONS = 3 connections, waits up to 10 s for one, and closes a connection idle for 60 s. It keeps a returned connection only outside any transaction, so a request cancelled mid-transaction leaves nothing open for the next one. Each process’s long-lived LISTEN (the site’s authority feed, the worker’s wakeups) holds one of those 3 while it runs, so two remain for requests and claims.

A rolling deploy runs the old and new revision side by side, so the peak is

peak = services × max_instances × overlapping revisions × MAX_CONNECTIONS
     = 2 × 2 × 2 × 3 = 24 of 40

with max_instances at its default of 2. That leaves 16 for the migration job and operators, and keeps the peak at or below 30. The highest max_instances the role fits is 40 ÷ (2 × 2 × 3), rounded down: 3. Raising max_instances past it, or raising MAX_CONNECTIONS, needs this budget redone and the role limit changed with it.

To turn scaling on:

  1. Deploy the code first. The site that queues turns and physician-worker must be on main with a successful Deploy staging job. Skills/docs-only pushes skip that job, so overall CI success is not deployment evidence. The plan refuses to run without a digest in images.physician.worker.
  2. Decide who applies. The plan creates bindings group:gcp-engineering@dabney.moe cannot write: the worker’s project-level Cloud SQL and Monitoring metric-writer roles. Apply as the project Owner, or grant engineering Project IAM Admin conditioned on api.getAttribute('iam.googleapis.com/modifiedGrantsByRole', []).hasOnly(['roles/cloudsql.client', 'roles/cloudsql.instanceUser', 'roles/monitoring.metricWriter']), and remove it afterwards. Do not apply part of the plan.
  3. Plan, review, apply. Use the saved-plan procedure right before applying, because a saved plan goes stale once deploy-staging or another apply touches state. A scaling-only plan must not change Duet or destroy anything. Apply exactly the reviewed file.
  4. Write Redis into Doppler and start new revisions, with the commands below. OpenTofu doesn’t write these two values. Without them each process keeps an in-process bus, so the worker’s events never reach the site. Runtimes read Doppler only at process start. The AUTH string goes straight into Doppler and never reaches the screen, argv or a file.
  5. Verify. Open site tabs until labels.instanceId in the physician stream logs shows two instances, send a turn from one tab, and check the reply appears in a tab on the other instance. The turn’s row in physician_runtime_conversations should show one completed attempt.

Replacing the Memorystore instance changes its host, AUTH string and CA, so run step 4 again.

root=infra/gcp/rust-environments
tf() { tofu -chdir="$root" "$@"; }
host=$(tf output -json physician_scale | jq -r .redis_host)
port=$(tf output -json physician_scale | jq -r .redis_port)
{ printf 'rediss://:'; tf output -raw physician_redis_auth_string; printf '@%s:%s' "$host" "$port"; } |
  doppler secrets set PHYSICIAN_REDIS_URL --project coda-rust --config stg_physician_runtime --silent
tf output -raw physician_redis_ca_pem |
  doppler secrets set PHYSICIAN_REDIS_CA_PEM --project coda-rust --config stg_physician_runtime --silent
suffix=redis-$(date +%s)
for service in physician physician-worker; do
  gcloud run services update "$service" --project coda-rust-staging \
    --region us-east1 --revision-suffix="$suffix" --quiet
done

To turn scaling off, set enable_physician_scale = false and apply a reviewed saved plan. The plan removes the cache and the worker. The physician site keeps cpu_idle = false, because its Postgres authority listener still runs between requests. Then delete the two Doppler keys and redeploy.

Shared mail service

Products hosted outside the Rust VPC can use the mail-relay binary in crates/gmail. The mail-only production root owns its separate deployment in coda-health-prod; rust-environments continues to own staging. It wraps the existing SmtpRelay; it does not own product sign-in, message templates, recipients, send records or retry decisions. The physician server continues to use that same transport directly. There is one SMTP implementation and no additional mail vendor, mailbox credential, queue or persistence layer.

Build crates/gmail/Dockerfile from the workspace root for linux/amd64. It follows the existing private, digest-pinned base-image convention and builds only cargo build --locked --release -p gmail --bin mail-relay. Build/push and infrastructure apply require the normal release approvals. Configure its reviewed image digest explicitly.

In infra/gcp/rust-environments, mail_relay_image defaults to null (no service). Setting a reviewed digest and nonempty mail_relay_invokers creates an IAM-protected Cloud Run service, a runtime identity with no application-data roles, and a service-scoped invoker binding. enable_physician_smtp_relay must already be enabled: the adapter uses that existing network, subnet and NAT address, preserving the Workspace IP allowlist. It needs no Doppler token. Runtime settings are MAIL_FROM=signin@dabney.moe, MAIL_NOTIFICATION_FROM=notifications@dabney.moe, and MAIL_LISTEN_ADDR=0.0.0.0:8080.

For Gym staging, the named caller is serviceAccount:workspace-web-staging@coda-gym.iam.gserviceaccount.com. Production uses serviceAccount:workspace-web@coda-gym.iam.gserviceaccount.com on its own relay and authorized egress, managed by infra/gcp/shared-mail in a separate state. Production must not be planned or applied from the Rust staging root. Neither root grants a public invoker or routes production through staging. The mail_relay_url output is both the caller’s base URL and ID-token audience. Cloud Run IAM checks identity; the adapter does not add a second token verifier.

POST /send accepts JSON {purpose, to, subject, text, html?}. purpose is signin or notification; the service maps it to its two configured identities. Callers cannot supply an arbitrary From address. Omitted purpose uses the sign-in sender; unknown purposes are refused before SMTP. HTTP 204 means the SMTP server accepted the message, not that a mailbox received it. HTTP 422 means invalid headers or an explicit SMTP refusal. HTTP 503 means acceptance could not be established; a caller must not assume it is safe to retry. No message content, code, bearer token or SMTP response text is returned or logged by the adapter. GET /readyz returning 204 checks only process readiness, not SMTP or delivery. Gym owns its cutover and cleanup steps in authoring/web/infra/README.md in the coda-gym repository.