Files
archie/internal/infrastructure/postgres/migrations/0003_gateway.sql
T
sam 710fbab094 feat(gateway): port session store to Postgres
Move sessions, messages, turns and full-text search off the per-process
SQLite file onto Postgres behind the existing messaging.SessionStore
contract. New adapter internal/gateway/session_store_postgres.go, sqlc
queries/gateway.sql, migration 0003_gateway.sql, regenerated postgresdb.

FTS5 becomes a STORED generated tsvector column over (sender, text) plus
GIN. plainto_tsquery is the tsvector analog of ftsMatchQuery's
quote-escaping: query text is parsed as plain text, never query syntax, and
the surviving terms are ANDed. MessagePage.Truncated stays always-false on
Postgres too: the result set is counted exactly.

On internal/domain/messaging/session_store.go: this is a comment-only edit
to the MessagePage.Truncated doc comment (the brief's own "change the
comment" instruction). It changes no type, method or value, so L2 and the
import lane still build against an unchanged contract and the wire is
unaffected. No interface widened or altered.

Semantics preserved verbatim:
- The timestamp clamp is SQL-atomic (INSERT ... SELECT MAX(ts)+1). Appends to
  one session are serialised by a transaction-scoped advisory lock keyed on
  the session so two concurrent appends cannot read the same MAX(ts); a Go
  clamp would race (proven by the new cross-handle monotonicity test).
- Session ordering is GREATEST(last_active_at, created_at) with a matching
  expression index.
- ClaimTurn is insert-first (ON CONFLICT DO NOTHING), with a race test across
  two handles.

State outside the store is NOT made shared by this change, and none of it is
silently improved or worsened:
- sessionTracker.active, Router.titling and per-session persona selection are
  in-memory, per-process caches; a second Gateway still diverges from the
  first.
- messaging.Turns lanes and the per-process recovery latch stay per-process.
- RecoverTurns still fails every turn owned by another process, so a second
  Gateway starting would still fail the first's in-flight turns. This lane
  does NOT make that safe and does not try to: the safeguard is D4.1's
  single-Gateway advisory serve-ownership lock (not implemented here), which
  prevents a second Gateway from serving at all. The turn-recovery semantics
  are left exactly as they were.

Production openers still return SQLite; this lane adds the adapter and tests
only. The cutover and the state-sharing questions remain follow-up work.
2026-09-24 02:17:23 +10:00

83 lines
3.6 KiB
SQL

-- Gateway conversation schema: sessions, messages, turns and full-text search.
--
-- Translations from the SQLite schema this replaces (session_store_sqlite.go),
-- and why:
-- * Times stay bigint milliseconds. SQLite stored them as INTEGER ms and the
-- monotonic clamp adds one to that integer (MAX(ts) + 1); a timestamptz
-- translation would change the unit of the "+1" and therefore the strict
-- message-ordering contract, so the millisecond representation is kept
-- verbatim and the Go adapter converts with time.UnixMilli exactly as the
-- SQLite store did.
-- * FTS5 becomes a STORED generated tsvector column over (sender, text) plus
-- a GIN index. The external-content FTS5 table was kept in sync by three
-- triggers on messages; a generated column cannot drift from its row, so
-- the triggers are unnecessary here. The 'simple' configuration matches
-- FTS5's default tokenizer: case-folding only, no stemming, no stop words.
-- * Every column behind a Go int is bigint: SQLite's INTEGER is 64-bit.
-- +goose Up
CREATE TABLE sessions (
session_id text PRIMARY KEY,
platform text NOT NULL DEFAULT '',
bot_user text NOT NULL DEFAULT '',
channel_id text NOT NULL DEFAULT '',
thread_id text NOT NULL DEFAULT '',
title text NOT NULL DEFAULT '',
parent_session_id text NOT NULL DEFAULT '',
branch_name text NOT NULL DEFAULT '',
created_at bigint NOT NULL DEFAULT 0,
last_active_at bigint NOT NULL DEFAULT 0
);
CREATE INDEX idx_sessions_channel ON sessions (platform, channel_id);
-- Ordering is by recency: last_active_at when set, created_at otherwise
-- (GREATEST is the two-argument max SQLite's MAX(a, b) expressed). The index
-- matches that expression so newest-first listings do not sort at query time.
CREATE INDEX idx_sessions_recency
ON sessions (platform, channel_id, GREATEST(last_active_at, created_at) DESC);
CREATE TABLE messages (
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
message_id text NOT NULL,
session_id text NOT NULL,
source_id text NOT NULL DEFAULT '',
sender text NOT NULL DEFAULT '',
sender_id text NOT NULL DEFAULT '',
role text NOT NULL DEFAULT '',
text text NOT NULL DEFAULT '',
ts bigint NOT NULL,
-- Full-text search over sender and text only: ts, source_id and other
-- metadata are not indexed, so a query like "2026" cannot match every
-- message via its timestamp (the SQLite FTS5 external-content index kept
-- exactly these two columns).
search tsvector GENERATED ALWAYS AS (to_tsvector('simple', sender || ' ' || text)) STORED,
UNIQUE (session_id, message_id)
);
CREATE INDEX idx_messages_session_ts ON messages (session_id, ts);
CREATE INDEX idx_messages_search ON messages USING GIN (search);
CREATE TABLE turns (
turn_id text PRIMARY KEY,
session_id text NOT NULL,
source_id text NOT NULL DEFAULT '',
status text NOT NULL,
attempt bigint NOT NULL DEFAULT 0,
owner_id text NOT NULL DEFAULT '',
input_message_id text NOT NULL DEFAULT '',
assistant_message_id text NOT NULL DEFAULT '',
partial_text text NOT NULL DEFAULT '',
response_text text NOT NULL DEFAULT '',
tool_calls text NOT NULL DEFAULT '[]',
error text NOT NULL DEFAULT '',
created_at bigint NOT NULL,
updated_at bigint NOT NULL
);
CREATE INDEX idx_turns_session_source ON turns (session_id, source_id);
CREATE INDEX idx_turns_status_updated ON turns (status, updated_at);
-- +goose Down
DROP TABLE turns;
DROP TABLE messages;
DROP TABLE sessions;