chore(state-store): remove the one-time SQLite import and db_path
Every install serves from Postgres, so the legacyread/legacyimport packages, the archie-state-store import command, the boot gate that refused to serve over unimported SQLite files, and db_path (which only located those files) go. Migration 0010 drops the import_completion table.
This commit is contained in:
1 parent
d61e49b2c9
commit
8c55b5d4e4
65 files changed
+138
-3350
No files matched your search
@@ -224,7 +224,6 @@ func DefaultConfigPath() string {
|
||||
func (l *Loader) applyGeneralDefaults(cfg *config.Config) {
|
||||
cfg.SecretEngineDir = expandHomePath(cfg.SecretEngineDir)
|
||||
cfg.WorkDir = expandHomePath(cfg.WorkDir)
|
||||
cfg.DBPath = expandHomePath(cfg.DBPath)
|
||||
cfg.StateDir = expandHomePath(cfg.StateDir)
|
||||
cfg.Chat.Workspace = expandHomePath(cfg.Chat.Workspace)
|
||||
// DatabaseURL has no default and is not path-expanded: it is a connection
|
||||
@@ -235,9 +234,6 @@ func (l *Loader) applyGeneralDefaults(cfg *config.Config) {
|
||||
if cfg.WorkDir == "" {
|
||||
cfg.WorkDir = filepath.Join(l.dataHome(), "archie", "work")
|
||||
}
|
||||
if cfg.DBPath == "" {
|
||||
cfg.DBPath = filepath.Join(l.dataHome(), "archie", "archie.db")
|
||||
}
|
||||
if cfg.StateDir == "" {
|
||||
cfg.StateDir = filepath.Join(l.dataHome(), "archie")
|
||||
}
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
package configuration
|
||||
|
||||
// DeniedKeys are the config keys the runtime overlay may never set, mapped
|
||||
// to the reason shown to the operator. db_path is the daemon's own bootstrap
|
||||
// path -- the daemon must read it before it can open the overlay store --
|
||||
// and work_dir pins the whole working layout. Enforced at write time (the
|
||||
// to the reason shown to the operator. database_url and state_dir are read
|
||||
// before the overlay store can be opened, and work_dir pins the whole working
|
||||
// layout. Enforced at write time (the
|
||||
// API returns 4xx) and again in the overlay's Set, not silently dropped at
|
||||
// read time. Owned here rather than in the overlay package so the webui
|
||||
// config renderer can reference the policy without linking the overlay's
|
||||
// SQLite store (archie-core-8cda.5.6).
|
||||
var DeniedKeys = map[string]string{
|
||||
"db_path": "required for bootstrap; cannot be changed at runtime",
|
||||
"database_url": "required for bootstrap; cannot be changed at runtime",
|
||||
"state_dir": "required for bootstrap; cannot be changed at runtime",
|
||||
"work_dir": "pins the daemon's working layout; cannot be changed at runtime",
|
||||
|
||||
@@ -51,7 +51,6 @@ func TestLoadExpandsConfiguredHomePaths(t *testing.T) {
|
||||
contents := `
|
||||
bot_user = "widget"
|
||||
work_dir = "~/archie/work"
|
||||
db_path = "~/archie/archie.db"
|
||||
state_dir = "~/archie/state"
|
||||
|
||||
[chat]
|
||||
@@ -74,7 +73,6 @@ name = "app"
|
||||
want string
|
||||
}{
|
||||
"work_dir": {got: cfg.WorkDir, want: filepath.Join(home, "archie", "work")},
|
||||
"db_path": {got: cfg.DBPath, want: filepath.Join(home, "archie", "archie.db")},
|
||||
"state_dir": {got: cfg.StateDir, want: filepath.Join(home, "archie", "state")},
|
||||
"chat.workspace": {got: cfg.Chat.Workspace, want: filepath.Join(home, "archie", "workspace")},
|
||||
}
|
||||
@@ -87,15 +85,13 @@ name = "app"
|
||||
}
|
||||
}
|
||||
|
||||
// state_dir defaults to archie's directory under the data home, independent
|
||||
// of db_path, which only locates legacy files for the one-time import.
|
||||
// state_dir defaults to archie's directory under the data home.
|
||||
func TestStateDirDefaultsToTheDataHome(t *testing.T) {
|
||||
dataHome := t.TempDir()
|
||||
t.Setenv("XDG_DATA_HOME", dataHome)
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := `
|
||||
bot_user = "widget"
|
||||
db_path = "/elsewhere/archie.db"
|
||||
|
||||
[[repos]]
|
||||
owner = "acme"
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
// Package legacyfixture writes the legacy SQLite files an existing install
|
||||
// holds, for tests of the one-time import and the boot gate that requires it.
|
||||
package legacyfixture
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
// StateStoreDDL, EDADDL and GatewayDDL apply the legacy schemas as their production openers leave
|
||||
// them, columns added by ALTER TABLE included, with values in the layouts the
|
||||
// production writers used.
|
||||
const StateStoreDDL = `
|
||||
CREATE TABLE tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, owner TEXT NOT NULL, repo TEXT NOT NULL,
|
||||
issue_number INTEGER NOT NULL, title TEXT DEFAULT '', body TEXT DEFAULT '', labels TEXT DEFAULT '',
|
||||
status TEXT DEFAULT 'queued', workflow TEXT DEFAULT '', stage TEXT DEFAULT '', branch TEXT DEFAULT '',
|
||||
plan TEXT DEFAULT '', notes TEXT DEFAULT '', pr_number INTEGER DEFAULT 0, tokens_used INTEGER DEFAULT 0,
|
||||
iterations INTEGER DEFAULT 0, attempt INTEGER DEFAULT 0, park_reason TEXT DEFAULT '',
|
||||
watch_comment_id INTEGER DEFAULT 0, park_class TEXT DEFAULT 'needs_human', remediation_rounds INTEGER DEFAULT 0,
|
||||
retry_count INTEGER DEFAULT 0, source TEXT DEFAULT 'forge', identity TEXT DEFAULT '', binding_id TEXT DEFAULT '',
|
||||
binding_version INTEGER DEFAULT 0, review_payload TEXT DEFAULT '', workflow_definition_version INTEGER DEFAULT 0,
|
||||
workflow_definition_digest TEXT DEFAULT '', workflow_definition_yaml TEXT DEFAULT '',
|
||||
created_at TEXT DEFAULT (datetime('now')), updated_at TEXT DEFAULT (datetime('now')));
|
||||
ALTER TABLE tasks ADD COLUMN review_cursor INTEGER NOT NULL DEFAULT 0;
|
||||
CREATE TABLE transitions (id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER NOT NULL,
|
||||
at TEXT DEFAULT (datetime('now')), from_status TEXT NOT NULL, to_status TEXT NOT NULL, detail TEXT DEFAULT '');
|
||||
CREATE TABLE events (id INTEGER PRIMARY KEY AUTOINCREMENT, at TEXT NOT NULL, kind TEXT NOT NULL,
|
||||
task_id INTEGER DEFAULT 0, repo TEXT DEFAULT '', issue INTEGER DEFAULT 0, workflow TEXT DEFAULT '',
|
||||
stage TEXT DEFAULT '', attempt INTEGER DEFAULT 0, actor_id TEXT DEFAULT '', actor_kind TEXT DEFAULT '',
|
||||
principal_id TEXT DEFAULT '', detail TEXT DEFAULT '', data TEXT DEFAULT '{}');
|
||||
CREATE TABLE resources (kind TEXT PRIMARY KEY, value BLOB NOT NULL, version INTEGER NOT NULL, updated_at TEXT NOT NULL);
|
||||
CREATE TABLE resource_history (id INTEGER PRIMARY KEY AUTOINCREMENT, kind TEXT NOT NULL, value BLOB NOT NULL,
|
||||
version INTEGER NOT NULL, actor TEXT NOT NULL, source TEXT NOT NULL, request_id TEXT NOT NULL,
|
||||
expected_version INTEGER NOT NULL, current_version INTEGER NOT NULL, at TEXT NOT NULL);
|
||||
CREATE TABLE channel_status (id TEXT PRIMARY KEY, name TEXT DEFAULT '', state TEXT DEFAULT '', detail TEXT DEFAULT '',
|
||||
configured INTEGER NOT NULL DEFAULT 0, reload_supported INTEGER NOT NULL DEFAULT 0, observed_at TEXT NOT NULL);
|
||||
CREATE TABLE apply_status (process TEXT NOT NULL, kind TEXT NOT NULL, applied_version INTEGER DEFAULT 0,
|
||||
error TEXT DEFAULT '', reported_at TEXT NOT NULL, PRIMARY KEY (process, kind));
|
||||
CREATE TABLE config_snapshot (id INTEGER PRIMARY KEY CHECK (id = 1), schema TEXT DEFAULT '', document TEXT DEFAULT '',
|
||||
published_at TEXT NOT NULL);
|
||||
CREATE TABLE identities (id TEXT PRIMARY KEY, kind TEXT NOT NULL, display_name TEXT NOT NULL, lifecycle TEXT NOT NULL,
|
||||
version INTEGER NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
|
||||
CREATE TABLE identity_aliases (alias TEXT PRIMARY KEY COLLATE NOCASE, identity_id TEXT NOT NULL REFERENCES identities(id));
|
||||
CREATE TABLE identity_events (id INTEGER PRIMARY KEY AUTOINCREMENT, identity_id TEXT NOT NULL, event_type TEXT NOT NULL,
|
||||
from_lifecycle TEXT NOT NULL, to_lifecycle TEXT NOT NULL, display_name TEXT NOT NULL, actor_id TEXT NOT NULL,
|
||||
source TEXT NOT NULL, request_id TEXT NOT NULL UNIQUE, at TEXT NOT NULL);
|
||||
CREATE TABLE identity_subjects (issuer TEXT NOT NULL, subject TEXT NOT NULL,
|
||||
identity_id TEXT NOT NULL REFERENCES identities(id), bound_at TEXT NOT NULL, PRIMARY KEY (issuer, subject));
|
||||
|
||||
INSERT INTO tasks (id, owner, repo, issue_number, review_cursor, created_at, updated_at) VALUES
|
||||
(1, 'o', 'r', 7, 3, '2026-01-01 00:00:00', '2026-01-01 00:00:01'),
|
||||
(4, 'o', 'r', 1000000000000000, 0, '2026-01-02 00:00:00', '2026-01-02 00:00:00'),
|
||||
(9, 'o', 'r', 8, 0, '2026-01-02 00:00:00', '2026-01-02 00:00:00');
|
||||
DELETE FROM tasks WHERE id = 9;
|
||||
INSERT INTO transitions (task_id, at, from_status, to_status) VALUES (1, '2026-01-01 00:00:00', 'queued', 'running');
|
||||
INSERT INTO events (id, at, kind, data) VALUES
|
||||
(1, '2026-01-01T00:00:00.000000100Z', 'a', 'null'),
|
||||
(2, '2026-01-01T00:00:01.000000000Z', 'b', '{"k":1}'),
|
||||
(5, '2026-01-01T00:00:00.500000000Z', 'c', '{}');
|
||||
INSERT INTO resources VALUES ('config', X'00ff10', 2, '2026-01-01T00:00:00.123456789Z');
|
||||
INSERT INTO resource_history (kind, value, version, actor, source, request_id, expected_version, current_version, at)
|
||||
VALUES ('config', X'00ff10', 2, 'sam', 'ui', 'req-1', 1, 1, '2026-01-01T00:00:00Z');
|
||||
INSERT INTO channel_status VALUES ('tg', 'Telegram', 'up', '', 1, 0, '2026-01-01T00:00:00Z');
|
||||
INSERT INTO apply_status VALUES ('daemon', 'config', 2, '', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO config_snapshot VALUES (1, 's', '{}', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO identities VALUES ('id-1', 'agent', 'Archie', 'active', 1, '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO identity_aliases VALUES ('archie', 'id-1');
|
||||
INSERT INTO identity_events (identity_id, event_type, from_lifecycle, to_lifecycle, display_name, actor_id, source, request_id, at)
|
||||
VALUES ('id-1', 'created', '', 'active', 'Archie', 'sam', 'boot', 'rq-1', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO identity_subjects VALUES ('https://issuer', 'sub-1', 'id-1', '2026-01-01T00:00:00Z');
|
||||
`
|
||||
|
||||
// Secret is an encrypted binding secret envelope; it must arrive unchanged.
|
||||
const Secret = "arcie-binding:v1:0123456789abcdef:AbC-_dEf012"
|
||||
|
||||
const EDADDL = `
|
||||
CREATE TABLE captures (id TEXT PRIMARY KEY NOT NULL, authenticated BOOLEAN DEFAULT FALSE NOT NULL,
|
||||
body TEXT DEFAULT '' NOT NULL, content_type TEXT DEFAULT '' NOT NULL, headers JSON DEFAULT NULL,
|
||||
received_at TEXT DEFAULT '' NOT NULL, remote_addr TEXT DEFAULT '' NOT NULL, source TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE mappings (id TEXT PRIMARY KEY NOT NULL, created_at TEXT DEFAULT '' NOT NULL, fields JSON DEFAULT NULL,
|
||||
name TEXT DEFAULT '' NOT NULL, source_hint TEXT DEFAULT '' NOT NULL, updated_at TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE bindings (id TEXT PRIMARY KEY NOT NULL, created_at TEXT DEFAULT '' NOT NULL, mapping TEXT DEFAULT '' NOT NULL,
|
||||
name TEXT DEFAULT '' NOT NULL, owner TEXT DEFAULT '' NOT NULL, repo TEXT DEFAULT '' NOT NULL,
|
||||
secret TEXT DEFAULT '' NOT NULL, source TEXT DEFAULT '' NOT NULL, status TEXT DEFAULT '' NOT NULL,
|
||||
updated_at TEXT DEFAULT '' NOT NULL, version NUMERIC DEFAULT 0 NOT NULL, workflow TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE binding_dispatches (id TEXT PRIMARY KEY NOT NULL, binding TEXT DEFAULT '' NOT NULL,
|
||||
binding_version NUMERIC DEFAULT 0 NOT NULL, capture TEXT DEFAULT '' NOT NULL, dispatched_at TEXT DEFAULT '' NOT NULL,
|
||||
task_id NUMERIC DEFAULT 0 NOT NULL);
|
||||
CREATE UNIQUE INDEX idx_binding_dispatch_once ON binding_dispatches (binding, capture);
|
||||
CREATE TABLE playbook_dispatches (id TEXT PRIMARY KEY NOT NULL, action_id TEXT DEFAULT '' NOT NULL,
|
||||
dispatched_at TEXT DEFAULT '' NOT NULL, event_id TEXT DEFAULT '' NOT NULL, playbook_id TEXT DEFAULT '' NOT NULL,
|
||||
playbook_version TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE tool_calls (id TEXT PRIMARY KEY NOT NULL, args JSON DEFAULT NULL, attempt NUMERIC DEFAULT 0 NOT NULL,
|
||||
called_at TEXT DEFAULT '' NOT NULL, duration_ms NUMERIC DEFAULT 0 NOT NULL, error TEXT DEFAULT '' NOT NULL,
|
||||
result JSON DEFAULT NULL, task_id NUMERIC DEFAULT 0 NOT NULL, tool TEXT DEFAULT '' NOT NULL);
|
||||
|
||||
INSERT INTO captures VALUES ('rcap1', 1, '{}', 'application/json', '{"x":["1"]}', '2026-01-01T00:00:00.000000000Z', '127.0.0.1', 'gh');
|
||||
INSERT INTO captures VALUES ('rcap2', 0, '', '', NULL, '2026-01-01T00:00:01.000000000Z', '', 'gh');
|
||||
INSERT INTO mappings VALUES ('rmap1', '2026-01-01 00:00:00.000Z', '[]', 'm', 'gh', '2026-01-01 00:00:00.000Z');
|
||||
INSERT INTO bindings VALUES ('rbind1', '2026-01-01 00:00:00.000Z', 'rmap1', 'b', 'o', 'r', '` + Secret + `', 'gh', 'armed', '2026-01-01 00:00:00.000Z', 1, 'implement');
|
||||
INSERT INTO binding_dispatches VALUES ('rdisp1', 'rbind1', 1, 'rcap1', '2026-01-01 00:00:00.000Z', 4);
|
||||
INSERT INTO playbook_dispatches VALUES ('rpb1', 'act', '2026-01-01 00:00:00.000Z', 'ev', 'pb', 'v1');
|
||||
INSERT INTO tool_calls VALUES ('rtool1', NULL, 1, '2026-01-01 00:00:00.000Z', 12, '', '"exit 0"', 4, 'bash');
|
||||
`
|
||||
|
||||
const GatewayDDL = `
|
||||
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 INTEGER NOT NULL DEFAULT 0, last_active_at INTEGER NOT NULL DEFAULT 0);
|
||||
CREATE TABLE messages (id INTEGER PRIMARY KEY AUTOINCREMENT, message_id TEXT NOT NULL, session_id TEXT NOT NULL,
|
||||
source_id TEXT NOT NULL DEFAULT '', sender TEXT NOT NULL DEFAULT '', text TEXT NOT NULL DEFAULT '', ts INTEGER NOT NULL,
|
||||
UNIQUE(session_id, message_id));
|
||||
ALTER TABLE messages ADD COLUMN role TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE messages ADD COLUMN sender_id TEXT NOT NULL DEFAULT '';
|
||||
CREATE VIRTUAL TABLE messages_fts USING fts5(sender, text, content='messages', content_rowid='id');
|
||||
CREATE TRIGGER messages_ai AFTER INSERT ON messages BEGIN
|
||||
INSERT INTO messages_fts(rowid, sender, text) VALUES (new.id, new.sender, new.text);
|
||||
END;
|
||||
CREATE TABLE turns (turn_id TEXT PRIMARY KEY, session_id TEXT NOT NULL, source_id TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL, attempt INTEGER 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 INTEGER NOT NULL, updated_at INTEGER NOT NULL);
|
||||
|
||||
INSERT INTO sessions VALUES ('s1', 'telegram', 'bot', 'c1', '', 'Chat', '', '', 1000, 2000);
|
||||
INSERT INTO messages (message_id, session_id, sender, text, ts, role) VALUES ('m1', 's1', 'sam', 'hello there', 1000, 'user');
|
||||
INSERT INTO messages (message_id, session_id, sender, text, ts, role) VALUES ('m2', 's1', 'archie', 'hi', 1001, 'assistant');
|
||||
INSERT INTO turns VALUES ('t1', 's1', '', 'done', 1, '', 'm1', 'm2', '', 'hi', '[]', '', 1000, 1001);
|
||||
`
|
||||
|
||||
// Install writes the three legacy files the configured db_path names in dir
|
||||
// and returns their paths.
|
||||
func Install(t testing.TB, dbPath string) (stateStore, eda, gateway string) {
|
||||
t.Helper()
|
||||
stateStore, eda, gateway = dbPath+"-tasks.sqlite", dbPath+"-eda.sqlite", dbPath+"-conversations.sqlite"
|
||||
Exec(t, stateStore, StateStoreDDL)
|
||||
Exec(t, eda, EDADDL)
|
||||
Exec(t, gateway, GatewayDDL)
|
||||
return stateStore, eda, gateway
|
||||
}
|
||||
|
||||
// Exec runs stmt against the SQLite file at path, creating it if absent.
|
||||
func Exec(t testing.TB, path, stmt string) {
|
||||
t.Helper()
|
||||
db, err := sql.Open("sqlite", "file:"+path)
|
||||
if err != nil {
|
||||
t.Fatalf("open fixture: %v", err)
|
||||
}
|
||||
defer func() { _ = db.Close() }()
|
||||
if _, err := db.ExecContext(t.Context(), stmt); err != nil {
|
||||
t.Fatalf("fixture %s: %v", filepath.Base(path), err)
|
||||
}
|
||||
}
|
||||
@@ -1,394 +0,0 @@
|
||||
// Package legacyimport moves an existing install's SQLite stores (the State
|
||||
// Store's task database, the PocketBase event store and the Gateway
|
||||
// conversation store) into Postgres, once.
|
||||
//
|
||||
// The import is one transaction: it refuses a target that already holds data
|
||||
// in a domain it imports, refuses rather than skips a row the target cannot
|
||||
// hold, verifies what it wrote against what it read, and only then records a
|
||||
// completion row and commits. A refusal at any point leaves the target as it
|
||||
// was, migrated and empty, so a failed import is never serveable.
|
||||
//
|
||||
// It reads through legacyread, which never writes to the source files, and is
|
||||
// deleted together with it.
|
||||
package legacyimport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/legacyread"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
||||
)
|
||||
|
||||
// ErrRefused wraps every refusal. The message names each offending table,
|
||||
// row, value and rule.
|
||||
var ErrRefused = errors.New("legacy import refused")
|
||||
|
||||
// Sources are the legacy files. A path whose file does not exist means that
|
||||
// domain has nothing to import.
|
||||
type Sources struct {
|
||||
StateStore string
|
||||
EDA string
|
||||
Gateway string
|
||||
}
|
||||
|
||||
type domain struct {
|
||||
name string
|
||||
path string
|
||||
tables []legacyread.Table
|
||||
}
|
||||
|
||||
func (s Sources) domains() []domain {
|
||||
return []domain{
|
||||
{"state-store", s.StateStore, legacyread.StateStoreTables},
|
||||
{"eda", s.EDA, legacyread.EDATables},
|
||||
{"gateway", s.Gateway, legacyread.GatewayTables},
|
||||
}
|
||||
}
|
||||
|
||||
// present returns the domains whose source file exists.
|
||||
func (s Sources) present() ([]domain, error) {
|
||||
var out []domain
|
||||
for _, d := range s.domains() {
|
||||
if d.path == "" {
|
||||
continue
|
||||
}
|
||||
_, err := os.Stat(d.path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("legacy import: %w", err)
|
||||
}
|
||||
out = append(out, d)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// HasLegacyData reports whether any legacy source holds a row. With
|
||||
// postgres.ImportComplete it is what decides whether a Postgres database may
|
||||
// serve: legacy data without a completed import must be refused.
|
||||
func HasLegacyData(ctx context.Context, src Sources) (bool, error) {
|
||||
for _, d := range src.domains() {
|
||||
if d.path == "" {
|
||||
continue
|
||||
}
|
||||
has, err := legacyread.HasData(ctx, d.path, d.tables)
|
||||
if err != nil || has {
|
||||
return has, err
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Report is what an import wrote.
|
||||
type Report struct {
|
||||
// Rows is each imported table's row count.
|
||||
Rows map[string]int
|
||||
// UnindexedMessages are Gateway message ids the source's FTS5 index did
|
||||
// not cover. The target derives its search column from every row, so
|
||||
// these become searchable; the count says the source index was stale.
|
||||
UnindexedMessages []string
|
||||
}
|
||||
|
||||
func (r Report) String() string {
|
||||
var b strings.Builder
|
||||
for _, table := range slices.Sorted(maps.Keys(r.Rows)) {
|
||||
fmt.Fprintf(&b, "%s=%d ", table, r.Rows[table])
|
||||
}
|
||||
fmt.Fprintf(&b, "unindexed_messages=%d", len(r.UnindexedMessages))
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// refusal collects every problem found before giving up, so an operator fixes
|
||||
// a source in one pass rather than one row per attempt.
|
||||
type refusal []string
|
||||
|
||||
func (r *refusal) add(format string, args ...any) { *r = append(*r, fmt.Sprintf(format, args...)) }
|
||||
|
||||
func (r *refusal) err() error {
|
||||
if len(*r) == 0 {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("%w:\n %s", ErrRefused, strings.Join(*r, "\n "))
|
||||
}
|
||||
|
||||
// Import runs the one-time import from src into the database behind pool.
|
||||
// Every service that serves the database must be stopped: the import holds
|
||||
// each service's ownership claim for its whole run and refuses if any is
|
||||
// taken.
|
||||
func Import(ctx context.Context, pool *pgxpool.Pool, src Sources) (Report, error) {
|
||||
present, err := src.present()
|
||||
if err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
if len(present) == 0 {
|
||||
return Report{}, fmt.Errorf("%w: no legacy source files found (%s, %s, %s)", ErrRefused, src.StateStore, src.EDA, src.Gateway)
|
||||
}
|
||||
before, err := hashSources(present)
|
||||
if err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
if err := postgres.Migrate(ctx, pool, postgres.Migrations()); err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
release, err := claimServices(ctx, pool)
|
||||
defer release()
|
||||
if err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
sources, closeSources, err := openSources(ctx, present)
|
||||
defer closeSources()
|
||||
if err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
|
||||
var problems refusal
|
||||
if err := checkSources(ctx, sources, &problems); err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
if err := problems.err(); err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return Report{}, fmt.Errorf("legacy import: begin: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
|
||||
report, err := importInto(ctx, tx, present, sources, &problems)
|
||||
if err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
if err := checkUnchanged(before, present, &problems); err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
if err := problems.err(); err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
if err := complete(ctx, tx, present, report); err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
return report, nil
|
||||
}
|
||||
|
||||
// checkUnchanged refuses when a source's bytes moved during the import: a
|
||||
// writer that was not stopped would leave the target short of its last writes.
|
||||
func checkUnchanged(before map[string][32]byte, present []domain, problems *refusal) error {
|
||||
after, err := hashSources(present)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for path, sum := range before {
|
||||
if after[path] != sum {
|
||||
problems.add("%s changed while it was read: stop the process writing it and import again", path)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// complete writes the completion record and commits, so the record exists
|
||||
// exactly when the imported rows do.
|
||||
func complete(ctx context.Context, tx pgx.Tx, present []domain, report Report) error {
|
||||
paths := make([]string, len(present))
|
||||
for i, d := range present {
|
||||
paths[i] = d.path
|
||||
}
|
||||
if err := postgresdb.New(tx).InsertImportCompletion(ctx, postgresdb.InsertImportCompletionParams{
|
||||
Sources: strings.Join(paths, "\n"),
|
||||
Report: report.String(),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("legacy import: completion record: %w", err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("legacy import: commit: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// claimServices takes every service's ownership claim without waiting. The
|
||||
// returned release is safe to call whether or not the claims were taken.
|
||||
func claimServices(ctx context.Context, pool *pgxpool.Pool) (func(), error) {
|
||||
var claims []*postgres.Ownership
|
||||
release := func() {
|
||||
for _, c := range claims {
|
||||
_ = c.Release(context.WithoutCancel(ctx))
|
||||
}
|
||||
}
|
||||
for _, name := range []string{postgres.OwnerStateStore, postgres.OwnerGateway} {
|
||||
claim, err := postgres.AcquireOwnership(ctx, pool, name)
|
||||
if err != nil {
|
||||
return release, fmt.Errorf("legacy import: stop every Archie service first: %w", err)
|
||||
}
|
||||
claims = append(claims, claim)
|
||||
}
|
||||
return release, nil
|
||||
}
|
||||
|
||||
// openSources opens each present source read-only, keyed by domain name.
|
||||
func openSources(ctx context.Context, present []domain) (map[string]*legacyread.Source, func(), error) {
|
||||
sources := map[string]*legacyread.Source{}
|
||||
closeAll := func() {
|
||||
for _, s := range sources {
|
||||
_ = s.Close()
|
||||
}
|
||||
}
|
||||
for _, d := range present {
|
||||
s, err := legacyread.Open(ctx, d.path)
|
||||
if err != nil {
|
||||
return nil, closeAll, err
|
||||
}
|
||||
sources[d.name] = s
|
||||
}
|
||||
return sources, closeAll, nil
|
||||
}
|
||||
|
||||
// importInto loads and verifies every present domain inside tx, adding to
|
||||
// problems anything that must stop the commit.
|
||||
func importInto(ctx context.Context, tx pgx.Tx, present []domain, sources map[string]*legacyread.Source, problems *refusal) (Report, error) {
|
||||
if err := checkTarget(ctx, tx, present, problems); err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
if err := problems.err(); err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
report := Report{Rows: map[string]int{}}
|
||||
var loaded []loadedTable
|
||||
for _, d := range present {
|
||||
for _, t := range d.tables {
|
||||
lt, err := load(ctx, tx, sources[d.name], t, problems)
|
||||
if err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
loaded = append(loaded, lt)
|
||||
report.Rows[t.Name] = len(lt.keys)
|
||||
}
|
||||
}
|
||||
if err := problems.err(); err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
for _, lt := range loaded {
|
||||
if err := verify(ctx, tx, lt, problems); err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
}
|
||||
// Sources are derived, not imported: the migration derived them from an
|
||||
// empty target, so derive again from what was just loaded.
|
||||
if sources["eda"] != nil {
|
||||
if err := postgresdb.New(tx).DeriveSources(ctx); err != nil {
|
||||
return Report{}, fmt.Errorf("legacy import: derive sources: %w", err)
|
||||
}
|
||||
}
|
||||
if gw := sources["gateway"]; gw != nil {
|
||||
var err error
|
||||
if report.UnindexedMessages, err = unindexedMessages(ctx, gw, loaded); err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
}
|
||||
return report, nil
|
||||
}
|
||||
|
||||
// hashSources fingerprints each source and its WAL, so a writer that was not
|
||||
// stopped is caught rather than assumed away.
|
||||
func hashSources(present []domain) (map[string][32]byte, error) {
|
||||
out := map[string][32]byte{}
|
||||
for _, d := range present {
|
||||
for _, path := range []string{d.path, d.path + "-wal"} {
|
||||
f, err := os.Open(path)
|
||||
if errors.Is(err, os.ErrNotExist) && path != d.path {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("legacy import: %w", err)
|
||||
}
|
||||
h := sha256.New()
|
||||
_, err = io.Copy(h, f)
|
||||
_ = f.Close()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("legacy import: hash %s: %w", path, err)
|
||||
}
|
||||
out[path] = [32]byte(h.Sum(nil))
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// checkSources finds the source rows Postgres would reject or reorder.
|
||||
func checkSources(ctx context.Context, sources map[string]*legacyread.Source, problems *refusal) error {
|
||||
if s := sources["state-store"]; s != nil {
|
||||
for _, fk := range legacyread.IdentityForeignKeys {
|
||||
orphans, err := s.Orphans(ctx, fk)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, o := range orphans {
|
||||
problems.add("%s %s: %s %q has no row in %s (foreign key)", fk.Table, o.Key, fk.Column, o.Parent, fk.Parent)
|
||||
}
|
||||
}
|
||||
aliases, err := s.DuplicateAliases(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, d := range aliases {
|
||||
problems.add("identity_aliases %s: aliases collide on unique lower(alias) %q", strings.Join(d.Values, ", "), d.Key)
|
||||
}
|
||||
collisions, err := s.MicrosecondCollisions(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, c := range collisions {
|
||||
problems.add("events %d and %d: at differs only below a microsecond (%s) while ids run the other way, so (at, id) order would change",
|
||||
c.EarlierID, c.LaterID, c.At.Format("2006-01-02T15:04:05.000000Z"))
|
||||
}
|
||||
}
|
||||
if s := sources["eda"]; s != nil {
|
||||
dups, err := s.DuplicateBindings(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, d := range dups {
|
||||
problems.add("bindings %s: more than one binding for source %q (unique source); resolve them and import again",
|
||||
strings.Join(d.Values, ", "), d.Key)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkTarget refuses a database that already completed an import, or that
|
||||
// holds rows in a table owned by a domain being imported. The check is an
|
||||
// allowlist of those tables, so goose's version table and other domains'
|
||||
// tables never count.
|
||||
func checkTarget(ctx context.Context, tx pgx.Tx, present []domain, problems *refusal) error {
|
||||
done, err := postgresdb.New(tx).ImportCompleted(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("legacy import: completion record: %w", err)
|
||||
}
|
||||
if done {
|
||||
problems.add("this database already holds a completed import")
|
||||
return nil
|
||||
}
|
||||
for _, d := range present {
|
||||
for _, t := range d.tables {
|
||||
var rows bool
|
||||
if err := tx.QueryRow(ctx, "SELECT EXISTS (SELECT 1 FROM "+pgx.Identifier{t.Name}.Sanitize()+")").Scan(&rows); err != nil {
|
||||
return fmt.Errorf("legacy import: %s: %w", t.Name, err)
|
||||
}
|
||||
if rows {
|
||||
problems.add("%s is not empty: the %s target already holds data", t.Name, d.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,375 +0,0 @@
|
||||
package legacyimport
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/legacyimport/legacyfixture"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
|
||||
// install writes the three legacy files the way an existing install holds
|
||||
// them and returns their paths. mutate runs extra statements against a file
|
||||
// before the import sees it.
|
||||
func install(t *testing.T, mutate map[string]string) Sources {
|
||||
t.Helper()
|
||||
var src Sources
|
||||
src.StateStore, src.EDA, src.Gateway = legacyfixture.Install(t, filepath.Join(t.TempDir(), "archie.db"))
|
||||
for path, stmt := range mutate {
|
||||
switch path {
|
||||
case "state":
|
||||
legacyfixture.Exec(t, src.StateStore, stmt)
|
||||
case "eda":
|
||||
legacyfixture.Exec(t, src.EDA, stmt)
|
||||
case "gateway":
|
||||
legacyfixture.Exec(t, src.Gateway, stmt)
|
||||
}
|
||||
}
|
||||
return src
|
||||
}
|
||||
|
||||
func hashFiles(t *testing.T, dir string) map[string][32]byte {
|
||||
t.Helper()
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("read dir: %v", err)
|
||||
}
|
||||
out := map[string][32]byte{}
|
||||
for _, e := range entries {
|
||||
b, err := os.ReadFile(filepath.Join(dir, e.Name()))
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", e.Name(), err)
|
||||
}
|
||||
out[e.Name()] = sha256.Sum256(b)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func target(t *testing.T) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
pool, err := postgres.Open(t.Context(), pgtest.URL(t))
|
||||
if err != nil {
|
||||
t.Fatalf("postgres.Open: %v", err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
return pool
|
||||
}
|
||||
|
||||
func migrated(t *testing.T) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
pool := target(t)
|
||||
if err := postgres.Migrate(t.Context(), pool, postgres.Migrations()); err != nil {
|
||||
t.Fatalf("Migrate: %v", err)
|
||||
}
|
||||
return pool
|
||||
}
|
||||
|
||||
func count(t *testing.T, pool *pgxpool.Pool, table string) int {
|
||||
t.Helper()
|
||||
var n int
|
||||
if err := pool.QueryRow(t.Context(), "SELECT count(*) FROM "+table).Scan(&n); err != nil {
|
||||
t.Fatalf("count %s: %v", table, err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func TestImportCopiesEverySourceAndLeavesThemUntouched(t *testing.T) {
|
||||
src := install(t, nil)
|
||||
before := hashFiles(t, filepath.Dir(src.StateStore))
|
||||
pool := target(t)
|
||||
|
||||
report, err := Import(t.Context(), pool, src)
|
||||
if err != nil {
|
||||
t.Fatalf("Import: %v", err)
|
||||
}
|
||||
|
||||
if after := hashFiles(t, filepath.Dir(src.StateStore)); len(after) != len(before) {
|
||||
t.Fatalf("source directory changed: %d files before, %d after", len(before), len(after))
|
||||
} else {
|
||||
for name, sum := range before {
|
||||
if after[name] != sum {
|
||||
t.Errorf("source %s changed during import", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
done, err := postgres.ImportComplete(t.Context(), pool)
|
||||
if err != nil || !done {
|
||||
t.Fatalf("ImportComplete = %v, %v; want true", done, err)
|
||||
}
|
||||
|
||||
counts := map[string]int{
|
||||
"tasks": 2, "transitions": 1, "events": 3, "resources": 1, "resource_history": 1,
|
||||
"channel_status": 1, "apply_status": 1, "config_snapshot": 1, "identities": 1,
|
||||
"identity_aliases": 1, "identity_events": 1, "identity_subjects": 1,
|
||||
"captures": 2, "mappings": 1, "bindings": 1, "binding_dispatches": 1, "playbook_dispatches": 1,
|
||||
"tool_calls": 1, "sessions": 1, "messages": 2, "turns": 1,
|
||||
}
|
||||
for table, want := range counts {
|
||||
if got := count(t, pool, table); got != want {
|
||||
t.Errorf("%s rows = %d, want %d", table, got, want)
|
||||
}
|
||||
if got := report.Rows[table]; got != want {
|
||||
t.Errorf("report rows[%s] = %d, want %d", table, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
ctx := t.Context()
|
||||
var (
|
||||
reviewCursor int64
|
||||
value []byte
|
||||
gotSecret string
|
||||
headers string
|
||||
result string
|
||||
configured bool
|
||||
)
|
||||
checks := []struct {
|
||||
query string
|
||||
dest any
|
||||
}{
|
||||
{"SELECT review_cursor FROM tasks WHERE id = 1", &reviewCursor},
|
||||
{"SELECT value FROM resource_history WHERE id = 1", &value},
|
||||
{"SELECT secret FROM sources WHERE path = 'gh'", &gotSecret},
|
||||
{"SELECT headers FROM captures WHERE id = 'rcap2'", &headers},
|
||||
{"SELECT result FROM tool_calls WHERE id = 'rtool1'", &result},
|
||||
{"SELECT configured FROM channel_status WHERE id = 'tg'", &configured},
|
||||
}
|
||||
for _, c := range checks {
|
||||
if err := pool.QueryRow(ctx, c.query).Scan(c.dest); err != nil {
|
||||
t.Fatalf("%s: %v", c.query, err)
|
||||
}
|
||||
}
|
||||
if reviewCursor != 3 {
|
||||
t.Errorf("review_cursor = %d, want 3", reviewCursor)
|
||||
}
|
||||
if !bytes.Equal(value, []byte{0x00, 0xff, 0x10}) {
|
||||
t.Errorf("resource_history.value = %x, want 00ff10", value)
|
||||
}
|
||||
if gotSecret != legacyfixture.Secret {
|
||||
t.Errorf("binding secret = %q, want %q", gotSecret, legacyfixture.Secret)
|
||||
}
|
||||
if headers != "" || result != "exit 0" || !configured {
|
||||
t.Errorf("headers %q, result %q, configured %v; want \"\", \"exit 0\", true", headers, result, configured)
|
||||
}
|
||||
|
||||
// Event order is (at, id) as the source had it, and the next event id
|
||||
// follows AUTOINCREMENT's high-water mark rather than reusing one.
|
||||
rows, err := pool.Query(ctx, "SELECT id FROM events ORDER BY at, id")
|
||||
if err != nil {
|
||||
t.Fatalf("events: %v", err)
|
||||
}
|
||||
var order []int64
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
t.Fatalf("scan: %v", err)
|
||||
}
|
||||
order = append(order, id)
|
||||
}
|
||||
if want := []int64{1, 5, 2}; !equalInts(order, want) {
|
||||
t.Errorf("event order = %v, want %v", order, want)
|
||||
}
|
||||
nextIDs := map[string]int64{"tasks": 10, "events": 6, "messages": 3}
|
||||
for table, want := range nextIDs {
|
||||
var got int64
|
||||
if err := pool.QueryRow(ctx, "SELECT nextval(pg_get_serial_sequence($1, 'id'))", table).Scan(&got); err != nil {
|
||||
t.Fatalf("nextval %s: %v", table, err)
|
||||
}
|
||||
if got != want {
|
||||
t.Errorf("next %s id = %d, want %d", table, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
var hits int
|
||||
if err := pool.QueryRow(ctx, "SELECT count(*) FROM messages WHERE search @@ to_tsquery('simple', 'hello')").Scan(&hits); err != nil {
|
||||
t.Fatalf("search: %v", err)
|
||||
}
|
||||
if hits != 1 {
|
||||
t.Errorf("search hits for an imported message = %d, want 1", hits)
|
||||
}
|
||||
}
|
||||
|
||||
func equalInts(a, b []int64) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i := range a {
|
||||
if a[i] != b[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func TestImportRefuses(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate map[string]string
|
||||
seed func(t *testing.T, pool *pgxpool.Pool)
|
||||
want []string
|
||||
is error
|
||||
}{
|
||||
{
|
||||
name: "non-empty target",
|
||||
seed: func(t *testing.T, pool *pgxpool.Pool) {
|
||||
mustExec(t, pool, "INSERT INTO transitions (task_id, from_status, to_status) VALUES (1, 'a', 'b')")
|
||||
},
|
||||
want: []string{"transitions", "not empty"},
|
||||
},
|
||||
{
|
||||
name: "completed import",
|
||||
seed: func(t *testing.T, pool *pgxpool.Pool) {
|
||||
mustExec(t, pool, "INSERT INTO import_completion (id, sources, report) VALUES (1, 's', 'r')")
|
||||
},
|
||||
want: []string{"already"},
|
||||
},
|
||||
{
|
||||
name: "live state store",
|
||||
seed: func(t *testing.T, pool *pgxpool.Pool) { holdOwnership(t, pool, postgres.OwnerStateStore) },
|
||||
want: []string{"state-store"},
|
||||
is: postgres.ErrOwned,
|
||||
},
|
||||
{
|
||||
name: "live gateway",
|
||||
seed: func(t *testing.T, pool *pgxpool.Pool) { holdOwnership(t, pool, postgres.OwnerGateway) },
|
||||
want: []string{"gateway"},
|
||||
is: postgres.ErrOwned,
|
||||
},
|
||||
{
|
||||
name: "orphaned alias",
|
||||
mutate: map[string]string{"state": "INSERT INTO identity_aliases VALUES ('ghost', 'id-404')"},
|
||||
want: []string{"identity_aliases", "ghost", "id-404"},
|
||||
},
|
||||
{
|
||||
name: "duplicate bindings",
|
||||
mutate: map[string]string{"eda": "INSERT INTO bindings VALUES ('rbind2', '2026-01-01 00:00:00.000Z', '', 'b2', 'o', 'r', '', 'gh', 'pending_approval', '2026-01-01 00:00:00.000Z', 1, 'implement')"},
|
||||
want: []string{"bindings", "gh", "rbind1", "rbind2"},
|
||||
},
|
||||
{
|
||||
name: "microsecond collision",
|
||||
mutate: map[string]string{"state": "INSERT INTO events (id, at, kind) VALUES (7, '2026-01-01T00:00:00.000000050Z', 'd')"},
|
||||
want: []string{"events", "7", "microsecond"},
|
||||
},
|
||||
{
|
||||
name: "unparseable timestamp",
|
||||
mutate: map[string]string{"eda": "UPDATE captures SET received_at = 'yesterday' WHERE id = 'rcap2'"},
|
||||
want: []string{"captures", "rcap2", "yesterday", "received_at"},
|
||||
},
|
||||
{
|
||||
name: "null in a required column",
|
||||
mutate: map[string]string{"state": "UPDATE tasks SET title = NULL WHERE id = 4"},
|
||||
want: []string{"tasks", "4", "title", "NULL"},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
src := install(t, tt.mutate)
|
||||
pool := migrated(t)
|
||||
if tt.seed != nil {
|
||||
tt.seed(t, pool)
|
||||
}
|
||||
_, err := Import(t.Context(), pool, src)
|
||||
if err == nil {
|
||||
t.Fatal("Import succeeded, want a refusal")
|
||||
}
|
||||
if tt.is != nil && !errors.Is(err, tt.is) {
|
||||
t.Errorf("Import error %v, want %v", err, tt.is)
|
||||
}
|
||||
for _, w := range tt.want {
|
||||
if !strings.Contains(err.Error(), w) {
|
||||
t.Errorf("refusal %q does not name %q", err, w)
|
||||
}
|
||||
}
|
||||
// Nothing of the import survives a refusal: the store stays
|
||||
// unserveable rather than half-imported.
|
||||
if got := count(t, pool, "tasks"); got != 0 {
|
||||
t.Errorf("tasks rows after refusal = %d, want 0", got)
|
||||
}
|
||||
if got := count(t, pool, "import_completion"); tt.name != "completed import" && got != 0 {
|
||||
t.Errorf("completion records after refusal = %d, want 0", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func mustExec(t *testing.T, pool *pgxpool.Pool, stmt string) {
|
||||
t.Helper()
|
||||
if _, err := pool.Exec(t.Context(), stmt); err != nil {
|
||||
t.Fatalf("%s: %v", stmt, err)
|
||||
}
|
||||
}
|
||||
|
||||
// holdOwnership claims name from a separate pool, as a live service would.
|
||||
func holdOwnership(t *testing.T, pool *pgxpool.Pool, name string) {
|
||||
t.Helper()
|
||||
other, err := pgxpool.New(t.Context(), pool.Config().ConnString())
|
||||
if err != nil {
|
||||
t.Fatalf("second pool: %v", err)
|
||||
}
|
||||
t.Cleanup(other.Close)
|
||||
claim, err := postgres.AcquireOwnership(t.Context(), other, name)
|
||||
if err != nil {
|
||||
t.Fatalf("claim %s: %v", name, err)
|
||||
}
|
||||
t.Cleanup(func() { _ = claim.Release(t.Context()) })
|
||||
}
|
||||
|
||||
// TestSiblingDomainDoesNotBlock pins that "non-empty" is per domain: a
|
||||
// domain with no legacy source is not imported, so rows in its tables do not
|
||||
// refuse the others.
|
||||
func TestSiblingDomainDoesNotBlock(t *testing.T) {
|
||||
src := install(t, nil)
|
||||
src.Gateway = filepath.Join(t.TempDir(), "absent.sqlite")
|
||||
pool := migrated(t)
|
||||
mustExec(t, pool, "INSERT INTO sessions (session_id) VALUES ('live')")
|
||||
if _, err := Import(t.Context(), pool, src); err != nil {
|
||||
t.Fatalf("Import: %v", err)
|
||||
}
|
||||
if got := count(t, pool, "tasks"); got != 2 {
|
||||
t.Fatalf("tasks rows = %d, want 2", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportRefusesWithNoSources(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
src := Sources{StateStore: filepath.Join(dir, "a"), EDA: filepath.Join(dir, "b"), Gateway: filepath.Join(dir, "c")}
|
||||
if _, err := Import(t.Context(), migrated(t), src); err == nil || !strings.Contains(err.Error(), "no legacy") {
|
||||
t.Fatalf("Import = %v, want a refusal naming no legacy sources", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHasLegacyData(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
absent := Sources{StateStore: filepath.Join(dir, "a"), EDA: filepath.Join(dir, "b"), Gateway: filepath.Join(dir, "c")}
|
||||
onlyGateway := absent
|
||||
onlyGateway.Gateway = install(t, nil).Gateway
|
||||
tests := []struct {
|
||||
name string
|
||||
src Sources
|
||||
want bool
|
||||
}{
|
||||
{"fresh install", absent, false},
|
||||
{"one source with rows", onlyGateway, true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := HasLegacyData(t.Context(), tt.src)
|
||||
if err != nil {
|
||||
t.Fatalf("HasLegacyData: %v", err)
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Fatalf("HasLegacyData = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,307 +0,0 @@
|
||||
package legacyimport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/legacyread"
|
||||
)
|
||||
|
||||
// droppedColumns are legacy columns with no target column by design:
|
||||
// PocketBase gave every ledger row a random record id, and the Postgres
|
||||
// ledgers are keyed by their natural unique key instead.
|
||||
var droppedColumns = map[string]bool{
|
||||
"binding_dispatches.id": true,
|
||||
"playbook_dispatches.id": true,
|
||||
}
|
||||
|
||||
// newColumns are target columns added after the legacy stores, with no
|
||||
// legacy value to carry; an imported row takes the column default. An
|
||||
// imported capture has no event type, so it stays unidentified and never
|
||||
// dispatches, and no legacy source could take unsigned events. An imported
|
||||
// mapping has no event type, so no binding using it dispatches until it is
|
||||
// given one, and an imported binding has no filter. Nor does an imported
|
||||
// binding assign workflow inputs or read its repository from a parameter,
|
||||
// and no legacy task carries inputs.
|
||||
var newColumns = map[string]bool{
|
||||
"captures.event_type": true,
|
||||
"mappings.event_type": true,
|
||||
"bindings.filter": true,
|
||||
"captures.unsigned": true,
|
||||
"bindings.inputs": true,
|
||||
"bindings.repo_param": true,
|
||||
"tasks.inputs": true,
|
||||
}
|
||||
|
||||
// targetKeys override a table's legacy key where the target has no column
|
||||
// for it.
|
||||
var targetKeys = map[string][]string{
|
||||
"binding_dispatches": {"binding", "capture"},
|
||||
"playbook_dispatches": {"playbook_id", "playbook_version", "event_id", "action_id"},
|
||||
}
|
||||
|
||||
// jsonColumns are PocketBase JSON fields, which may be NULL in the source and
|
||||
// map to a NOT NULL text column defaulting to the empty string. unwrap marks the fields the legacy reader
|
||||
// decoded from a JSON string (jsonTextToString) rather than returning raw.
|
||||
var jsonColumns = map[string]struct{ unwrap bool }{
|
||||
"captures.headers": {},
|
||||
"mappings.fields": {},
|
||||
"tool_calls.args": {unwrap: true},
|
||||
"tool_calls.result": {unwrap: true},
|
||||
}
|
||||
|
||||
// timeLayouts are every layout a legacy timestamp was written in: the
|
||||
// fixed-width cursor layout, Go's RFC 3339 forms, PocketBase's autodate
|
||||
// layout and SQLite's datetime('now').
|
||||
var timeLayouts = []string{
|
||||
"2006-01-02T15:04:05.000000000Z",
|
||||
time.RFC3339Nano,
|
||||
time.RFC3339,
|
||||
"2006-01-02 15:04:05.999999999Z07:00",
|
||||
"2006-01-02 15:04:05.999999999",
|
||||
}
|
||||
|
||||
type column struct {
|
||||
name string
|
||||
dataType string
|
||||
identity bool
|
||||
source int // index into the legacy row
|
||||
}
|
||||
|
||||
// loadedTable is what load wrote, for verify to check.
|
||||
type loadedTable struct {
|
||||
table legacyread.Table
|
||||
rows legacyread.Rows
|
||||
keys []string // target keys of the rows written, in source read order
|
||||
keyCols []string
|
||||
identity bool
|
||||
}
|
||||
|
||||
// load reads t from src, converts every row to the target's types and copies
|
||||
// them in with their historical ids. A row it cannot convert is added to
|
||||
// problems and nothing of the table is written.
|
||||
func load(ctx context.Context, tx pgx.Tx, src *legacyread.Source, t legacyread.Table, problems *refusal) (loadedTable, error) {
|
||||
cols, err := plan(ctx, tx, t, problems)
|
||||
if err != nil || cols == nil {
|
||||
return loadedTable{table: t}, err
|
||||
}
|
||||
rows, err := src.Read(ctx, t)
|
||||
if err != nil {
|
||||
return loadedTable{}, err
|
||||
}
|
||||
lt := loadedTable{table: t, rows: rows, keyCols: t.Key}
|
||||
if k, ok := targetKeys[t.Name]; ok {
|
||||
lt.keyCols = k
|
||||
}
|
||||
names := make([]string, len(cols))
|
||||
for i, c := range cols {
|
||||
names[i] = c.name
|
||||
lt.identity = lt.identity || c.identity
|
||||
}
|
||||
out, ok := convertRows(lt, cols, names, problems)
|
||||
if !ok {
|
||||
return lt, nil
|
||||
}
|
||||
for _, row := range out {
|
||||
key := make([]string, len(lt.keyCols))
|
||||
for j, k := range lt.keyCols {
|
||||
key[j] = fmt.Sprint(row[slices.Index(names, k)])
|
||||
}
|
||||
lt.keys = append(lt.keys, strings.Join(key, "/"))
|
||||
}
|
||||
if len(out) > 0 {
|
||||
if _, err := tx.CopyFrom(ctx, pgx.Identifier{t.Name}, names, pgx.CopyFromRows(out)); err != nil {
|
||||
problems.add("%s: the target rejected the rows: %v", t.Name, err)
|
||||
return lt, nil
|
||||
}
|
||||
}
|
||||
if lt.identity {
|
||||
return lt, advanceSequence(ctx, tx, src, t.Name)
|
||||
}
|
||||
return lt, nil
|
||||
}
|
||||
|
||||
// convertRows converts every row of lt, adding each value it cannot convert
|
||||
// to problems.
|
||||
func convertRows(lt loadedTable, cols []column, names []string, problems *refusal) ([][]any, bool) {
|
||||
sourceKeys := lt.rows.Keys()
|
||||
out := make([][]any, 0, len(lt.rows.Rows))
|
||||
ok := true
|
||||
for i, row := range lt.rows.Rows {
|
||||
converted := make([]any, len(cols))
|
||||
for j, c := range cols {
|
||||
v, err := convert(lt.table.Name+"."+c.name, c.dataType, row[c.source])
|
||||
if err != nil {
|
||||
problems.add("%s %s: column %s value %s: %v", lt.table.Name, sourceKeys[i], names[j], quote(row[c.source]), err)
|
||||
ok = false
|
||||
}
|
||||
converted[j] = v
|
||||
}
|
||||
out = append(out, converted)
|
||||
}
|
||||
return out, ok
|
||||
}
|
||||
|
||||
// advanceSequence sets table's identity sequence to hand out the id the
|
||||
// legacy AUTOINCREMENT would have, even for a table whose rows were all
|
||||
// deleted. is_called = false makes that id the next one, which keeps
|
||||
// AUTOINCREMENT's promise that a deleted top id is never reused.
|
||||
func advanceSequence(ctx context.Context, tx pgx.Tx, src *legacyread.Source, table string) error {
|
||||
seq, err := src.SequenceOf(ctx, table)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, "SELECT setval(pg_get_serial_sequence($1, 'id'), $2, false)", table, seq.Next); err != nil {
|
||||
return fmt.Errorf("legacy import: advance %s sequence: %w", table, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// plan matches the target table's columns to the legacy ones. A column on
|
||||
// either side with no counterpart is a schema gap the import refuses to
|
||||
// guess about; it returns nil columns then.
|
||||
func plan(ctx context.Context, tx pgx.Tx, t legacyread.Table, problems *refusal) ([]column, error) {
|
||||
rows, err := tx.Query(ctx, `SELECT column_name, data_type, is_identity = 'YES'
|
||||
FROM information_schema.columns
|
||||
WHERE table_schema = current_schema() AND table_name = $1 AND is_generated = 'NEVER'
|
||||
ORDER BY ordinal_position`, t.Name)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("legacy import: %s columns: %w", t.Name, err)
|
||||
}
|
||||
cols, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (column, error) {
|
||||
var c column
|
||||
err := row.Scan(&c.name, &c.dataType, &c.identity)
|
||||
return c, err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("legacy import: %s columns: %w", t.Name, err)
|
||||
}
|
||||
gap := len(cols) == 0
|
||||
if gap {
|
||||
problems.add("%s: no target table", t.Name)
|
||||
}
|
||||
targetNames := map[string]bool{}
|
||||
cols = slices.DeleteFunc(cols, func(c column) bool { return newColumns[t.Name+"."+c.name] })
|
||||
for i := range cols {
|
||||
targetNames[cols[i].name] = true
|
||||
cols[i].source = slices.Index(t.Columns, cols[i].name)
|
||||
if cols[i].source < 0 {
|
||||
problems.add("%s.%s: the target column has no legacy column", t.Name, cols[i].name)
|
||||
gap = true
|
||||
}
|
||||
}
|
||||
for _, c := range t.Columns {
|
||||
if !targetNames[c] && !droppedColumns[t.Name+"."+c] {
|
||||
problems.add("%s.%s: the legacy column has no target column", t.Name, c)
|
||||
gap = true
|
||||
}
|
||||
}
|
||||
if gap {
|
||||
return nil, nil
|
||||
}
|
||||
return cols, nil
|
||||
}
|
||||
|
||||
// convert maps one SQLite value to the Go value pgx writes to a column of
|
||||
// dataType. It never coerces: a value the column cannot hold is an error
|
||||
// naming the rule it breaks.
|
||||
func convert(qualified, dataType string, v any) (any, error) {
|
||||
if j, ok := jsonColumns[qualified]; ok {
|
||||
return convertJSON(v, j.unwrap)
|
||||
}
|
||||
if v == nil {
|
||||
return nil, fmt.Errorf("NULL in a NOT NULL %s column", dataType)
|
||||
}
|
||||
conv, ok := converters[dataType]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unsupported target type %s", dataType)
|
||||
}
|
||||
return conv(v)
|
||||
}
|
||||
|
||||
func convertJSON(v any, unwrap bool) (any, error) {
|
||||
switch s := v.(type) {
|
||||
case nil:
|
||||
return "", nil
|
||||
case string:
|
||||
if unwrap {
|
||||
var decoded string
|
||||
if json.Unmarshal([]byte(s), &decoded) == nil {
|
||||
return decoded, nil
|
||||
}
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
return nil, errors.New("text: not a string")
|
||||
}
|
||||
|
||||
// converters are keyed by information_schema data_type.
|
||||
var converters = map[string]func(any) (any, error){
|
||||
"text": func(v any) (any, error) {
|
||||
if s, ok := v.(string); ok {
|
||||
return s, nil
|
||||
}
|
||||
return nil, errors.New("text: not a string")
|
||||
},
|
||||
"bigint": func(v any) (any, error) {
|
||||
switch n := v.(type) {
|
||||
case int64:
|
||||
return n, nil
|
||||
case float64:
|
||||
if n == math.Trunc(n) && math.Abs(n) < 1<<63 {
|
||||
return int64(n), nil
|
||||
}
|
||||
}
|
||||
return nil, errors.New("bigint: not an integer")
|
||||
},
|
||||
"boolean": func(v any) (any, error) {
|
||||
switch b := v.(type) {
|
||||
case bool:
|
||||
return b, nil
|
||||
case int64:
|
||||
if b == 0 || b == 1 {
|
||||
return b == 1, nil
|
||||
}
|
||||
}
|
||||
return nil, errors.New("boolean: not 0 or 1")
|
||||
},
|
||||
"bytea": func(v any) (any, error) {
|
||||
switch b := v.(type) {
|
||||
case []byte:
|
||||
return b, nil
|
||||
case string:
|
||||
return []byte(b), nil
|
||||
}
|
||||
return nil, errors.New("bytea: not a blob")
|
||||
},
|
||||
"timestamp with time zone": func(v any) (any, error) {
|
||||
if s, ok := v.(string); ok {
|
||||
for _, layout := range timeLayouts {
|
||||
if at, err := time.Parse(layout, s); err == nil {
|
||||
return at.UTC(), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil, errors.New("timestamptz: not a timestamp in any legacy layout")
|
||||
},
|
||||
}
|
||||
|
||||
func quote(v any) string {
|
||||
switch s := v.(type) {
|
||||
case nil:
|
||||
return "NULL"
|
||||
case string:
|
||||
return fmt.Sprintf("%q", s)
|
||||
case []byte:
|
||||
return fmt.Sprintf("x'%x'", s)
|
||||
}
|
||||
return fmt.Sprint(v)
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
package legacyimport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/legacyread"
|
||||
)
|
||||
|
||||
// blobColumns are the columns whose bytes must survive exactly: resource
|
||||
// documents, and binding secrets, which stay decryptable by the configured
|
||||
// keyring only if the envelope is untouched.
|
||||
var blobColumns = map[string]string{
|
||||
"resources": "value",
|
||||
"resource_history": "value",
|
||||
"bindings": "secret",
|
||||
}
|
||||
|
||||
// verify reads back what load wrote for lt and compares it with the source:
|
||||
// the key set (a count passes on a swallowed row when ids have gaps), the
|
||||
// (at, id) event order, blob bytes and the identity sequence.
|
||||
func verify(ctx context.Context, tx pgx.Tx, lt loadedTable, problems *refusal) error {
|
||||
name := lt.table.Name
|
||||
ident := pgx.Identifier{name}.Sanitize()
|
||||
keyExprs := make([]string, len(lt.keyCols))
|
||||
for i, k := range lt.keyCols {
|
||||
keyExprs[i] = pgx.Identifier{k}.Sanitize() + "::text"
|
||||
}
|
||||
keyExpr := "concat_ws('/', " + strings.Join(keyExprs, ", ") + ")"
|
||||
|
||||
targetKeys, err := strs(ctx, tx, "SELECT "+keyExpr+" FROM "+ident)
|
||||
if err != nil {
|
||||
return fmt.Errorf("legacy import: verify %s: %w", name, err)
|
||||
}
|
||||
if len(targetKeys) != len(lt.keys) {
|
||||
problems.add("%s: %d rows read, %d rows in the target", name, len(lt.keys), len(targetKeys))
|
||||
}
|
||||
if d := legacyread.CompareKeys(lt.keys, targetKeys); len(d.Missing)+len(d.Extra) > 0 {
|
||||
problems.add("%s: rows missing from the target %v, rows only in the target %v", name, d.Missing, d.Extra)
|
||||
}
|
||||
|
||||
if name == "events" {
|
||||
if err := verifyEventOrder(ctx, tx, lt, problems); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if col, ok := blobColumns[name]; ok {
|
||||
if err := verifyBlobs(ctx, tx, lt, col, keyExpr, problems); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if lt.identity {
|
||||
return verifySequence(ctx, tx, name, problems)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// verifySequence asserts the next id the sequence hands out is above every
|
||||
// imported id, reading its state rather than calling nextval.
|
||||
func verifySequence(ctx context.Context, tx pgx.Tx, name string, problems *refusal) error {
|
||||
var seq string
|
||||
var maxID int64
|
||||
if err := tx.QueryRow(ctx, "SELECT pg_get_serial_sequence($1, 'id'), (SELECT COALESCE(max(id), 0) FROM "+
|
||||
pgx.Identifier{name}.Sanitize()+")", name).Scan(&seq, &maxID); err != nil {
|
||||
return fmt.Errorf("legacy import: verify %s sequence: %w", name, err)
|
||||
}
|
||||
var (
|
||||
last int64
|
||||
called bool
|
||||
)
|
||||
// seq comes from pg_get_serial_sequence, which returns it quoted.
|
||||
if err := tx.QueryRow(ctx, "SELECT last_value, is_called FROM "+seq).Scan(&last, &called); err != nil {
|
||||
return fmt.Errorf("legacy import: verify %s sequence: %w", name, err)
|
||||
}
|
||||
next := last
|
||||
if called {
|
||||
next++
|
||||
}
|
||||
if next <= maxID {
|
||||
problems.add("%s: next id %d would reuse an imported id (max %d)", name, next, maxID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// verifyEventOrder compares the ids in (at, id) order on both sides. The
|
||||
// source was read in that order; a difference means microsecond storage
|
||||
// reordered history, and a cursor reader would skip a row.
|
||||
func verifyEventOrder(ctx context.Context, tx pgx.Tx, lt loadedTable, problems *refusal) error {
|
||||
source := make([]int64, len(lt.keys))
|
||||
for i, k := range lt.keys {
|
||||
id, err := strconv.ParseInt(k, 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("legacy import: event key %q: %w", k, err)
|
||||
}
|
||||
source[i] = id
|
||||
}
|
||||
rows, err := tx.Query(ctx, "SELECT id FROM events ORDER BY at, id")
|
||||
if err != nil {
|
||||
return fmt.Errorf("legacy import: verify events order: %w", err)
|
||||
}
|
||||
target, err := pgx.CollectRows(rows, pgx.RowTo[int64])
|
||||
if err != nil {
|
||||
return fmt.Errorf("legacy import: verify events order: %w", err)
|
||||
}
|
||||
if d := legacyread.CompareOrder(source, target); d != nil {
|
||||
problems.add("events: (at, id) order differs at position %d: source id %d, target id %d", d.Position, d.Source, d.Target)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func verifyBlobs(ctx context.Context, tx pgx.Tx, lt loadedTable, col, keyExpr string, problems *refusal) error {
|
||||
source := map[string][]byte{}
|
||||
for i, k := range lt.keys {
|
||||
switch v := lt.rows.Value(i, col).(type) {
|
||||
case []byte:
|
||||
source[k] = v
|
||||
case string:
|
||||
source[k] = []byte(v)
|
||||
}
|
||||
}
|
||||
rows, err := tx.Query(ctx, fmt.Sprintf("SELECT %s, %s FROM %s", keyExpr,
|
||||
pgx.Identifier{col}.Sanitize(), pgx.Identifier{lt.table.Name}.Sanitize()))
|
||||
if err != nil {
|
||||
return fmt.Errorf("legacy import: verify %s.%s: %w", lt.table.Name, col, err)
|
||||
}
|
||||
target := map[string][]byte{}
|
||||
for rows.Next() {
|
||||
var (
|
||||
k string
|
||||
v []byte
|
||||
)
|
||||
if err := rows.Scan(&k, &v); err != nil {
|
||||
rows.Close()
|
||||
return fmt.Errorf("legacy import: verify %s.%s: %w", lt.table.Name, col, err)
|
||||
}
|
||||
target[k] = v
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return fmt.Errorf("legacy import: verify %s.%s: %w", lt.table.Name, col, err)
|
||||
}
|
||||
if diff := legacyread.CompareBlobs(source, target); len(diff) > 0 {
|
||||
problems.add("%s.%s: bytes differ from the source for %v", lt.table.Name, col, diff)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// unindexedMessages returns the source message ids the FTS5 index missed.
|
||||
func unindexedMessages(ctx context.Context, gw *legacyread.Source, loaded []loadedTable) ([]string, error) {
|
||||
indexed, err := gw.IndexedMessageIDs(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, lt := range loaded {
|
||||
if lt.table.Name == "messages" {
|
||||
return legacyread.CompareKeys(indexed, lt.keys).Extra, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func strs(ctx context.Context, tx pgx.Tx, query string) ([]string, error) {
|
||||
rows, err := tx.Query(ctx, query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return pgx.CollectRows(rows, pgx.RowTo[string])
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
// Package legacyread reads an existing install's SQLite stores (the State
|
||||
// Store's archie.db, the PocketBase event store and the Gateway conversation
|
||||
// store) for the one-time import into Postgres, and verifies what was read.
|
||||
//
|
||||
// Every production opener of those files writes on open (schema migrations,
|
||||
// PocketBase bootstrap, DDL and backfills), so this package never imports
|
||||
// them: it opens each file read-only and issues only SELECT. It knows nothing
|
||||
// about Postgres; values come back as the SQLite driver's native types
|
||||
// (int64, float64, string, []byte, nil) under their legacy column names.
|
||||
//
|
||||
// The package exists only for the import and is deleted with it.
|
||||
package legacyread
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
// Source is one legacy SQLite file opened read-only. The process that owns
|
||||
// the file must be stopped: a read-only open cannot checkpoint a WAL.
|
||||
type Source struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
// Open opens path read-only. It refuses a path that does not exist rather
|
||||
// than letting SQLite create an empty database there.
|
||||
func Open(ctx context.Context, path string) (*Source, error) {
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
return nil, fmt.Errorf("legacyread: %w", err)
|
||||
}
|
||||
db, err := sql.Open("sqlite", "file:"+path+"?mode=ro&_pragma=busy_timeout(5000)")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("legacyread: open %s: %w", path, err)
|
||||
}
|
||||
if err := db.PingContext(ctx); err != nil {
|
||||
return nil, errors.Join(fmt.Errorf("legacyread: open %s: %w", path, err), db.Close())
|
||||
}
|
||||
return &Source{db: db}, nil
|
||||
}
|
||||
|
||||
// Close closes the source.
|
||||
func (s *Source) Close() error { return s.db.Close() }
|
||||
|
||||
// Table names one legacy table: its columns as the production code leaves
|
||||
// them (columns added by ALTER TABLE included), the columns that identify a
|
||||
// row, and the order it is read in.
|
||||
type Table struct {
|
||||
Name string
|
||||
Columns []string
|
||||
Key []string
|
||||
OrderBy string
|
||||
}
|
||||
|
||||
// Rows is one table's contents in read order.
|
||||
type Rows struct {
|
||||
Table Table
|
||||
Rows [][]any
|
||||
}
|
||||
|
||||
// Value returns column col of row i, or nil for an unknown column.
|
||||
func (r Rows) Value(i int, col string) any {
|
||||
for j, c := range r.Table.Columns {
|
||||
if c == col {
|
||||
return r.Rows[i][j]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Keys returns each row's key, its key columns joined with "/", in read order.
|
||||
func (r Rows) Keys() []string {
|
||||
keys := make([]string, len(r.Rows))
|
||||
for i := range r.Rows {
|
||||
parts := make([]string, len(r.Table.Key))
|
||||
for j, col := range r.Table.Key {
|
||||
parts[j] = fmt.Sprint(r.Value(i, col))
|
||||
}
|
||||
keys[i] = strings.Join(parts, "/")
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
// Read returns every row of t.
|
||||
func (s *Source) Read(ctx context.Context, t Table) (Rows, error) {
|
||||
query := "SELECT " + strings.Join(t.Columns, ", ") + " FROM " + t.Name + " ORDER BY " + t.OrderBy
|
||||
rows, err := s.db.QueryContext(ctx, query)
|
||||
if err != nil {
|
||||
return Rows{}, fmt.Errorf("legacyread: read %s: %w", t.Name, err)
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
out := Rows{Table: t}
|
||||
for rows.Next() {
|
||||
row := make([]any, len(t.Columns))
|
||||
ptrs := make([]any, len(row))
|
||||
for i := range row {
|
||||
ptrs[i] = &row[i]
|
||||
}
|
||||
if err := rows.Scan(ptrs...); err != nil {
|
||||
return Rows{}, fmt.Errorf("legacyread: read %s: %w", t.Name, err)
|
||||
}
|
||||
out.Rows = append(out.Rows, row)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return Rows{}, fmt.Errorf("legacyread: read %s: %w", t.Name, err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// IndexedMessageIDs returns the message ids the Gateway's FTS5 search index
|
||||
// holds. messages_fts is an external-content index derived from messages, so
|
||||
// it is rebuilt on the target rather than copied; what the import must account
|
||||
// for is whether it covered every message, which comparing this set against
|
||||
// the messages ids answers.
|
||||
func (s *Source) IndexedMessageIDs(ctx context.Context) ([]string, error) {
|
||||
return s.strings(ctx, "SELECT CAST(id AS TEXT) FROM messages_fts_docsize ORDER BY id")
|
||||
}
|
||||
|
||||
func (s *Source) strings(ctx context.Context, query string) ([]string, error) {
|
||||
rows, err := s.db.QueryContext(ctx, query)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("legacyread: %w", err)
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
var out []string
|
||||
for rows.Next() {
|
||||
var v string
|
||||
if err := rows.Scan(&v); err != nil {
|
||||
return nil, fmt.Errorf("legacyread: %w", err)
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
@@ -1,449 +0,0 @@
|
||||
package legacyread
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The fixtures below apply the legacy schemas as their production openers
|
||||
// leave them, columns added by ALTER TABLE included, without importing those
|
||||
// openers.
|
||||
const stateStoreDDL = `
|
||||
CREATE TABLE tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, owner TEXT NOT NULL, repo TEXT NOT NULL,
|
||||
issue_number INTEGER NOT NULL, title TEXT DEFAULT '', body TEXT DEFAULT '', labels TEXT DEFAULT '',
|
||||
status TEXT DEFAULT 'queued', workflow TEXT DEFAULT '', stage TEXT DEFAULT '', branch TEXT DEFAULT '',
|
||||
plan TEXT DEFAULT '', notes TEXT DEFAULT '', pr_number INTEGER DEFAULT 0, tokens_used INTEGER DEFAULT 0,
|
||||
iterations INTEGER DEFAULT 0, attempt INTEGER DEFAULT 0, park_reason TEXT DEFAULT '',
|
||||
watch_comment_id INTEGER DEFAULT 0, park_class TEXT DEFAULT 'needs_human', remediation_rounds INTEGER DEFAULT 0,
|
||||
retry_count INTEGER DEFAULT 0, source TEXT DEFAULT 'forge', identity TEXT DEFAULT '', binding_id TEXT DEFAULT '',
|
||||
binding_version INTEGER DEFAULT 0, review_payload TEXT DEFAULT '', workflow_definition_version INTEGER DEFAULT 0,
|
||||
workflow_definition_digest TEXT DEFAULT '', workflow_definition_yaml TEXT DEFAULT '',
|
||||
created_at TEXT DEFAULT (datetime('now')), updated_at TEXT DEFAULT (datetime('now')));
|
||||
ALTER TABLE tasks ADD COLUMN review_cursor INTEGER NOT NULL DEFAULT 0;
|
||||
CREATE TABLE transitions (id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER NOT NULL,
|
||||
at TEXT DEFAULT (datetime('now')), from_status TEXT NOT NULL, to_status TEXT NOT NULL, detail TEXT DEFAULT '');
|
||||
CREATE TABLE events (id INTEGER PRIMARY KEY AUTOINCREMENT, at TEXT NOT NULL, kind TEXT NOT NULL,
|
||||
task_id INTEGER DEFAULT 0, repo TEXT DEFAULT '', issue INTEGER DEFAULT 0, workflow TEXT DEFAULT '',
|
||||
stage TEXT DEFAULT '', attempt INTEGER DEFAULT 0, actor_id TEXT DEFAULT '', actor_kind TEXT DEFAULT '',
|
||||
principal_id TEXT DEFAULT '', detail TEXT DEFAULT '', data TEXT DEFAULT '{}');
|
||||
CREATE TABLE resources (kind TEXT PRIMARY KEY, value BLOB NOT NULL, version INTEGER NOT NULL, updated_at TEXT NOT NULL);
|
||||
CREATE TABLE resource_history (id INTEGER PRIMARY KEY AUTOINCREMENT, kind TEXT NOT NULL, value BLOB NOT NULL,
|
||||
version INTEGER NOT NULL, actor TEXT NOT NULL, source TEXT NOT NULL, request_id TEXT NOT NULL,
|
||||
expected_version INTEGER NOT NULL, current_version INTEGER NOT NULL, at TEXT NOT NULL);
|
||||
CREATE TABLE channel_status (id TEXT PRIMARY KEY, name TEXT DEFAULT '', state TEXT DEFAULT '', detail TEXT DEFAULT '',
|
||||
configured INTEGER NOT NULL DEFAULT 0, reload_supported INTEGER NOT NULL DEFAULT 0, observed_at TEXT NOT NULL);
|
||||
CREATE TABLE apply_status (process TEXT NOT NULL, kind TEXT NOT NULL, applied_version INTEGER DEFAULT 0,
|
||||
error TEXT DEFAULT '', reported_at TEXT NOT NULL, PRIMARY KEY (process, kind));
|
||||
CREATE TABLE config_snapshot (id INTEGER PRIMARY KEY CHECK (id = 1), schema TEXT DEFAULT '', document TEXT DEFAULT '',
|
||||
published_at TEXT NOT NULL);
|
||||
CREATE TABLE identities (id TEXT PRIMARY KEY, kind TEXT NOT NULL, display_name TEXT NOT NULL, lifecycle TEXT NOT NULL,
|
||||
version INTEGER NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
|
||||
CREATE TABLE identity_aliases (alias TEXT PRIMARY KEY COLLATE NOCASE, identity_id TEXT NOT NULL REFERENCES identities(id));
|
||||
CREATE TABLE identity_events (id INTEGER PRIMARY KEY AUTOINCREMENT, identity_id TEXT NOT NULL, event_type TEXT NOT NULL,
|
||||
from_lifecycle TEXT NOT NULL, to_lifecycle TEXT NOT NULL, display_name TEXT NOT NULL, actor_id TEXT NOT NULL,
|
||||
source TEXT NOT NULL, request_id TEXT NOT NULL UNIQUE, at TEXT NOT NULL);
|
||||
CREATE TABLE identity_subjects (issuer TEXT NOT NULL, subject TEXT NOT NULL,
|
||||
identity_id TEXT NOT NULL REFERENCES identities(id), bound_at TEXT NOT NULL, PRIMARY KEY (issuer, subject));
|
||||
|
||||
INSERT INTO tasks (id, owner, repo, issue_number, review_cursor) VALUES (1, 'o', 'r', 7, 3), (4, 'o', 'r', 1000000000000000, 0);
|
||||
INSERT INTO transitions (task_id, at, from_status, to_status) VALUES (1, '2026-01-01 00:00:00', 'queued', 'running');
|
||||
INSERT INTO events (id, at, kind) VALUES
|
||||
(1, '2026-01-01T00:00:00.000000100Z', 'a'),
|
||||
(2, '2026-01-01T00:00:01.000000000Z', 'b');
|
||||
INSERT INTO resources VALUES ('config', X'00ff10', 2, '2026-01-01T00:00:00Z');
|
||||
INSERT INTO resource_history (kind, value, version, actor, source, request_id, expected_version, current_version, at)
|
||||
VALUES ('config', X'00ff10', 2, 'sam', 'ui', 'req-1', 1, 1, '2026-01-01T00:00:00Z');
|
||||
INSERT INTO channel_status VALUES ('tg', 'Telegram', 'up', '', 1, 0, '2026-01-01T00:00:00Z');
|
||||
INSERT INTO apply_status VALUES ('daemon', 'config', 2, '', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO config_snapshot VALUES (1, 's', '{}', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO identities VALUES ('id-1', 'agent', 'Archie', 'active', 1, '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO identity_aliases VALUES ('archie', 'id-1');
|
||||
INSERT INTO identity_events (identity_id, event_type, from_lifecycle, to_lifecycle, display_name, actor_id, source, request_id, at)
|
||||
VALUES ('id-1', 'created', '', 'active', 'Archie', 'sam', 'boot', 'rq-1', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO identity_subjects VALUES ('https://issuer', 'sub-1', 'id-1', '2026-01-01T00:00:00Z');
|
||||
`
|
||||
|
||||
const edaDDL = `
|
||||
CREATE TABLE captures (id TEXT PRIMARY KEY NOT NULL, authenticated BOOLEAN DEFAULT FALSE NOT NULL,
|
||||
body TEXT DEFAULT '' NOT NULL, content_type TEXT DEFAULT '' NOT NULL, headers JSON DEFAULT NULL,
|
||||
received_at TEXT DEFAULT '' NOT NULL, remote_addr TEXT DEFAULT '' NOT NULL, source TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE mappings (id TEXT PRIMARY KEY NOT NULL, created_at TEXT DEFAULT '' NOT NULL, fields JSON DEFAULT NULL,
|
||||
name TEXT DEFAULT '' NOT NULL, source_hint TEXT DEFAULT '' NOT NULL, updated_at TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE bindings (id TEXT PRIMARY KEY NOT NULL, created_at TEXT DEFAULT '' NOT NULL, mapping TEXT DEFAULT '' NOT NULL,
|
||||
name TEXT DEFAULT '' NOT NULL, owner TEXT DEFAULT '' NOT NULL, repo TEXT DEFAULT '' NOT NULL,
|
||||
secret TEXT DEFAULT '' NOT NULL, source TEXT DEFAULT '' NOT NULL, status TEXT DEFAULT '' NOT NULL,
|
||||
updated_at TEXT DEFAULT '' NOT NULL, version NUMERIC DEFAULT 0 NOT NULL, workflow TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE binding_dispatches (id TEXT PRIMARY KEY NOT NULL, binding TEXT DEFAULT '' NOT NULL,
|
||||
binding_version NUMERIC DEFAULT 0 NOT NULL, capture TEXT DEFAULT '' NOT NULL, dispatched_at TEXT DEFAULT '' NOT NULL,
|
||||
task_id NUMERIC DEFAULT 0 NOT NULL);
|
||||
CREATE UNIQUE INDEX idx_binding_dispatch_once ON binding_dispatches (binding, capture);
|
||||
CREATE TABLE playbook_dispatches (id TEXT PRIMARY KEY NOT NULL, action_id TEXT DEFAULT '' NOT NULL,
|
||||
dispatched_at TEXT DEFAULT '' NOT NULL, event_id TEXT DEFAULT '' NOT NULL, playbook_id TEXT DEFAULT '' NOT NULL,
|
||||
playbook_version TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE tool_calls (id TEXT PRIMARY KEY NOT NULL, args JSON DEFAULT NULL, attempt NUMERIC DEFAULT 0 NOT NULL,
|
||||
called_at TEXT DEFAULT '' NOT NULL, duration_ms NUMERIC DEFAULT 0 NOT NULL, error TEXT DEFAULT '' NOT NULL,
|
||||
result JSON DEFAULT NULL, task_id NUMERIC DEFAULT 0 NOT NULL, tool TEXT DEFAULT '' NOT NULL);
|
||||
|
||||
INSERT INTO captures VALUES ('rcap1', 1, '{}', 'application/json', '{"x":["1"]}', '2026-01-01T00:00:00.000000000Z', '127.0.0.1', 'gh');
|
||||
INSERT INTO mappings VALUES ('rmap1', '2026-01-01', '[]', 'm', 'gh', '2026-01-01');
|
||||
INSERT INTO bindings VALUES ('rbind1', '2026-01-01', 'rmap1', 'b', 'o', 'r', 'plaintext-secret', 'gh', 'armed', '2026-01-01', 1, 'implement');
|
||||
INSERT INTO binding_dispatches VALUES ('rdisp1', 'rbind1', 1, 'rcap1', '2026-01-01', 4);
|
||||
INSERT INTO playbook_dispatches VALUES ('rpb1', 'act', '2026-01-01', 'ev', 'pb', 'v1');
|
||||
INSERT INTO tool_calls VALUES ('rtool1', '{}', 1, '2026-01-01', 12, '', '{}', 4, 'bash');
|
||||
`
|
||||
|
||||
const gatewayDDL = `
|
||||
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 INTEGER NOT NULL DEFAULT 0, last_active_at INTEGER NOT NULL DEFAULT 0);
|
||||
CREATE TABLE messages (id INTEGER PRIMARY KEY AUTOINCREMENT, message_id TEXT NOT NULL, session_id TEXT NOT NULL,
|
||||
source_id TEXT NOT NULL DEFAULT '', sender TEXT NOT NULL DEFAULT '', text TEXT NOT NULL DEFAULT '', ts INTEGER NOT NULL,
|
||||
UNIQUE(session_id, message_id));
|
||||
ALTER TABLE messages ADD COLUMN role TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE messages ADD COLUMN sender_id TEXT NOT NULL DEFAULT '';
|
||||
CREATE VIRTUAL TABLE messages_fts USING fts5(sender, text, content='messages', content_rowid='id');
|
||||
CREATE TRIGGER messages_ai AFTER INSERT ON messages BEGIN
|
||||
INSERT INTO messages_fts(rowid, sender, text) VALUES (new.id, new.sender, new.text);
|
||||
END;
|
||||
CREATE TABLE turns (turn_id TEXT PRIMARY KEY, session_id TEXT NOT NULL, source_id TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL, attempt INTEGER 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 INTEGER NOT NULL, updated_at INTEGER NOT NULL);
|
||||
|
||||
INSERT INTO sessions VALUES ('s1', 'telegram', 'bot', 'c1', '', 'Chat', '', '', 1000, 2000);
|
||||
INSERT INTO messages (message_id, session_id, sender, text, ts, role) VALUES ('m1', 's1', 'sam', 'hello there', 1000, 'user');
|
||||
INSERT INTO messages (message_id, session_id, sender, text, ts, role) VALUES ('m2', 's1', 'archie', 'hi', 1001, 'assistant');
|
||||
INSERT INTO turns VALUES ('t1', 's1', '', 'done', 1, '', 'm1', 'm2', '', 'hi', '[]', '', 1000, 1001);
|
||||
`
|
||||
|
||||
// fixture writes a legacy database built from ddl and returns its path. It
|
||||
// is checkpointed into a single file so a hash covers all of its state.
|
||||
func fixture(t *testing.T, name, ddl string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), name)
|
||||
db, err := sql.Open("sqlite", "file:"+path)
|
||||
if err != nil {
|
||||
t.Fatalf("open fixture: %v", err)
|
||||
}
|
||||
defer func() { _ = db.Close() }()
|
||||
if _, err := db.ExecContext(t.Context(), ddl); err != nil {
|
||||
t.Fatalf("apply fixture DDL: %v", err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func exec(t *testing.T, path, stmt string) {
|
||||
t.Helper()
|
||||
db, err := sql.Open("sqlite", "file:"+path)
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
defer func() { _ = db.Close() }()
|
||||
if _, err := db.ExecContext(t.Context(), stmt); err != nil {
|
||||
t.Fatalf("exec %q: %v", stmt, err)
|
||||
}
|
||||
}
|
||||
|
||||
func hashDir(t *testing.T, dir string) map[string][32]byte {
|
||||
t.Helper()
|
||||
sums := map[string][32]byte{}
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("read dir: %v", err)
|
||||
}
|
||||
for _, e := range entries {
|
||||
b, err := os.ReadFile(filepath.Join(dir, e.Name()))
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", e.Name(), err)
|
||||
}
|
||||
sums[e.Name()] = sha256.Sum256(b)
|
||||
}
|
||||
return sums
|
||||
}
|
||||
|
||||
func openSource(t *testing.T, path string) *Source {
|
||||
t.Helper()
|
||||
src, err := Open(t.Context(), path)
|
||||
if err != nil {
|
||||
t.Fatalf("Open(%s): %v", path, err)
|
||||
}
|
||||
t.Cleanup(func() { _ = src.Close() })
|
||||
return src
|
||||
}
|
||||
|
||||
// TestReadersDoNotMutateSources reads every table of all three stores and
|
||||
// asserts every file in each store's directory is byte-for-byte unchanged,
|
||||
// including the FTS5 index read.
|
||||
func TestReadersDoNotMutateSources(t *testing.T) {
|
||||
stores := []struct {
|
||||
name string
|
||||
ddl string
|
||||
tables []Table
|
||||
rows map[string]int
|
||||
}{
|
||||
{"archie.db", stateStoreDDL, StateStoreTables, map[string]int{"tasks": 2, "events": 2, "identity_subjects": 1}},
|
||||
{"archie.db-eda.sqlite", edaDDL, EDATables, map[string]int{"captures": 1, "bindings": 1, "tool_calls": 1}},
|
||||
{"archie.db-conversations.sqlite", gatewayDDL, GatewayTables, map[string]int{"messages": 2, "turns": 1}},
|
||||
}
|
||||
for _, s := range stores {
|
||||
t.Run(s.name, func(t *testing.T) {
|
||||
path := fixture(t, s.name, s.ddl)
|
||||
before := hashDir(t, filepath.Dir(path))
|
||||
src := openSource(t, path)
|
||||
for _, table := range s.tables {
|
||||
rows, err := src.Read(t.Context(), table)
|
||||
if err != nil {
|
||||
t.Fatalf("Read(%s): %v", table.Name, err)
|
||||
}
|
||||
if want, ok := s.rows[table.Name]; ok && len(rows.Rows) != want {
|
||||
t.Errorf("Read(%s) = %d rows, want %d", table.Name, len(rows.Rows), want)
|
||||
}
|
||||
}
|
||||
if s.name == "archie.db-conversations.sqlite" {
|
||||
if _, err := src.IndexedMessageIDs(t.Context()); err != nil {
|
||||
t.Fatalf("IndexedMessageIDs: %v", err)
|
||||
}
|
||||
}
|
||||
if err := src.Close(); err != nil {
|
||||
t.Fatalf("Close: %v", err)
|
||||
}
|
||||
if after := hashDir(t, filepath.Dir(path)); !mapsEqual(before, after) {
|
||||
t.Fatalf("reading changed the source directory:\nbefore %x\nafter %x", before, after)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func mapsEqual(a, b map[string][32]byte) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for k, v := range a {
|
||||
if b[k] != v {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// TestOpenRefusesWrites pins the read-only open: a write through the
|
||||
// source's connection is an error, not a silent mutation.
|
||||
func TestOpenRefusesWrites(t *testing.T) {
|
||||
src := openSource(t, fixture(t, "archie.db", stateStoreDDL))
|
||||
if _, err := src.db.ExecContext(t.Context(), "DELETE FROM tasks"); err == nil {
|
||||
t.Fatal("DELETE through the read-only source succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadCarriesAlteredColumnsAndBlobs(t *testing.T) {
|
||||
src := openSource(t, fixture(t, "archie.db", stateStoreDDL))
|
||||
tasks, err := src.Read(t.Context(), tableNamed(t, StateStoreTables, "tasks"))
|
||||
if err != nil {
|
||||
t.Fatalf("Read(tasks): %v", err)
|
||||
}
|
||||
if got := tasks.Value(0, "review_cursor"); got != int64(3) {
|
||||
t.Errorf("tasks[0].review_cursor = %#v, want 3 (an ALTER TABLE column)", got)
|
||||
}
|
||||
if got := tasks.Value(1, "issue_number"); got != int64(1_000_000_000_000_000) {
|
||||
t.Errorf("tasks[1].issue_number = %#v, want the chat seed", got)
|
||||
}
|
||||
res, err := src.Read(t.Context(), tableNamed(t, StateStoreTables, "resources"))
|
||||
if err != nil {
|
||||
t.Fatalf("Read(resources): %v", err)
|
||||
}
|
||||
if got, ok := res.Value(0, "value").([]byte); !ok || string(got) != "\x00\xff\x10" {
|
||||
t.Errorf("resources[0].value = %#v, want the raw bytes 00 ff 10", res.Value(0, "value"))
|
||||
}
|
||||
}
|
||||
|
||||
func tableNamed(t *testing.T, tables []Table, name string) Table {
|
||||
t.Helper()
|
||||
i := slices.IndexFunc(tables, func(tb Table) bool { return tb.Name == name })
|
||||
if i < 0 {
|
||||
t.Fatalf("no table %q", name)
|
||||
}
|
||||
return tables[i]
|
||||
}
|
||||
|
||||
func TestCompareKeys(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
source []string
|
||||
target []string
|
||||
missing, extra []string
|
||||
}{
|
||||
{name: "equal with the same gap", source: []string{"1", "2", "5"}, target: []string{"5", "1", "2"}},
|
||||
{name: "swallowed row", source: []string{"1", "2", "3"}, target: []string{"1", "3"}, missing: []string{"2"}},
|
||||
{name: "same count, different ids", source: []string{"1", "2"}, target: []string{"1", "9"}, missing: []string{"2"}, extra: []string{"9"}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := CompareKeys(tt.source, tt.target)
|
||||
if !slices.Equal(got.Missing, tt.missing) || !slices.Equal(got.Extra, tt.extra) {
|
||||
t.Errorf("CompareKeys = %+v, want missing %v extra %v", got, tt.missing, tt.extra)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompareOrder(t *testing.T) {
|
||||
if got := CompareOrder([]int64{1, 2, 3}, []int64{1, 2, 3}); got != nil {
|
||||
t.Errorf("CompareOrder(equal) = %+v, want nil", got)
|
||||
}
|
||||
got := CompareOrder([]int64{1, 2, 3}, []int64{1, 3, 2})
|
||||
if got == nil || got.Position != 1 || got.Source != 2 || got.Target != 3 {
|
||||
t.Errorf("CompareOrder(swapped) = %+v, want the first divergence at position 1 (2 vs 3)", got)
|
||||
}
|
||||
if got := CompareOrder([]int64{1, 2}, []int64{1}); got == nil || got.Position != 1 {
|
||||
t.Errorf("CompareOrder(short target) = %+v, want a divergence at position 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMicrosecondCollisions constructs D3.8's condition: two events whose
|
||||
// instants differ only below a microsecond, with the later instant carrying
|
||||
// the lower id, so Postgres's (at, id) order would reverse them.
|
||||
func TestMicrosecondCollisions(t *testing.T) {
|
||||
path := fixture(t, "archie.db", stateStoreDDL)
|
||||
exec(t, path, `INSERT INTO events (id, at, kind) VALUES
|
||||
(10, '2026-02-01T00:00:00.000000900Z', 'later instant, lower id'),
|
||||
(11, '2026-02-01T00:00:00.000000100Z', 'earlier instant, higher id'),
|
||||
(12, '2026-02-01T00:00:05.000000100Z', 'same microsecond, ids in order'),
|
||||
(13, '2026-02-01T00:00:05.000000900Z', 'same microsecond, ids in order')`)
|
||||
src := openSource(t, path)
|
||||
got, err := src.MicrosecondCollisions(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("MicrosecondCollisions: %v", err)
|
||||
}
|
||||
if len(got) != 1 || got[0].EarlierID != 11 || got[0].LaterID != 10 {
|
||||
t.Fatalf("MicrosecondCollisions = %+v, want exactly the pair (11 before 10)", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrphans(t *testing.T) {
|
||||
path := fixture(t, "archie.db", stateStoreDDL)
|
||||
src := openSource(t, path)
|
||||
for _, fk := range IdentityForeignKeys {
|
||||
got, err := src.Orphans(t.Context(), fk)
|
||||
if err != nil || len(got) != 0 {
|
||||
t.Fatalf("Orphans(%s) on a clean fixture = %v, %v; want none", fk.Table, got, err)
|
||||
}
|
||||
}
|
||||
_ = src.Close()
|
||||
exec(t, path, `INSERT INTO identity_aliases VALUES ('ghost', 'id-missing')`)
|
||||
src = openSource(t, path)
|
||||
got, err := src.Orphans(t.Context(), IdentityForeignKeys[0])
|
||||
if err != nil {
|
||||
t.Fatalf("Orphans: %v", err)
|
||||
}
|
||||
if len(got) != 1 || got[0].Key != "ghost" || got[0].Parent != "id-missing" {
|
||||
t.Fatalf("Orphans(identity_aliases) = %+v, want the ghost alias", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDuplicateAliases pins the case-folding hazard: SQLite's NOCASE folds
|
||||
// ASCII only, so two aliases differing in non-ASCII case coexist there and
|
||||
// collide under Postgres's Unicode lower().
|
||||
func TestDuplicateAliases(t *testing.T) {
|
||||
path := fixture(t, "archie.db", stateStoreDDL)
|
||||
exec(t, path, `INSERT INTO identity_aliases VALUES ('ÉMILE', 'id-1'), ('émile', 'id-1')`)
|
||||
src := openSource(t, path)
|
||||
got, err := src.DuplicateAliases(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("DuplicateAliases: %v", err)
|
||||
}
|
||||
if len(got) != 1 || got[0].Key != "émile" || len(got[0].Values) != 2 {
|
||||
t.Fatalf("DuplicateAliases = %+v, want one group of two for émile", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDuplicateArmedBindings(t *testing.T) {
|
||||
path := fixture(t, "archie.db-eda.sqlite", edaDDL)
|
||||
src := openSource(t, path)
|
||||
if got, err := src.DuplicateBindings(t.Context()); err != nil || len(got) != 0 {
|
||||
t.Fatalf("DuplicateBindings on a clean fixture = %v, %v; want none", got, err)
|
||||
}
|
||||
_ = src.Close()
|
||||
exec(t, path, `INSERT INTO bindings VALUES ('rbind2', '', 'rmap1', 'b2', 'o', 'r', '', 'gh', 'pending_approval', '', 1, 'implement')`)
|
||||
src = openSource(t, path)
|
||||
got, err := src.DuplicateBindings(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("DuplicateBindings: %v", err)
|
||||
}
|
||||
if len(got) != 1 || got[0].Key != "gh" || !slices.Equal(got[0].Values, []string{"rbind1", "rbind2"}) {
|
||||
t.Fatalf("DuplicateBindings = %+v, want source gh held by rbind1 and rbind2", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSequences(t *testing.T) {
|
||||
src := openSource(t, fixture(t, "archie.db", stateStoreDDL))
|
||||
got, err := src.Sequences(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("Sequences: %v", err)
|
||||
}
|
||||
want := map[string]Sequence{
|
||||
"tasks": {Table: "tasks", MaxID: 4, Next: 5},
|
||||
"transitions": {Table: "transitions", MaxID: 1, Next: 2},
|
||||
"events": {Table: "events", MaxID: 2, Next: 3},
|
||||
"resource_history": {Table: "resource_history", MaxID: 1, Next: 2},
|
||||
"identity_events": {Table: "identity_events", MaxID: 1, Next: 2},
|
||||
}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("Sequences = %+v, want %d tables", got, len(want))
|
||||
}
|
||||
for _, s := range got {
|
||||
if want[s.Table] != s {
|
||||
t.Errorf("Sequences[%s] = %+v, want %+v", s.Table, s, want[s.Table])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestSequenceNextSkipsDeletedTop pins that Next comes from AUTOINCREMENT's
|
||||
// high-water mark, not max(id): a deleted top row still reserves its id.
|
||||
func TestSequenceNextSkipsDeletedTop(t *testing.T) {
|
||||
path := fixture(t, "archie.db", stateStoreDDL)
|
||||
exec(t, path, `DELETE FROM tasks WHERE id = 4`)
|
||||
src := openSource(t, path)
|
||||
got, err := src.Sequences(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("Sequences: %v", err)
|
||||
}
|
||||
i := slices.IndexFunc(got, func(s Sequence) bool { return s.Table == "tasks" })
|
||||
if got[i].MaxID != 1 || got[i].Next != 5 {
|
||||
t.Fatalf("Sequences[tasks] = %+v, want max 1, next 5", got[i])
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompareBlobs(t *testing.T) {
|
||||
src := map[string][]byte{"config": {0, 0xff}, "routing": {1}}
|
||||
if got := CompareBlobs(src, map[string][]byte{"config": {0, 0xff}, "routing": {1}}); len(got) != 0 {
|
||||
t.Errorf("CompareBlobs(equal) = %v, want none", got)
|
||||
}
|
||||
got := CompareBlobs(src, map[string][]byte{"config": {0, 0xfe}})
|
||||
if !slices.Equal(got, []string{"config", "routing"}) {
|
||||
t.Errorf("CompareBlobs = %v, want config (changed) and routing (missing)", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIndexedMessageIDsFindsAStaleIndex(t *testing.T) {
|
||||
path := fixture(t, "archie.db-conversations.sqlite", gatewayDDL)
|
||||
exec(t, path, `DROP TRIGGER messages_ai; INSERT INTO messages (message_id, session_id, text, ts) VALUES ('m3', 's1', 'unindexed', 1002)`)
|
||||
src := openSource(t, path)
|
||||
indexed, err := src.IndexedMessageIDs(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("IndexedMessageIDs: %v", err)
|
||||
}
|
||||
messages, err := src.Read(t.Context(), tableNamed(t, GatewayTables, "messages"))
|
||||
if err != nil {
|
||||
t.Fatalf("Read(messages): %v", err)
|
||||
}
|
||||
got := CompareKeys(messages.Keys(), indexed)
|
||||
if !slices.Equal(got.Missing, []string{"3"}) {
|
||||
t.Fatalf("CompareKeys(messages, index) = %+v, want message 3 missing from the index", got)
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
package legacyread
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
// HasData reports whether the legacy file at path holds any row in tables. A
|
||||
// missing file, and a table the file never created, hold nothing. It is the
|
||||
// legacy half of the boot gate: a Postgres database without a completed import
|
||||
// must not serve while this is true for any source.
|
||||
func HasData(ctx context.Context, path string, tables []Table) (bool, error) {
|
||||
if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
|
||||
return false, nil
|
||||
}
|
||||
src, err := Open(ctx, path)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer func() { _ = src.Close() }()
|
||||
for _, t := range tables {
|
||||
var present bool
|
||||
if err := src.db.QueryRowContext(ctx,
|
||||
"SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?)", t.Name).Scan(&present); err != nil {
|
||||
return false, fmt.Errorf("legacyread: %s: %w", path, err)
|
||||
}
|
||||
if !present {
|
||||
continue
|
||||
}
|
||||
var rows bool
|
||||
if err := src.db.QueryRowContext(ctx, "SELECT EXISTS (SELECT 1 FROM "+t.Name+")").Scan(&rows); err != nil {
|
||||
return false, fmt.Errorf("legacyread: %s: %s: %w", path, t.Name, err)
|
||||
}
|
||||
if rows {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// SequenceOf returns the state of table's AUTOINCREMENT id column.
|
||||
func (s *Source) SequenceOf(ctx context.Context, table string) (Sequence, error) {
|
||||
seq := Sequence{Table: table}
|
||||
var high int64
|
||||
err := s.db.QueryRowContext(ctx, fmt.Sprintf(
|
||||
"SELECT COALESCE((SELECT max(id) FROM %[1]s), 0), COALESCE((SELECT seq FROM sqlite_sequence WHERE name = '%[1]s'), 0)",
|
||||
table)).Scan(&seq.MaxID, &high)
|
||||
if err != nil {
|
||||
return Sequence{}, fmt.Errorf("legacyread: sequence %s: %w", table, err)
|
||||
}
|
||||
seq.Next = max(seq.MaxID, high) + 1
|
||||
return seq, nil
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package legacyread
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHasData(t *testing.T) {
|
||||
emptyGateway := `CREATE TABLE sessions (session_id TEXT PRIMARY KEY);
|
||||
CREATE TABLE messages (id INTEGER PRIMARY KEY AUTOINCREMENT, message_id TEXT);`
|
||||
tests := []struct {
|
||||
name string
|
||||
path func(t *testing.T) string
|
||||
tables []Table
|
||||
want bool
|
||||
}{
|
||||
{"missing file", func(t *testing.T) string { return filepath.Join(t.TempDir(), "absent.sqlite") }, GatewayTables, false},
|
||||
{"tables without rows", func(t *testing.T) string { return fixture(t, "gw.sqlite", emptyGateway) }, GatewayTables, false},
|
||||
{"rows present", func(t *testing.T) string { return fixture(t, "gw.sqlite", gatewayDDL) }, GatewayTables, true},
|
||||
{"rows in the state store", func(t *testing.T) string { return fixture(t, "archie.db", stateStoreDDL) }, StateStoreTables, true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := HasData(t.Context(), tt.path(t), tt.tables)
|
||||
if err != nil {
|
||||
t.Fatalf("HasData: %v", err)
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Fatalf("HasData = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSequenceOfMessages(t *testing.T) {
|
||||
path := fixture(t, "gw.sqlite", gatewayDDL)
|
||||
exec(t, path, `DELETE FROM messages WHERE message_id = 'm2'`)
|
||||
src := openSource(t, path)
|
||||
got, err := src.SequenceOf(t.Context(), "messages")
|
||||
if err != nil {
|
||||
t.Fatalf("SequenceOf: %v", err)
|
||||
}
|
||||
if want := (Sequence{Table: "messages", MaxID: 1, Next: 3}); got != want {
|
||||
t.Fatalf("SequenceOf(messages) = %+v, want %+v", got, want)
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
package legacyread
|
||||
|
||||
func idTable(name string, columns ...string) Table {
|
||||
return Table{Name: name, Columns: columns, Key: []string{columns[0]}, OrderBy: columns[0]}
|
||||
}
|
||||
|
||||
// StateStoreTables are the twelve tables of the State Store's archie.db.
|
||||
var StateStoreTables = []Table{
|
||||
idTable("tasks", "id", "owner", "repo", "issue_number", "title", "body", "labels", "status",
|
||||
"workflow", "stage", "branch", "plan", "notes", "pr_number", "tokens_used", "iterations",
|
||||
"attempt", "park_reason", "watch_comment_id", "park_class", "remediation_rounds", "retry_count",
|
||||
"source", "identity", "binding_id", "binding_version", "review_payload",
|
||||
"workflow_definition_version", "workflow_definition_digest", "workflow_definition_yaml",
|
||||
"created_at", "updated_at", "review_cursor"),
|
||||
idTable("transitions", "id", "task_id", "at", "from_status", "to_status", "detail"),
|
||||
{
|
||||
Name: "events",
|
||||
Columns: []string{
|
||||
"id", "at", "kind", "task_id", "repo", "issue", "workflow", "stage", "attempt",
|
||||
"actor_id", "actor_kind", "principal_id", "detail", "data",
|
||||
},
|
||||
Key: []string{"id"},
|
||||
OrderBy: "at, id",
|
||||
},
|
||||
idTable("resources", "kind", "value", "version", "updated_at"),
|
||||
idTable("resource_history", "id", "kind", "value", "version", "actor", "source", "request_id",
|
||||
"expected_version", "current_version", "at"),
|
||||
idTable("channel_status", "id", "name", "state", "detail", "configured", "reload_supported", "observed_at"),
|
||||
{
|
||||
Name: "apply_status",
|
||||
Columns: []string{"process", "kind", "applied_version", "error", "reported_at"},
|
||||
Key: []string{"process", "kind"},
|
||||
OrderBy: "process, kind",
|
||||
},
|
||||
idTable("config_snapshot", "id", "schema", "document", "published_at"),
|
||||
idTable("identities", "id", "kind", "display_name", "lifecycle", "version", "created_at", "updated_at"),
|
||||
idTable("identity_aliases", "alias", "identity_id"),
|
||||
idTable("identity_events", "id", "identity_id", "event_type", "from_lifecycle", "to_lifecycle",
|
||||
"display_name", "actor_id", "source", "request_id", "at"),
|
||||
{
|
||||
Name: "identity_subjects",
|
||||
Columns: []string{"issuer", "subject", "identity_id", "bound_at"},
|
||||
Key: []string{"issuer", "subject"},
|
||||
OrderBy: "issuer, subject",
|
||||
},
|
||||
}
|
||||
|
||||
// EDATables are the six app collections of the PocketBase event store.
|
||||
// PocketBase's own tables (_collections, _params, _superusers, ...) are not
|
||||
// archie data and are not read.
|
||||
var EDATables = []Table{
|
||||
idTable("captures", "id", "authenticated", "body", "content_type", "headers", "received_at",
|
||||
"remote_addr", "source"),
|
||||
idTable("mappings", "id", "created_at", "fields", "name", "source_hint", "updated_at"),
|
||||
idTable("bindings", "id", "created_at", "mapping", "name", "owner", "repo", "secret", "source",
|
||||
"status", "updated_at", "version", "workflow"),
|
||||
idTable("binding_dispatches", "id", "binding", "binding_version", "capture", "dispatched_at", "task_id"),
|
||||
idTable("playbook_dispatches", "id", "action_id", "dispatched_at", "event_id", "playbook_id",
|
||||
"playbook_version"),
|
||||
idTable("tool_calls", "id", "args", "attempt", "called_at", "duration_ms", "error", "result",
|
||||
"task_id", "tool"),
|
||||
}
|
||||
|
||||
// GatewayTables are the Gateway conversation store's three data tables. Its
|
||||
// FTS5 index is read through IndexedMessageIDs.
|
||||
var GatewayTables = []Table{
|
||||
idTable("sessions", "session_id", "platform", "bot_user", "channel_id", "thread_id", "title",
|
||||
"parent_session_id", "branch_name", "created_at", "last_active_at"),
|
||||
idTable("messages", "id", "message_id", "session_id", "source_id", "sender", "text", "ts", "role", "sender_id"),
|
||||
idTable("turns", "turn_id", "session_id", "source_id", "status", "attempt", "owner_id",
|
||||
"input_message_id", "assistant_message_id", "partial_text", "response_text", "tool_calls",
|
||||
"error", "created_at", "updated_at"),
|
||||
}
|
||||
@@ -1,270 +0,0 @@
|
||||
package legacyread
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// KeyDiff is the difference between two key sets. A count comparison alone
|
||||
// passes on a swallowed row when ids have gaps; comparing the sets does not.
|
||||
type KeyDiff struct {
|
||||
Missing []string // in the source, not the target
|
||||
Extra []string // in the target, not the source
|
||||
}
|
||||
|
||||
// CompareKeys compares the source's key set with the target's.
|
||||
func CompareKeys(source, target []string) KeyDiff {
|
||||
var d KeyDiff
|
||||
src := setOf(source)
|
||||
tgt := setOf(target)
|
||||
for k := range src {
|
||||
if !tgt[k] {
|
||||
d.Missing = append(d.Missing, k)
|
||||
}
|
||||
}
|
||||
for k := range tgt {
|
||||
if !src[k] {
|
||||
d.Extra = append(d.Extra, k)
|
||||
}
|
||||
}
|
||||
slices.Sort(d.Missing)
|
||||
slices.Sort(d.Extra)
|
||||
return d
|
||||
}
|
||||
|
||||
func setOf(keys []string) map[string]bool {
|
||||
set := make(map[string]bool, len(keys))
|
||||
for _, k := range keys {
|
||||
set[k] = true
|
||||
}
|
||||
return set
|
||||
}
|
||||
|
||||
// Divergence is the first position at which two ordered id sequences differ.
|
||||
// A missing element on one side reads as 0.
|
||||
type Divergence struct {
|
||||
Position int
|
||||
Source, Target int64
|
||||
}
|
||||
|
||||
// CompareOrder compares two id sequences read in cursor order, returning nil
|
||||
// when they are identical.
|
||||
func CompareOrder(source, target []int64) *Divergence {
|
||||
for i := range max(len(source), len(target)) {
|
||||
var s, t int64
|
||||
if i < len(source) {
|
||||
s = source[i]
|
||||
}
|
||||
if i < len(target) {
|
||||
t = target[i]
|
||||
}
|
||||
if s != t || i >= len(source) || i >= len(target) {
|
||||
return &Divergence{Position: i, Source: s, Target: t}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Collision is two events whose instants differ only below a microsecond
|
||||
// while their ids run the other way. Postgres stores microseconds, so its
|
||||
// (at, id) order would put LaterID before EarlierID.
|
||||
type Collision struct {
|
||||
EarlierID, LaterID int64
|
||||
At time.Time // the shared microsecond
|
||||
}
|
||||
|
||||
// eventAtLayouts are the layouts events.at has been written in, newest first.
|
||||
var eventAtLayouts = []string{"2006-01-02T15:04:05.000000000Z", time.RFC3339Nano, time.RFC3339}
|
||||
|
||||
func parseEventAt(s string) (time.Time, error) {
|
||||
for _, layout := range eventAtLayouts {
|
||||
if t, err := time.Parse(layout, s); err == nil {
|
||||
return t.UTC(), nil
|
||||
}
|
||||
}
|
||||
return time.Time{}, fmt.Errorf("unrecognised timestamp %q", s)
|
||||
}
|
||||
|
||||
// MicrosecondCollisions returns every event pair that truncating events.at
|
||||
// to microseconds would reorder.
|
||||
func (s *Source) MicrosecondCollisions(ctx context.Context) ([]Collision, error) {
|
||||
rows, err := s.db.QueryContext(ctx, "SELECT id, at FROM events ORDER BY id")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("legacyread: events: %w", err)
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
type event struct {
|
||||
id int64
|
||||
at time.Time
|
||||
}
|
||||
byMicro := map[time.Time][]event{}
|
||||
for rows.Next() {
|
||||
var (
|
||||
id int64
|
||||
raw string
|
||||
)
|
||||
if err := rows.Scan(&id, &raw); err != nil {
|
||||
return nil, fmt.Errorf("legacyread: events: %w", err)
|
||||
}
|
||||
at, err := parseEventAt(raw)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("legacyread: event %d: %w", id, err)
|
||||
}
|
||||
micro := at.Truncate(time.Microsecond)
|
||||
byMicro[micro] = append(byMicro[micro], event{id, at})
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("legacyread: events: %w", err)
|
||||
}
|
||||
var out []Collision
|
||||
for micro, events := range byMicro {
|
||||
for i, a := range events {
|
||||
for _, b := range events[i+1:] {
|
||||
// Read in id order, so a.id < b.id.
|
||||
if b.at.Before(a.at) {
|
||||
out = append(out, Collision{EarlierID: b.id, LaterID: a.id, At: micro})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
slices.SortFunc(out, func(x, y Collision) int { return int(x.EarlierID - y.EarlierID) })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ForeignKey is a reference SQLite declared but never enforced (the State
|
||||
// Store never set PRAGMA foreign_keys) and Postgres will.
|
||||
type ForeignKey struct {
|
||||
Table, Column string
|
||||
KeyExpr string // SQL naming the child row in a report
|
||||
Parent, ParentC string
|
||||
}
|
||||
|
||||
// IdentityForeignKeys are the three identity references.
|
||||
var IdentityForeignKeys = []ForeignKey{
|
||||
{Table: "identity_aliases", Column: "identity_id", KeyExpr: "alias", Parent: "identities", ParentC: "id"},
|
||||
{Table: "identity_events", Column: "identity_id", KeyExpr: "CAST(id AS TEXT)", Parent: "identities", ParentC: "id"},
|
||||
{Table: "identity_subjects", Column: "identity_id", KeyExpr: "issuer || '/' || subject", Parent: "identities", ParentC: "id"},
|
||||
}
|
||||
|
||||
// Orphan is a child row whose parent does not exist.
|
||||
type Orphan struct {
|
||||
Key, Parent string
|
||||
}
|
||||
|
||||
// Orphans returns fk's child rows with no parent.
|
||||
func (s *Source) Orphans(ctx context.Context, fk ForeignKey) ([]Orphan, error) {
|
||||
query := fmt.Sprintf("SELECT %s, %s FROM %s WHERE %s NOT IN (SELECT %s FROM %s) ORDER BY 1",
|
||||
fk.KeyExpr, fk.Column, fk.Table, fk.Column, fk.ParentC, fk.Parent)
|
||||
rows, err := s.db.QueryContext(ctx, query)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("legacyread: orphans in %s: %w", fk.Table, err)
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
var out []Orphan
|
||||
for rows.Next() {
|
||||
var o Orphan
|
||||
if err := rows.Scan(&o.Key, &o.Parent); err != nil {
|
||||
return nil, fmt.Errorf("legacyread: orphans in %s: %w", fk.Table, err)
|
||||
}
|
||||
out = append(out, o)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Duplicate is a key the target will hold unique that more than one source
|
||||
// row shares.
|
||||
type Duplicate struct {
|
||||
Key string
|
||||
Values []string
|
||||
}
|
||||
|
||||
// DuplicateAliases groups identity aliases by Unicode lower case. SQLite's
|
||||
// NOCASE folds ASCII only, so aliases that differ in non-ASCII case coexist in
|
||||
// the source and collide on the target's lower(alias) index.
|
||||
func (s *Source) DuplicateAliases(ctx context.Context) ([]Duplicate, error) {
|
||||
aliases, err := s.strings(ctx, "SELECT alias FROM identity_aliases ORDER BY alias")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return duplicates(aliases, aliases, strings.ToLower), nil
|
||||
}
|
||||
|
||||
// DuplicateBindings groups bindings by source. One binding per source is
|
||||
// enforced in Go, not by the legacy schema, so a duplicate is possible and is
|
||||
// refused rather than repaired (D4.2).
|
||||
func (s *Source) DuplicateBindings(ctx context.Context) ([]Duplicate, error) {
|
||||
rows, err := s.Read(ctx, Table{Name: "bindings", Columns: []string{"id", "source"}, OrderBy: "id"})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids := make([]string, len(rows.Rows))
|
||||
sources := make([]string, len(rows.Rows))
|
||||
for i := range rows.Rows {
|
||||
ids[i] = fmt.Sprint(rows.Value(i, "id"))
|
||||
sources[i] = fmt.Sprint(rows.Value(i, "source"))
|
||||
}
|
||||
return duplicates(sources, ids, func(s string) string { return s }), nil
|
||||
}
|
||||
|
||||
// duplicates groups values by key(keys[i]) and returns the groups of two or
|
||||
// more, sorted by key.
|
||||
func duplicates(keys, values []string, key func(string) string) []Duplicate {
|
||||
groups := map[string][]string{}
|
||||
for i, k := range keys {
|
||||
groups[key(k)] = append(groups[key(k)], values[i])
|
||||
}
|
||||
var out []Duplicate
|
||||
for _, k := range slices.Sorted(maps.Keys(groups)) {
|
||||
if len(groups[k]) > 1 {
|
||||
out = append(out, Duplicate{Key: k, Values: groups[k]})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Sequence is an identity column's state: the highest id present and the id
|
||||
// SQLite would assign next. Next comes from AUTOINCREMENT's high-water mark,
|
||||
// so a deleted top row still reserves its id.
|
||||
type Sequence struct {
|
||||
Table string
|
||||
MaxID, Next int64
|
||||
}
|
||||
|
||||
// sequenceTables are the State Store tables with an AUTOINCREMENT id.
|
||||
var sequenceTables = []string{"tasks", "transitions", "events", "resource_history", "identity_events"}
|
||||
|
||||
// Sequences returns the state of every State Store identity column.
|
||||
func (s *Source) Sequences(ctx context.Context) ([]Sequence, error) {
|
||||
out := make([]Sequence, 0, len(sequenceTables))
|
||||
for _, table := range sequenceTables {
|
||||
seq, err := s.SequenceOf(ctx, table)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, seq)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// CompareBlobs returns, sorted, every key whose bytes differ between source
|
||||
// and target or that only one side holds.
|
||||
func CompareBlobs(source, target map[string][]byte) []string {
|
||||
var out []string
|
||||
for k, v := range source {
|
||||
if t, ok := target[k]; !ok || !bytes.Equal(v, t) {
|
||||
out = append(out, k)
|
||||
}
|
||||
}
|
||||
for k := range target {
|
||||
if _, ok := source[k]; !ok {
|
||||
out = append(out, k)
|
||||
}
|
||||
}
|
||||
slices.Sort(out)
|
||||
return out
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
||||
)
|
||||
|
||||
// ImportComplete reports whether the one-time legacy import committed and
|
||||
// verified against this migrated database. Serving over non-empty legacy
|
||||
// files is refused without it.
|
||||
func ImportComplete(ctx context.Context, pool *pgxpool.Pool) (bool, error) {
|
||||
done, err := postgresdb.New(pool).ImportCompleted(ctx)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("postgres: import completion: %w", err)
|
||||
}
|
||||
return done, nil
|
||||
}
|
||||
|
||||
// RecordFreshInstall writes the completion record for a database that starts
|
||||
// with no legacy data to import, so a legacy file that appears later cannot
|
||||
// block it from serving. It leaves an existing record untouched.
|
||||
func RecordFreshInstall(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
if err := postgresdb.New(pool).InsertFreshInstallCompletion(ctx); err != nil {
|
||||
return fmt.Errorf("postgres: fresh install completion: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestImportComplete(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
record bool
|
||||
want bool
|
||||
}{
|
||||
{name: "migrated database without a record", want: false},
|
||||
{name: "committed record", record: true, want: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
pool := openPool(t, pgtest.URL(t))
|
||||
if err := Migrate(t.Context(), pool, Migrations()); err != nil {
|
||||
t.Fatalf("Migrate: %v", err)
|
||||
}
|
||||
if tt.record {
|
||||
if _, err := pool.Exec(t.Context(),
|
||||
"INSERT INTO import_completion (id, sources, report) VALUES (1, 's', 'r')"); err != nil {
|
||||
t.Fatalf("seed record: %v", err)
|
||||
}
|
||||
}
|
||||
got, err := ImportComplete(t.Context(), pool)
|
||||
if err != nil {
|
||||
t.Fatalf("ImportComplete: %v", err)
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Fatalf("ImportComplete = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
-- The one-time SQLite import is removed, and with it the completion record
|
||||
-- that gated serving over unimported legacy files.
|
||||
|
||||
-- +goose Up
|
||||
|
||||
DROP TABLE import_completion;
|
||||
|
||||
-- +goose Down
|
||||
|
||||
CREATE TABLE import_completion (
|
||||
id bigint PRIMARY KEY CHECK (id = 1),
|
||||
completed_at timestamptz NOT NULL DEFAULT now(),
|
||||
sources text NOT NULL,
|
||||
report text NOT NULL
|
||||
);
|
||||
@@ -1,47 +0,0 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: import.sql
|
||||
|
||||
package postgresdb
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
const importCompleted = `-- name: ImportCompleted :one
|
||||
SELECT EXISTS (SELECT 1 FROM import_completion)
|
||||
`
|
||||
|
||||
func (q *Queries) ImportCompleted(ctx context.Context) (bool, error) {
|
||||
row := q.db.QueryRow(ctx, importCompleted)
|
||||
var exists bool
|
||||
err := row.Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
||||
const insertFreshInstallCompletion = `-- name: InsertFreshInstallCompletion :exec
|
||||
INSERT INTO import_completion (id, sources, report) VALUES (1, '', 'fresh install: no legacy data')
|
||||
ON CONFLICT (id) DO NOTHING
|
||||
`
|
||||
|
||||
func (q *Queries) InsertFreshInstallCompletion(ctx context.Context) error {
|
||||
_, err := q.db.Exec(ctx, insertFreshInstallCompletion)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertImportCompletion = `-- name: InsertImportCompletion :exec
|
||||
|
||||
INSERT INTO import_completion (id, sources, report) VALUES (1, $1, $2)
|
||||
`
|
||||
|
||||
type InsertImportCompletionParams struct {
|
||||
Sources string
|
||||
Report string
|
||||
}
|
||||
|
||||
// The one-time legacy import's completion record.
|
||||
func (q *Queries) InsertImportCompletion(ctx context.Context, arg InsertImportCompletionParams) error {
|
||||
_, err := q.db.Exec(ctx, insertImportCompletion, arg.Sources, arg.Report)
|
||||
return err
|
||||
}
|
||||
@@ -134,13 +134,6 @@ type IdentitySubject struct {
|
||||
BoundAt time.Time
|
||||
}
|
||||
|
||||
type ImportCompletion struct {
|
||||
ID int64
|
||||
CompletedAt time.Time
|
||||
Sources string
|
||||
Report string
|
||||
}
|
||||
|
||||
type Mapping struct {
|
||||
ID string
|
||||
Name string
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
-- The one-time legacy import's completion record.
|
||||
|
||||
-- name: InsertImportCompletion :exec
|
||||
INSERT INTO import_completion (id, sources, report) VALUES (1, $1, $2);
|
||||
|
||||
-- name: ImportCompleted :one
|
||||
SELECT EXISTS (SELECT 1 FROM import_completion);
|
||||
|
||||
-- name: InsertFreshInstallCompletion :exec
|
||||
INSERT INTO import_completion (id, sources, report) VALUES (1, '', 'fresh install: no legacy data')
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
Reference in new issue
Block a user