Skip to main content

objectiveai_cli/db/
init.rs

1//! Pool construction + schema bootstrap.
2//!
3//! No migration framework — schema lives inline as `CREATE TABLE IF
4//! NOT EXISTS` etc. that we run on every cold `init`. Idempotent: a
5//! second invocation against an already-populated database is a no-op.
6//!
7//! Connection URL strategy: the caller (`Context::db_client()`)
8//! hands [`init`] a base connect URL WITHOUT a database path — either
9//! the `postgresql://...` published in the `db` spawn lock, or one
10//! composed from `config db` via [`config_url`] when `db.address`
11//! points at a remote postgres — plus the application database name
12//! (`config db.database`, default `objectiveai`).
13//!
14//! We open two pools sequentially: a small admin pool against the
15//! base URL as-is (no path segment, so it lands on the connecting
16//! user's default database, `postgres`), used only to
17//! `CREATE DATABASE` the application database when it doesn't exist;
18//! then the real application pool against the freshly-ensured
19//! database. Schema runs inside one transaction.
20
21use sqlx::postgres::PgPoolOptions;
22use sqlx::{Executor as _, Row as _};
23
24use super::{Error, Pool};
25
26/// Inline schema applied on every cold `init`. `CREATE TABLE IF NOT
27/// EXISTS` + `CREATE INDEX IF NOT EXISTS` everywhere keeps the call
28/// idempotent — re-running against an existing database is a no-op.
29/// No migration framework: nobody is on this DB yet, and adding one
30/// would add ceremony we don't need.
31const SCHEMA: &str = r#"
32-- Every base objectiveai table lives in the `objectiveai` schema —
33-- one namespace for what used to be split across `public` and
34-- `logs`. Plugin/tool compartments (see `db::compartment`) get
35-- readonly over exactly this schema and never touch `public`.
36CREATE SCHEMA IF NOT EXISTS objectiveai;
37
38-- `tag_groups`: explicit grouping container that lets many tags
39-- share one resolved `AgentSpec` + parent lineage. The cli's
40-- `agents tags apply` either creates a group on the fly (for the
41-- `--agent` arm) or joins the new tag into an existing group (for
42-- the `--agent-tag` arm). When any one tag in a group is picked
43-- up by a live spawn, the conduit-driven upgrade flips every tag
44-- in the group from `tag_group` to `agent_instance_hierarchy` in
45-- one UPDATE inside the read transaction — see
46-- `db::message_queue::read_pending_and_upgrade_tag`.
47CREATE TABLE IF NOT EXISTS objectiveai.tag_groups (
48    id                              BIGSERIAL PRIMARY KEY,
49    -- Resolved `agents::spawn::AgentSpec`; serialized
50    -- as JSONB. References are resolved at apply-time, never at
51    -- spawn-time, so this column is always inline-or-remote.
52    agent_spec                      JSONB  NOT NULL,
53    -- The lineage prefix the spawn-by-tag will compose its AIH
54    -- against. NOT NULL: callers (CLI handlers) substitute the
55    -- cli's own `Config.agent_instance_hierarchy` when the user
56    -- omits the argument.
57    parent_agent_instance_hierarchy TEXT   NOT NULL,
58    created_at                      BIGINT NOT NULL
59);
60
61CREATE TABLE IF NOT EXISTS objectiveai.tags (
62    name                     TEXT PRIMARY KEY NOT NULL,
63    -- BOUND when set: this tag resolves to a live AIH.
64    agent_instance_hierarchy TEXT,
65    -- GROUPED when set: this tag's resolution is the tag_group
66    -- row's (agent_spec, parent). Exactly one of the two columns
67    -- is non-null at any time.
68    tag_group                BIGINT,
69    updated_at               BIGINT NOT NULL,
70    CHECK (
71        (agent_instance_hierarchy IS NOT NULL AND tag_group IS NULL)
72        OR
73        (agent_instance_hierarchy IS NULL AND tag_group IS NOT NULL)
74    ),
75    FOREIGN KEY (tag_group) REFERENCES objectiveai.tag_groups(id) ON DELETE CASCADE
76);
77CREATE INDEX IF NOT EXISTS tags_hierarchy_idx
78    ON objectiveai.tags(agent_instance_hierarchy);
79CREATE INDEX IF NOT EXISTS tags_tag_group_idx
80    ON objectiveai.tags(tag_group);
81
82-- `laboratory_attachments`: laboratory IDs attached to an agent target.
83-- The target is EITHER an `agent_instance_hierarchy` (AIH) OR a `tag`
84-- (never both — same exclusivity CHECK as `tags`/`message_queue`). A
85-- given laboratory is attached at most once per target, enforced by a
86-- partial unique index per target column. `laboratory_id` is an opaque
87-- external identifier (no labs table, no FK).
88CREATE TABLE IF NOT EXISTS objectiveai.laboratory_attachments (
89    id                       BIGSERIAL PRIMARY KEY,
90    agent_instance_hierarchy TEXT,
91    tag                      TEXT,
92    laboratory_id            TEXT   NOT NULL,
93    created_at               BIGINT NOT NULL,
94    CHECK (
95        (agent_instance_hierarchy IS NOT NULL AND tag IS NULL)
96        OR
97        (agent_instance_hierarchy IS NULL AND tag IS NOT NULL)
98    )
99);
100CREATE UNIQUE INDEX IF NOT EXISTS laboratory_attachments_tag_unique_idx
101    ON objectiveai.laboratory_attachments(tag, laboratory_id)
102    WHERE tag IS NOT NULL;
103CREATE UNIQUE INDEX IF NOT EXISTS laboratory_attachments_aih_unique_idx
104    ON objectiveai.laboratory_attachments(agent_instance_hierarchy, laboratory_id)
105    WHERE agent_instance_hierarchy IS NOT NULL;
106
107-- Latest continuation token per agent_instance_hierarchy. Upserted
108-- per streamed chunk by the chunk-yielder loops in `agents spawn`
109-- and `functions execute`. No GC, no history — querying it gives
110-- the single most recent continuation for that AIH.
111CREATE TABLE IF NOT EXISTS objectiveai.agent_continuations (
112    agent_instance_hierarchy TEXT PRIMARY KEY NOT NULL,
113    continuation             TEXT             NOT NULL,
114    updated_at               BIGINT           NOT NULL
115);
116
117CREATE TABLE IF NOT EXISTS objectiveai.message_queue (
118    id                              BIGSERIAL PRIMARY KEY,
119    agent_instance_hierarchy        TEXT,
120    agent_tag                       TEXT,
121    -- AIH of the caller who enqueued this row (sourced from
122    -- `ctx.config.agent_instance_hierarchy` at enqueue time).
123    -- Surfaced on `agents queue read pending` so callers can
124    -- audit "who asked for this" without a join.
125    sender_agent_instance_hierarchy TEXT   NOT NULL,
126    -- Content rows live in `message_queue_contents` (PK
127    -- `id BIGSERIAL`, FK `message_queue_id` → here). Readers
128    -- JOIN; no denormalized JSON shadow column lives here.
129    enqueued_at                     BIGINT NOT NULL,
130    key                             TEXT,
131    -- Soft-delete marker. Rows start at TRUE and flip to FALSE
132    -- when consumed (either via the LogWriter's MessageQueue row
133    -- write or via `db::message_queue::delete_by_id`'s in-flight
134    -- lock-race-released path). Every reader filters
135    -- `WHERE active = TRUE`, so flipped rows are invisible.
136    -- Content stays around in `message_queue_contents` (the old
137    -- `ON DELETE CASCADE` chain no longer fires because we don't
138    -- DELETE).
139    active                          BOOLEAN NOT NULL DEFAULT TRUE,
140    CHECK (
141        (agent_instance_hierarchy IS NOT NULL AND agent_tag IS NULL)
142        OR
143        (agent_instance_hierarchy IS NULL AND agent_tag IS NOT NULL)
144    )
145);
146CREATE INDEX IF NOT EXISTS message_queue_hierarchy_idx
147    ON objectiveai.message_queue(agent_instance_hierarchy, id)
148    WHERE agent_instance_hierarchy IS NOT NULL;
149CREATE INDEX IF NOT EXISTS message_queue_tag_idx
150    ON objectiveai.message_queue(agent_tag, id)
151    WHERE agent_tag IS NOT NULL;
152-- Per-target idempotency keys. The `AND active = TRUE` clause
153-- means inactive prior rows don't count toward uniqueness — an
154-- `agents message --enqueue-with-key k` after a prior consumption
155-- inserts cleanly without UNIQUE-violating the soft-flipped row.
156CREATE UNIQUE INDEX IF NOT EXISTS message_queue_key_hierarchy_unique_idx
157    ON objectiveai.message_queue(agent_instance_hierarchy, key)
158    WHERE agent_instance_hierarchy IS NOT NULL
159      AND key IS NOT NULL
160      AND active = TRUE;
161CREATE UNIQUE INDEX IF NOT EXISTS message_queue_key_tag_unique_idx
162    ON objectiveai.message_queue(agent_tag, key)
163    WHERE agent_tag IS NOT NULL
164      AND key IS NOT NULL
165      AND active = TRUE;
166
167CREATE TABLE IF NOT EXISTS objectiveai.message_queue_contents (
168    id               BIGSERIAL PRIMARY KEY,
169    message_queue_id BIGINT NOT NULL,
170    kind             TEXT   NOT NULL
171        CHECK (kind IN ('text','image','audio','video','file')),
172    FOREIGN KEY (message_queue_id) REFERENCES objectiveai.message_queue(id) ON DELETE CASCADE
173);
174CREATE INDEX IF NOT EXISTS message_queue_contents_parent_idx
175    ON objectiveai.message_queue_contents(message_queue_id);
176
177CREATE TABLE IF NOT EXISTS objectiveai.message_queue_texts (
178    id   BIGINT PRIMARY KEY,
179    text TEXT   NOT NULL,
180    FOREIGN KEY (id) REFERENCES objectiveai.message_queue_contents(id) ON DELETE CASCADE
181);
182
183CREATE TABLE IF NOT EXISTS objectiveai.message_queue_images (
184    id     BIGINT PRIMARY KEY,
185    url    TEXT   NOT NULL,
186    detail TEXT,
187    FOREIGN KEY (id) REFERENCES objectiveai.message_queue_contents(id) ON DELETE CASCADE
188);
189
190CREATE TABLE IF NOT EXISTS objectiveai.message_queue_audios (
191    id     BIGINT PRIMARY KEY,
192    data   TEXT   NOT NULL,
193    format TEXT   NOT NULL,
194    FOREIGN KEY (id) REFERENCES objectiveai.message_queue_contents(id) ON DELETE CASCADE
195);
196
197CREATE TABLE IF NOT EXISTS objectiveai.message_queue_videos (
198    id  BIGINT PRIMARY KEY,
199    url TEXT   NOT NULL,
200    FOREIGN KEY (id) REFERENCES objectiveai.message_queue_contents(id) ON DELETE CASCADE
201);
202
203CREATE TABLE IF NOT EXISTS objectiveai.message_queue_files (
204    id        BIGINT PRIMARY KEY,
205    file_data TEXT,
206    file_id   TEXT,
207    filename  TEXT,
208    file_url  TEXT,
209    FOREIGN KEY (id) REFERENCES objectiveai.message_queue_contents(id) ON DELETE CASCADE
210);
211
212-- AFTER-UPDATE trigger on `message_queue.active`: every soft-flip
213-- (TRUE → FALSE) emits a `NOTIFY message_queue_inactive '<id>'`
214-- so the cli's `db::message_queue::subscribe_delivered` listener
215-- wakes up the instant a consumption flip lands. Pure native
216-- LISTEN/NOTIFY — no polling. We no longer hard-delete, so the
217-- prior AFTER DELETE trigger is gone.
218CREATE OR REPLACE FUNCTION objectiveai.notify_message_queue_inactive()
219RETURNS trigger AS $$
220BEGIN
221    IF OLD.active = TRUE AND NEW.active = FALSE THEN
222        PERFORM pg_notify('message_queue_inactive', NEW.id::text);
223    END IF;
224    RETURN NEW;
225END;
226$$ LANGUAGE plpgsql;
227CREATE OR REPLACE TRIGGER message_queue_inactive_notify
228AFTER UPDATE OF active ON objectiveai.message_queue
229FOR EACH ROW EXECUTE FUNCTION objectiveai.notify_message_queue_inactive();
230
231"#;
232
233/// `logs.*` schema. Pulled from `src/db/logs/schema.sql` so the
234/// canonical definitions live in a real .sql file (readable by
235/// tooling, syntax-highlighted by editors) instead of as a string
236/// constant baked into Rust source.
237const LOGS_SCHEMA: &str = include_str!("logs/schema.sql");
238
239/// The shared readonly group every plugin/tool compartment role
240/// joins (see [`super::compartment`]): USAGE + SELECT over the base
241/// `objectiveai` schema, with default privileges so tables the base
242/// schema grows LATER are covered automatically. Applied inside the
243/// same advisory-locked schema-apply step as the table DDL;
244/// `CREATE ROLE` has no `IF NOT EXISTS`, hence the DO block (roles
245/// are cluster-wide — a sibling database in the same cluster may
246/// have created it already; the GRANTs are per-database and re-run
247/// for each).
248const READER_GROUP: &str = r#"
249DO $$
250BEGIN
251    CREATE ROLE objectiveai_read NOLOGIN;
252EXCEPTION WHEN duplicate_object THEN
253    NULL;
254END
255$$;
256GRANT USAGE ON SCHEMA objectiveai TO objectiveai_read;
257GRANT SELECT ON ALL TABLES IN SCHEMA objectiveai TO objectiveai_read;
258ALTER DEFAULT PRIVILEGES IN SCHEMA objectiveai GRANT SELECT ON TABLES TO objectiveai_read;
259"#;
260
261/// Open the admin pool against `url` (no database path — lands on the
262/// connecting user's default database, `postgres`), ensure `database`
263/// exists, then open the application pool and apply the inline
264/// schema. Idempotent across cold and warm starts — re-running
265/// against an already-bootstrapped database is a no-op (every CREATE
266/// uses `IF NOT EXISTS`).
267pub async fn init(url: &str, database: &str) -> Result<Pool, Error> {
268    let app_url = format!(
269        "{}/{}",
270        url.trim_end_matches('/'),
271        percent_encoding::utf8_percent_encode(database, percent_encoding::NON_ALPHANUMERIC),
272    );
273
274    // 1. Admin pool: ensure the application database exists.
275    //    `CREATE DATABASE` cannot run inside a transaction, so we use
276    //    a fresh single-connection pool just for this check + insert.
277    let admin = PgPoolOptions::new()
278        .max_connections(1)
279        .connect(url)
280        .await
281        .map_err(|e| unreachable_hint(url, e))?;
282    let exists: bool = {
283        let row = sqlx::query("SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = $1)")
284            .bind(database)
285            .fetch_one(&admin)
286            .await?;
287        row.try_get::<bool, _>(0)?
288    };
289    if !exists {
290        // `CREATE DATABASE` can't be parameterised; the name comes
291        // from config, so quote it as an identifier (double-quote
292        // wrapping with embedded quotes doubled) to keep arbitrary
293        // names safe.
294        //
295        // Race: two concurrent cli processes can both observe
296        // `exists = false` and race the CREATE. The second to
297        // commit gets SQLSTATE 42P04 (`duplicate_database`); swallow
298        // that exact code (any other error still propagates).
299        let quoted = database.replace('"', "\"\"");
300        match admin
301            .execute(format!("CREATE DATABASE \"{quoted}\"").as_str())
302            .await
303        {
304            Ok(_) => {}
305            // 42P04 = `duplicate_database` (the high-level check
306            // postgres fires when it sees an existing matching
307            // datname row in pg_database).
308            // 23505 = `unique_violation` on `pg_database_datname_index`
309            // (the low-level catalog insert losing the race).
310            // Either way, the database exists now; continue.
311            Err(sqlx::Error::Database(db))
312                if matches!(db.code().as_deref(), Some("42P04") | Some("23505")) => {}
313            Err(e) => return Err(e.into()),
314        }
315    }
316    admin.close().await;
317
318    // 2. App pool: connect to the just-ensured database, apply schema
319    //    inside one transaction.
320    //
321    //    Concurrency: `CREATE … IF NOT EXISTS` is not atomic across
322    //    parallel sessions (two can both see "doesn't exist" and
323    //    both try to insert into `pg_class`; the loser gets 23505
324    //    on `pg_class_relname_nsp_index` or a deadlock against
325    //    another session writing the same catalog row).
326    //    Serialize the schema-apply step behind a session-level
327    //    advisory lock so only one process at a time runs it; the
328    //    `IF NOT EXISTS` clauses then make every subsequent run a
329    //    no-op.
330    let pool = PgPoolOptions::new()
331        .max_connections(8)
332        .connect(&app_url)
333        .await
334        .map_err(|e| unreachable_hint(&app_url, e))?;
335    {
336        // Arbitrary 64-bit constant; the pair `(database, key)`
337        // defines the lock identity, so as long as every process
338        // uses the same key against the same db they serialize on
339        // schema-apply.
340        const SCHEMA_LOCK_KEY: i64 = 0x0B7EC71AE_15CBE_AA_i64;
341        let mut conn = pool.acquire().await?;
342        sqlx::query("SELECT pg_advisory_lock($1)")
343            .bind(SCHEMA_LOCK_KEY)
344            .execute(&mut *conn)
345            .await?;
346        let apply_result: Result<(), Error> = async {
347            conn.execute(SCHEMA).await?;
348            conn.execute(LOGS_SCHEMA).await?;
349            conn.execute(READER_GROUP).await?;
350            Ok(())
351        }
352        .await;
353        // Best-effort release; if the connection died the lock
354        // releases on session end anyway.
355        let _ = sqlx::query("SELECT pg_advisory_unlock($1)")
356            .bind(SCHEMA_LOCK_KEY)
357            .execute(&mut *conn)
358            .await;
359        apply_result?;
360    }
361
362    Ok(Pool(pool))
363}
364
365/// Compose the base connect URL (no database path) for a remote
366/// postgres configured via `config db` — used by `Context::db_client`
367/// when `db.address` is set, in place of the spawn lock's URL. The
368/// address may embed a port (`host:5432`); a bare host gets postgres's
369/// default port. User and password are percent-encoded so arbitrary
370/// config values can't break the URL shape.
371pub(crate) fn config_url(address: &str, user: &str, password: &str) -> String {
372    let user =
373        percent_encoding::utf8_percent_encode(user, percent_encoding::NON_ALPHANUMERIC);
374    let password =
375        percent_encoding::utf8_percent_encode(password, percent_encoding::NON_ALPHANUMERIC);
376    format!("postgres://{user}:{password}@{address}")
377}
378
379/// Map a pool-connect failure to the actionable error: the database
380/// at the resolved URL isn't reachable, and the fix is either
381/// `objectiveai db spawn` (local objectiveai-db) or `db config
382/// address` (remote postgres). Non-connect errors (auth failures,
383/// TLS, ...) get the same wrapper — the remedy hint is still the
384/// right one.
385fn unreachable_hint(url: &str, source: sqlx::Error) -> Error {
386    Error::DbUnreachable {
387        url: redact_url_password(url),
388        source: Box::new(source),
389    }
390}
391
392/// `scheme://user:password@rest` → `scheme://user:***@rest`, so the
393/// connect URL can ride in an error message without leaking the
394/// password. Returned unchanged when there is no userinfo or no
395/// password segment.
396fn redact_url_password(url: &str) -> String {
397    let Some(scheme_end) = url.find("://") else {
398        return url.to_string();
399    };
400    let rest = &url[scheme_end + 3..];
401    let authority = &rest[..rest.find('/').unwrap_or(rest.len())];
402    let Some(at) = authority.rfind('@') else {
403        return url.to_string();
404    };
405    let userinfo = &authority[..at];
406    let Some(colon) = userinfo.find(':') else {
407        return url.to_string();
408    };
409    format!(
410        "{}:***{}",
411        &url[..scheme_end + 3 + colon],
412        &url[scheme_end + 3 + at..],
413    )
414}
415
416#[cfg(test)]
417mod tests {
418    use super::redact_url_password;
419
420    #[test]
421    fn redact_url_password_cases() {
422        assert_eq!(
423            redact_url_password("postgresql://postgres:s3cr%40t@127.0.0.1:5432"),
424            "postgresql://postgres:***@127.0.0.1:5432",
425        );
426        assert_eq!(
427            redact_url_password("postgres://u:p@h:5432/objectiveai"),
428            "postgres://u:***@h:5432/objectiveai",
429        );
430        // No password segment in the userinfo.
431        assert_eq!(
432            redact_url_password("postgres://postgres@127.0.0.1:5432"),
433            "postgres://postgres@127.0.0.1:5432",
434        );
435        // No userinfo at all.
436        assert_eq!(
437            redact_url_password("postgres://127.0.0.1:5432/db"),
438            "postgres://127.0.0.1:5432/db",
439        );
440        // Not even a scheme.
441        assert_eq!(redact_url_password("127.0.0.1:5432"), "127.0.0.1:5432");
442    }
443}