-- Two middens that start at once apply this schema one after the other. SELECT pg_advisory_xact_lock(hashtext('midden schema')); -- One row for each OTLP log record that midden receives. Rows are never -- updated or deleted. CREATE TABLE IF NOT EXISTS records ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, received_at timestamptz NOT NULL DEFAULT now(), -- 'transcript' for a harness's transcript entry, 'event' for one of -- its native OpenTelemetry events. kind text NOT NULL CHECK (kind IN ('transcript', 'event')), -- The Authentik user that sent the record. username text NOT NULL, harness text, host text, session_id text, -- The transcript file, relative to the harness's projects directory. -- A resumed session's file repeats earlier entries with the same uuid -- and different metadata, so each file's copy is its own row. transcript_path text, -- The entry's uuid, or its byte offset in the transcript file when -- the entry has no uuid. Only transcript entries have one. entry_key text, prompt_id text, event_name text, time timestamptz, -- The transcript entry, parsed, when its body is JSON. entry jsonb, -- The whole log record with its resource and scope, as OTLP JSON. record jsonb NOT NULL ); -- A retry, a second backfill, or two shippers that overlap send the same -- entry of the same file again, and this index keeps one copy. CREATE UNIQUE INDEX IF NOT EXISTS records_transcript_entry ON records (session_id, transcript_path, entry_key) WHERE kind = 'transcript'; CREATE INDEX IF NOT EXISTS records_session_time ON records (session_id, time); -- The searchable parts of a transcript entry, the way Archive.Conversation -- reads them: the text of the user's prompts, the assistant's text, the -- string values of a tool call's input, and the text of a tool's result. -- part is the part's place in Entry.Parts. Other parts have no text to -- search, and the function leaves them out. -- -- The index records_search depends on these two functions. A change to -- what they return needs a new index name, or the old index goes stale. CREATE OR REPLACE FUNCTION entry_parts(entry jsonb) RETURNS TABLE (part integer, kind text, tool text, body text) LANGUAGE sql IMMUTABLE PARALLEL SAFE BEGIN ATOMIC SELECT 0, CASE entry->>'type' WHEN 'user' THEN 'prompt' ELSE 'text' END, NULL::text, entry->'message'->>'content' WHERE entry->>'type' IN ('user', 'assistant') AND jsonb_typeof(entry->'message'->'content') = 'string' UNION ALL SELECT (b.n - 1)::integer, p.kind, p.tool, p.body FROM jsonb_array_elements( CASE WHEN entry->>'type' IN ('user', 'assistant') AND jsonb_typeof(entry->'message'->'content') = 'array' THEN entry->'message'->'content' END) WITH ORDINALITY b(block, n) CROSS JOIN LATERAL ( SELECT CASE entry->>'type' WHEN 'user' THEN 'prompt' ELSE 'text' END, NULL::text, b.block->>'text' WHERE b.block->>'type' = 'text' UNION ALL SELECT 'tool_use', b.block->>'name', (SELECT string_agg(v #>> '{}', E'\n') FROM jsonb_path_query(b.block->'input', 'strict $.**') v WHERE jsonb_typeof(v) = 'string') WHERE b.block->>'type' = 'tool_use' UNION ALL SELECT 'tool_result', NULL::text, CASE jsonb_typeof(b.block->'content') WHEN 'string' THEN b.block->>'content' WHEN 'array' THEN (SELECT string_agg(c.block->>'text', E'\n' ORDER BY c.n) FROM jsonb_array_elements(b.block->'content') WITH ORDINALITY c(block, n) WHERE c.block->>'type' = 'text') END WHERE b.block->>'type' = 'tool_result' ) p (kind, tool, body) WHERE p.body <> ''; END; -- The words of an entry's searchable parts, for the index records_search. -- The text is cut at 100000 characters, which keeps the tsvector under -- its limit of 1 MB, so that no entry fails its insert. CREATE OR REPLACE FUNCTION entry_search(entry jsonb) RETURNS tsvector LANGUAGE sql IMMUTABLE PARALLEL SAFE BEGIN ATOMIC SELECT to_tsvector('english', left(coalesce(string_agg(body, E'\n' ORDER BY part), ''), 100000)) FROM entry_parts(entry); END; -- The index records_search, a GIN index on entry_search(entry), is not -- here: building it reads the whole table, so Archive.Index builds it -- after midden starts, without blocking writes. -- The traits of a transcript entry that say whether its session is -- private: its working directory, as ('cwd', the directory), and each -- tool it calls, as ('tool', the tool's name). -- -- session_traits depends on this function. A change to what it returns -- needs a new table name, or the rows already stored keep the old traits. CREATE OR REPLACE FUNCTION entry_traits(entry jsonb) RETURNS TABLE (kind text, value text) LANGUAGE sql IMMUTABLE PARALLEL SAFE BEGIN ATOMIC SELECT 'cwd', entry->>'cwd' WHERE coalesce(entry->>'cwd', '') <> '' UNION SELECT 'tool', b->>'name' FROM jsonb_array_elements( CASE WHEN jsonb_typeof(entry->'message'->'content') = 'array' THEN entry->'message'->'content' END) b WHERE b->>'type' = 'tool_use' AND coalesce(b->>'name', '') <> ''; END; CREATE OR REPLACE FUNCTION record_session_traits() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN INSERT INTO session_traits (session_id, kind, value) SELECT NEW.session_id, t.kind, t.value FROM entry_traits(NEW.entry) t ON CONFLICT DO NOTHING; RETURN NULL; END; $$; -- Each trait of each session, once, from every entry of every file of -- the session. The trigger adds the traits of each entry in the -- transaction that stores it, so a read never sees an entry without its -- traits. Which traits make a session private is midden's config, and -- the reads apply it, so a change to the config needs no change here. -- -- The block runs once, on the first start with this schema. Creating -- the trigger waits for the inserts in flight and holds off new ones -- until the schema commits, so the backfill sees every row that the -- trigger does not. DO $$ BEGIN IF to_regclass('session_traits') IS NULL THEN CREATE TABLE session_traits ( session_id text NOT NULL, kind text NOT NULL CHECK (kind IN ('cwd', 'tool')), value text NOT NULL ); -- md5 keeps a long value from failing the insert, and with it -- the entry's. CREATE UNIQUE INDEX session_traits_one ON session_traits (session_id, kind, md5(value)); CREATE TRIGGER records_session_traits AFTER INSERT ON records FOR EACH ROW WHEN (NEW.kind = 'transcript' AND NEW.session_id IS NOT NULL) EXECUTE FUNCTION record_session_traits(); INSERT INTO session_traits (session_id, kind, value) SELECT DISTINCT r.session_id, t.kind, t.value FROM records r CROSS JOIN LATERAL entry_traits(r.entry) t WHERE r.kind = 'transcript' AND r.session_id IS NOT NULL ON CONFLICT DO NOTHING; END IF; END; $$; -- Whether a session is private: one of its entries works in a directory -- that matches one of the repositories, which are regular expressions, -- or calls a tool whose name starts with one of the tools. CREATE OR REPLACE FUNCTION session_private(session text, repositories text[], tools text[]) RETURNS boolean LANGUAGE sql STABLE PARALLEL SAFE BEGIN ATOMIC SELECT EXISTS ( SELECT 1 FROM session_traits t WHERE t.session_id = session AND ((t.kind = 'cwd' AND t.value ~ ANY (repositories)) OR (t.kind = 'tool' AND EXISTS (SELECT 1 FROM unnest(tools) p WHERE starts_with(t.value, p))))); END; -- The place of each transcript entry in its session's conversation, so -- that Archive.Conversation reads a page by an index and never opens the -- entries it does not return. One row for each transcript row, with: -- -- - file, the transcript file, and one, the md5 of the key that says -- which rows are copies of one entry: the uuid, or the file and the -- offset for an entry with no uuid -- - own, the entry's own timestamp, and NULL when it has none -- - at, the entry's place in time: own, or else the latest own of the -- rows before it in its file, or else the earliest own of its file, -- or else infinity -- - leads, which marks a row that takes the earliest own of its file, -- because no row before it in its file has one -- - first, which marks the copy that midden stored first, the one that -- stands for the entry -- -- The rows of a file come in the order of the file, so a new row never -- comes before an old one. Only the leading rows of a file change their -- place, when a row with an earlier timestamp arrives. -- -- The trigger holds the session's place lock, shared, so that -- place_session never places a session while an entry of it is on its -- way in. CREATE OR REPLACE FUNCTION record_entry_place() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE path text := coalesce(NEW.transcript_path, ''); stamp timestamptz := CASE WHEN NEW.entry ? 'timestamp' THEN NEW.time END; copies text := md5(CASE WHEN NEW.entry_key LIKE 'offset:%' THEN path || ' ' || NEW.entry_key ELSE coalesce(NEW.entry_key, 'id:' || NEW.id) END); latest timestamptz; BEGIN PERFORM pg_advisory_xact_lock_shared(hashtextextended('midden place ' || NEW.session_id, 0)); SELECT max(p.own) INTO latest FROM entry_places p WHERE p.session_id = NEW.session_id AND p.file = path; IF stamp IS NOT NULL THEN UPDATE entry_places p SET at = stamp WHERE p.session_id = NEW.session_id AND p.file = path AND p.leads AND p.at > stamp; END IF; INSERT INTO entry_places (id, session_id, file, one, own, at, leads, first) VALUES (NEW.id, NEW.session_id, path, copies, stamp, coalesce(stamp, latest, 'infinity'), stamp IS NULL AND latest IS NULL, true) ON CONFLICT (session_id, one) WHERE first DO NOTHING; IF NOT FOUND THEN INSERT INTO entry_places (id, session_id, file, one, own, at, leads, first) VALUES (NEW.id, NEW.session_id, path, copies, stamp, coalesce(stamp, latest, 'infinity'), stamp IS NULL AND latest IS NULL, false); END IF; RETURN NULL; END; $$; -- place_session places every row of a session again, from records, and -- takes the session off unplaced_sessions. It holds the session's place -- lock, so it waits for the entries of the session on their way in, and -- the entries after it wait for it. CREATE OR REPLACE FUNCTION place_session(session text) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM pg_advisory_xact_lock(hashtextextended('midden place ' || session, 0)); DELETE FROM entry_places WHERE session_id = session; INSERT INTO entry_places (id, session_id, file, one, own, at, leads, first) SELECT id, session_id, file, one, own, coalesce(own, latest, min(own) OVER (PARTITION BY file), 'infinity'), own IS NULL AND latest IS NULL, row_number() OVER (PARTITION BY one ORDER BY id) = 1 FROM ( SELECT id, session_id, file, one, own, max(own) OVER (PARTITION BY file ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS latest FROM ( SELECT id, session_id, coalesce(transcript_path, '') AS file, md5(CASE WHEN entry_key LIKE 'offset:%' THEN coalesce(transcript_path, '') || ' ' || entry_key ELSE coalesce(entry_key, 'id:' || id) END) AS one, CASE WHEN entry ? 'timestamp' THEN time END AS own FROM records WHERE kind = 'transcript' AND session_id = session ) r ) b; DELETE FROM unplaced_sessions WHERE session_id = session; END; $$; -- The block runs once, on the first start with this schema. Placing the -- rows stored before it reads every entry, which takes too long for a -- start, so the block only lists their sessions in unplaced_sessions, -- and Archive.Place places them after midden starts. Conversation -- places a session on the list before it reads it. DO $$ BEGIN IF to_regclass('entry_places') IS NULL THEN CREATE TABLE entry_places ( id bigint PRIMARY KEY, session_id text NOT NULL, file text NOT NULL, one text NOT NULL, own timestamptz, at timestamptz NOT NULL, leads boolean NOT NULL, first boolean NOT NULL ); CREATE INDEX entry_places_order ON entry_places (session_id, at, id) WHERE first; CREATE UNIQUE INDEX entry_places_one ON entry_places (session_id, one) WHERE first; CREATE INDEX entry_places_own ON entry_places (session_id, file, own); CREATE INDEX entry_places_leads ON entry_places (session_id, file) WHERE leads; CREATE TABLE unplaced_sessions (session_id text PRIMARY KEY); CREATE TRIGGER records_entry_places AFTER INSERT ON records FOR EACH ROW WHEN (NEW.kind = 'transcript' AND NEW.session_id IS NOT NULL) EXECUTE FUNCTION record_entry_place(); INSERT INTO unplaced_sessions SELECT DISTINCT session_id FROM records WHERE session_id IS NOT NULL; END IF; END; $$;