aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
18
akode-rs/state/BUILD.bazel
Normal file
18
akode-rs/state/BUILD.bazel
Normal file
@@ -0,0 +1,18 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "state",
|
||||
compile_data = glob([
|
||||
"goals_migrations/**",
|
||||
"logs_migrations/**",
|
||||
"memory_migrations/**",
|
||||
"migrations/**",
|
||||
"queue_migrations/**",
|
||||
"thread_history_migrations/**",
|
||||
]),
|
||||
crate_name = "akode_state",
|
||||
test_shard_counts = {
|
||||
# Windows runs database-heavy Rust tests serially within each shard.
|
||||
"state-unit-tests": 4,
|
||||
},
|
||||
)
|
||||
35
akode-rs/state/Cargo.toml
Normal file
35
akode-rs/state/Cargo.toml
Normal file
@@ -0,0 +1,35 @@
|
||||
[package]
|
||||
name = "akode-state"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
akode-file-system = { workspace = true }
|
||||
akode-history = { workspace = true }
|
||||
akode-protocol = { workspace = true }
|
||||
akode-utils-absolute-path = { workspace = true }
|
||||
file-id = { workspace = true }
|
||||
libsqlite3-sys = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
sqlx = { workspace = true }
|
||||
sqlx-macros = { workspace = true }
|
||||
sqlx-sqlite = { workspace = true }
|
||||
strum = { workspace = true, features = ["derive"] }
|
||||
tempfile = { workspace = true }
|
||||
tokio = { workspace = true, features = ["fs", "io-util", "macros", "rt-multi-thread", "sync", "time"] }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
uuid = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
akode-git-utils = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
scopeguard = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
18
akode-rs/state/goals_migrations/0001_thread_goals.sql
Normal file
18
akode-rs/state/goals_migrations/0001_thread_goals.sql
Normal file
@@ -0,0 +1,18 @@
|
||||
CREATE TABLE thread_goals (
|
||||
thread_id TEXT PRIMARY KEY NOT NULL,
|
||||
goal_id TEXT NOT NULL,
|
||||
objective TEXT NOT NULL,
|
||||
status TEXT NOT NULL CHECK(status IN (
|
||||
'active',
|
||||
'paused',
|
||||
'blocked',
|
||||
'usage_limited',
|
||||
'budget_limited',
|
||||
'complete'
|
||||
)),
|
||||
token_budget INTEGER,
|
||||
tokens_used INTEGER NOT NULL DEFAULT 0,
|
||||
time_used_seconds INTEGER NOT NULL DEFAULT 0,
|
||||
created_at_ms INTEGER NOT NULL,
|
||||
updated_at_ms INTEGER NOT NULL
|
||||
);
|
||||
@@ -0,0 +1,3 @@
|
||||
CREATE TABLE thread_goal_continuation_deferrals (
|
||||
thread_id TEXT PRIMARY KEY NOT NULL REFERENCES thread_goals(thread_id) ON DELETE CASCADE
|
||||
);
|
||||
21
akode-rs/state/logs_migrations/0001_logs.sql
Normal file
21
akode-rs/state/logs_migrations/0001_logs.sql
Normal file
@@ -0,0 +1,21 @@
|
||||
CREATE TABLE logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
ts INTEGER NOT NULL,
|
||||
ts_nanos INTEGER NOT NULL,
|
||||
level TEXT NOT NULL,
|
||||
target TEXT NOT NULL,
|
||||
message TEXT,
|
||||
module_path TEXT,
|
||||
file TEXT,
|
||||
line INTEGER,
|
||||
thread_id TEXT,
|
||||
process_uuid TEXT,
|
||||
estimated_bytes INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE INDEX idx_logs_ts ON logs(ts DESC, ts_nanos DESC, id DESC);
|
||||
CREATE INDEX idx_logs_thread_id ON logs(thread_id);
|
||||
CREATE INDEX idx_logs_process_uuid ON logs(process_uuid);
|
||||
CREATE INDEX idx_logs_thread_id_ts ON logs(thread_id, ts DESC, ts_nanos DESC, id DESC);
|
||||
CREATE INDEX idx_logs_process_uuid_threadless_ts ON logs(process_uuid, ts DESC, ts_nanos DESC, id DESC)
|
||||
WHERE thread_id IS NULL;
|
||||
@@ -0,0 +1,53 @@
|
||||
ALTER TABLE logs RENAME TO logs_old;
|
||||
|
||||
CREATE TABLE logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
ts INTEGER NOT NULL,
|
||||
ts_nanos INTEGER NOT NULL,
|
||||
level TEXT NOT NULL,
|
||||
target TEXT NOT NULL,
|
||||
feedback_log_body TEXT,
|
||||
module_path TEXT,
|
||||
file TEXT,
|
||||
line INTEGER,
|
||||
thread_id TEXT,
|
||||
process_uuid TEXT,
|
||||
estimated_bytes INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
INSERT INTO logs (
|
||||
id,
|
||||
ts,
|
||||
ts_nanos,
|
||||
level,
|
||||
target,
|
||||
feedback_log_body,
|
||||
module_path,
|
||||
file,
|
||||
line,
|
||||
thread_id,
|
||||
process_uuid,
|
||||
estimated_bytes
|
||||
)
|
||||
SELECT
|
||||
id,
|
||||
ts,
|
||||
ts_nanos,
|
||||
level,
|
||||
target,
|
||||
message,
|
||||
module_path,
|
||||
file,
|
||||
line,
|
||||
thread_id,
|
||||
process_uuid,
|
||||
estimated_bytes
|
||||
FROM logs_old;
|
||||
|
||||
DROP TABLE logs_old;
|
||||
|
||||
CREATE INDEX idx_logs_ts ON logs(ts DESC, ts_nanos DESC, id DESC);
|
||||
CREATE INDEX idx_logs_thread_id ON logs(thread_id);
|
||||
CREATE INDEX idx_logs_thread_id_ts ON logs(thread_id, ts DESC, ts_nanos DESC, id DESC);
|
||||
CREATE INDEX idx_logs_process_uuid_threadless_ts ON logs(process_uuid, ts DESC, ts_nanos DESC, id DESC)
|
||||
WHERE thread_id IS NULL;
|
||||
35
akode-rs/state/memory_migrations/0001_memories.sql
Normal file
35
akode-rs/state/memory_migrations/0001_memories.sql
Normal file
@@ -0,0 +1,35 @@
|
||||
CREATE TABLE stage1_outputs (
|
||||
thread_id TEXT PRIMARY KEY,
|
||||
source_updated_at INTEGER NOT NULL,
|
||||
raw_memory TEXT NOT NULL,
|
||||
rollout_summary TEXT NOT NULL,
|
||||
rollout_slug TEXT,
|
||||
generated_at INTEGER NOT NULL,
|
||||
usage_count INTEGER,
|
||||
last_usage INTEGER,
|
||||
selected_for_phase2 INTEGER NOT NULL DEFAULT 0,
|
||||
selected_for_phase2_source_updated_at INTEGER
|
||||
);
|
||||
|
||||
CREATE INDEX idx_stage1_outputs_source_updated_at
|
||||
ON stage1_outputs(source_updated_at DESC, thread_id DESC);
|
||||
|
||||
CREATE TABLE jobs (
|
||||
kind TEXT NOT NULL,
|
||||
job_key TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
worker_id TEXT,
|
||||
ownership_token TEXT,
|
||||
started_at INTEGER,
|
||||
finished_at INTEGER,
|
||||
lease_until INTEGER,
|
||||
retry_at INTEGER,
|
||||
retry_remaining INTEGER NOT NULL,
|
||||
last_error TEXT,
|
||||
input_watermark INTEGER,
|
||||
last_success_watermark INTEGER,
|
||||
PRIMARY KEY (kind, job_key)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_jobs_kind_status_retry_lease
|
||||
ON jobs(kind, status, retry_at, lease_until);
|
||||
@@ -0,0 +1,6 @@
|
||||
-- A successful consolidation is the readiness boundary for the version experiment.
|
||||
CREATE TABLE consolidation_progress (
|
||||
singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
|
||||
max_thread_count INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
INSERT INTO consolidation_progress (singleton) VALUES (1);
|
||||
25
akode-rs/state/migrations/0001_threads.sql
Normal file
25
akode-rs/state/migrations/0001_threads.sql
Normal file
@@ -0,0 +1,25 @@
|
||||
CREATE TABLE threads (
|
||||
id TEXT PRIMARY KEY,
|
||||
rollout_path TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
source TEXT NOT NULL,
|
||||
model_provider TEXT NOT NULL,
|
||||
cwd TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
sandbox_policy TEXT NOT NULL,
|
||||
approval_mode TEXT NOT NULL,
|
||||
tokens_used INTEGER NOT NULL DEFAULT 0,
|
||||
has_user_event INTEGER NOT NULL DEFAULT 0,
|
||||
archived INTEGER NOT NULL DEFAULT 0,
|
||||
archived_at INTEGER,
|
||||
git_sha TEXT,
|
||||
git_branch TEXT,
|
||||
git_origin_url TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX idx_threads_created_at ON threads(created_at DESC, id DESC);
|
||||
CREATE INDEX idx_threads_updated_at ON threads(updated_at DESC, id DESC);
|
||||
CREATE INDEX idx_threads_archived ON threads(archived);
|
||||
CREATE INDEX idx_threads_source ON threads(source);
|
||||
CREATE INDEX idx_threads_provider ON threads(model_provider);
|
||||
13
akode-rs/state/migrations/0002_logs.sql
Normal file
13
akode-rs/state/migrations/0002_logs.sql
Normal file
@@ -0,0 +1,13 @@
|
||||
CREATE TABLE logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
ts INTEGER NOT NULL,
|
||||
ts_nanos INTEGER NOT NULL,
|
||||
level TEXT NOT NULL,
|
||||
target TEXT NOT NULL,
|
||||
message TEXT,
|
||||
module_path TEXT,
|
||||
file TEXT,
|
||||
line INTEGER
|
||||
);
|
||||
|
||||
CREATE INDEX idx_logs_ts ON logs(ts DESC, ts_nanos DESC, id DESC);
|
||||
3
akode-rs/state/migrations/0003_logs_thread_id.sql
Normal file
3
akode-rs/state/migrations/0003_logs_thread_id.sql
Normal file
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE logs ADD COLUMN thread_id TEXT;
|
||||
|
||||
CREATE INDEX idx_logs_thread_id ON logs(thread_id);
|
||||
11
akode-rs/state/migrations/0004_thread_dynamic_tools.sql
Normal file
11
akode-rs/state/migrations/0004_thread_dynamic_tools.sql
Normal file
@@ -0,0 +1,11 @@
|
||||
CREATE TABLE thread_dynamic_tools (
|
||||
thread_id TEXT NOT NULL,
|
||||
position INTEGER NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT NOT NULL,
|
||||
input_schema TEXT NOT NULL,
|
||||
PRIMARY KEY(thread_id, position),
|
||||
FOREIGN KEY(thread_id) REFERENCES threads(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX idx_thread_dynamic_tools_thread ON thread_dynamic_tools(thread_id);
|
||||
1
akode-rs/state/migrations/0005_threads_cli_version.sql
Normal file
1
akode-rs/state/migrations/0005_threads_cli_version.sql
Normal file
@@ -0,0 +1 @@
|
||||
ALTER TABLE threads ADD COLUMN cli_version TEXT NOT NULL DEFAULT '';
|
||||
31
akode-rs/state/migrations/0006_memories.sql
Normal file
31
akode-rs/state/migrations/0006_memories.sql
Normal file
@@ -0,0 +1,31 @@
|
||||
CREATE TABLE stage1_outputs (
|
||||
thread_id TEXT PRIMARY KEY,
|
||||
source_updated_at INTEGER NOT NULL,
|
||||
raw_memory TEXT NOT NULL,
|
||||
rollout_summary TEXT NOT NULL,
|
||||
generated_at INTEGER NOT NULL,
|
||||
FOREIGN KEY(thread_id) REFERENCES threads(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX idx_stage1_outputs_source_updated_at
|
||||
ON stage1_outputs(source_updated_at DESC, thread_id DESC);
|
||||
|
||||
CREATE TABLE jobs (
|
||||
kind TEXT NOT NULL,
|
||||
job_key TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
worker_id TEXT,
|
||||
ownership_token TEXT,
|
||||
started_at INTEGER,
|
||||
finished_at INTEGER,
|
||||
lease_until INTEGER,
|
||||
retry_at INTEGER,
|
||||
retry_remaining INTEGER NOT NULL,
|
||||
last_error TEXT,
|
||||
input_watermark INTEGER,
|
||||
last_success_watermark INTEGER,
|
||||
PRIMARY KEY (kind, job_key)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_jobs_kind_status_retry_lease
|
||||
ON jobs(kind, status, retry_at, lease_until);
|
||||
@@ -0,0 +1,5 @@
|
||||
ALTER TABLE threads ADD COLUMN first_user_message TEXT NOT NULL DEFAULT '';
|
||||
|
||||
UPDATE threads
|
||||
SET first_user_message = title
|
||||
WHERE first_user_message = '' AND has_user_event = 1 AND title <> '';
|
||||
17
akode-rs/state/migrations/0008_backfill_state.sql
Normal file
17
akode-rs/state/migrations/0008_backfill_state.sql
Normal file
@@ -0,0 +1,17 @@
|
||||
CREATE TABLE backfill_state (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
status TEXT NOT NULL,
|
||||
last_watermark TEXT,
|
||||
last_success_at INTEGER,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
INSERT INTO backfill_state (id, status, last_watermark, last_success_at, updated_at)
|
||||
VALUES (
|
||||
1,
|
||||
'pending',
|
||||
NULL,
|
||||
NULL,
|
||||
CAST(strftime('%s', 'now') AS INTEGER)
|
||||
)
|
||||
ON CONFLICT(id) DO NOTHING;
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE stage1_outputs
|
||||
ADD COLUMN rollout_slug TEXT;
|
||||
3
akode-rs/state/migrations/0010_logs_process_id.sql
Normal file
3
akode-rs/state/migrations/0010_logs_process_id.sql
Normal file
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE logs ADD COLUMN process_uuid TEXT;
|
||||
|
||||
CREATE INDEX idx_logs_process_uuid ON logs(process_uuid);
|
||||
@@ -0,0 +1,4 @@
|
||||
CREATE INDEX idx_logs_thread_id_ts ON logs(thread_id, ts DESC, ts_nanos DESC, id DESC);
|
||||
|
||||
CREATE INDEX idx_logs_process_uuid_threadless_ts ON logs(process_uuid, ts DESC, ts_nanos DESC, id DESC)
|
||||
WHERE thread_id IS NULL;
|
||||
9
akode-rs/state/migrations/0012_logs_estimated_bytes.sql
Normal file
9
akode-rs/state/migrations/0012_logs_estimated_bytes.sql
Normal file
@@ -0,0 +1,9 @@
|
||||
ALTER TABLE logs ADD COLUMN estimated_bytes INTEGER NOT NULL DEFAULT 0;
|
||||
|
||||
UPDATE logs
|
||||
SET estimated_bytes =
|
||||
LENGTH(CAST(COALESCE(message, '') AS BLOB))
|
||||
+ LENGTH(CAST(level AS BLOB))
|
||||
+ LENGTH(CAST(target AS BLOB))
|
||||
+ LENGTH(CAST(COALESCE(module_path, '') AS BLOB))
|
||||
+ LENGTH(CAST(COALESCE(file, '') AS BLOB));
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE threads ADD COLUMN agent_nickname TEXT;
|
||||
ALTER TABLE threads ADD COLUMN agent_role TEXT;
|
||||
38
akode-rs/state/migrations/0014_agent_jobs.sql
Normal file
38
akode-rs/state/migrations/0014_agent_jobs.sql
Normal file
@@ -0,0 +1,38 @@
|
||||
CREATE TABLE agent_jobs (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
instruction TEXT NOT NULL,
|
||||
output_schema_json TEXT,
|
||||
input_headers_json TEXT NOT NULL,
|
||||
input_csv_path TEXT NOT NULL,
|
||||
output_csv_path TEXT NOT NULL,
|
||||
auto_export INTEGER NOT NULL DEFAULT 1,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
started_at INTEGER,
|
||||
completed_at INTEGER,
|
||||
last_error TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE agent_job_items (
|
||||
job_id TEXT NOT NULL,
|
||||
item_id TEXT NOT NULL,
|
||||
row_index INTEGER NOT NULL,
|
||||
source_id TEXT,
|
||||
row_json TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
assigned_thread_id TEXT,
|
||||
attempt_count INTEGER NOT NULL DEFAULT 0,
|
||||
result_json TEXT,
|
||||
last_error TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
completed_at INTEGER,
|
||||
reported_at INTEGER,
|
||||
PRIMARY KEY (job_id, item_id),
|
||||
FOREIGN KEY(job_id) REFERENCES agent_jobs(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX idx_agent_jobs_status ON agent_jobs(status, updated_at DESC);
|
||||
CREATE INDEX idx_agent_job_items_status ON agent_job_items(job_id, status, row_index ASC);
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE agent_jobs
|
||||
ADD COLUMN max_runtime_seconds INTEGER;
|
||||
2
akode-rs/state/migrations/0016_memory_usage.sql
Normal file
2
akode-rs/state/migrations/0016_memory_usage.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE stage1_outputs ADD COLUMN usage_count INTEGER;
|
||||
ALTER TABLE stage1_outputs ADD COLUMN last_usage INTEGER;
|
||||
2
akode-rs/state/migrations/0017_phase2_selection_flag.sql
Normal file
2
akode-rs/state/migrations/0017_phase2_selection_flag.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE stage1_outputs
|
||||
ADD COLUMN selected_for_phase2 INTEGER NOT NULL DEFAULT 0;
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE stage1_outputs
|
||||
ADD COLUMN selected_for_phase2_source_updated_at INTEGER;
|
||||
ALTER TABLE threads ADD COLUMN memory_mode TEXT NOT NULL DEFAULT 'enabled';
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE thread_dynamic_tools
|
||||
ADD COLUMN defer_loading INTEGER NOT NULL DEFAULT 0;
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE threads ADD COLUMN model TEXT;
|
||||
ALTER TABLE threads ADD COLUMN reasoning_effort TEXT;
|
||||
8
akode-rs/state/migrations/0021_thread_spawn_edges.sql
Normal file
8
akode-rs/state/migrations/0021_thread_spawn_edges.sql
Normal file
@@ -0,0 +1,8 @@
|
||||
CREATE TABLE thread_spawn_edges (
|
||||
parent_thread_id TEXT NOT NULL,
|
||||
child_thread_id TEXT NOT NULL PRIMARY KEY,
|
||||
status TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX idx_thread_spawn_edges_parent_status
|
||||
ON thread_spawn_edges(parent_thread_id, status);
|
||||
1
akode-rs/state/migrations/0022_threads_agent_path.sql
Normal file
1
akode-rs/state/migrations/0022_threads_agent_path.sql
Normal file
@@ -0,0 +1 @@
|
||||
ALTER TABLE threads ADD COLUMN agent_path TEXT;
|
||||
3
akode-rs/state/migrations/0023_drop_logs.sql
Normal file
3
akode-rs/state/migrations/0023_drop_logs.sql
Normal file
@@ -0,0 +1,3 @@
|
||||
PRAGMA auto_vacuum = INCREMENTAL;
|
||||
|
||||
DROP TABLE IF EXISTS logs;
|
||||
@@ -0,0 +1,10 @@
|
||||
CREATE TABLE remote_control_enrollments (
|
||||
websocket_url TEXT NOT NULL,
|
||||
account_id TEXT NOT NULL,
|
||||
app_server_client_name TEXT NOT NULL,
|
||||
server_id TEXT NOT NULL,
|
||||
environment_id TEXT NOT NULL,
|
||||
server_name TEXT NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (websocket_url, account_id, app_server_client_name)
|
||||
);
|
||||
112
akode-rs/state/migrations/0025_thread_timestamps_millis.sql
Normal file
112
akode-rs/state/migrations/0025_thread_timestamps_millis.sql
Normal file
@@ -0,0 +1,112 @@
|
||||
ALTER TABLE threads ADD COLUMN created_at_ms INTEGER;
|
||||
ALTER TABLE threads ADD COLUMN updated_at_ms INTEGER;
|
||||
|
||||
CREATE TEMP TABLE thread_timestamp_migration AS
|
||||
SELECT
|
||||
id,
|
||||
CASE
|
||||
WHEN created_at < 1577836800000 THEN created_at * 1000
|
||||
ELSE created_at
|
||||
END AS created_at_base_ms,
|
||||
CASE
|
||||
WHEN updated_at < 1577836800000 THEN updated_at * 1000
|
||||
ELSE updated_at
|
||||
END AS updated_at_base_ms
|
||||
FROM threads;
|
||||
|
||||
WITH RECURSIVE
|
||||
ordered_created AS (
|
||||
SELECT
|
||||
id,
|
||||
created_at_base_ms,
|
||||
ROW_NUMBER() OVER (ORDER BY created_at_base_ms, id) AS row_number
|
||||
FROM thread_timestamp_migration
|
||||
),
|
||||
assigned_created(row_number, id, created_at_ms) AS (
|
||||
SELECT row_number, id, created_at_base_ms
|
||||
FROM ordered_created
|
||||
WHERE row_number = 1
|
||||
UNION ALL
|
||||
SELECT
|
||||
ordered_created.row_number,
|
||||
ordered_created.id,
|
||||
MAX(ordered_created.created_at_base_ms, assigned_created.created_at_ms + 1)
|
||||
FROM ordered_created
|
||||
JOIN assigned_created ON ordered_created.row_number = assigned_created.row_number + 1
|
||||
)
|
||||
UPDATE threads
|
||||
SET created_at_ms = (
|
||||
SELECT created_at_ms
|
||||
FROM assigned_created
|
||||
WHERE assigned_created.id = threads.id
|
||||
);
|
||||
|
||||
WITH RECURSIVE
|
||||
ordered_updated AS (
|
||||
SELECT
|
||||
id,
|
||||
updated_at_base_ms,
|
||||
ROW_NUMBER() OVER (ORDER BY updated_at_base_ms, id) AS row_number
|
||||
FROM thread_timestamp_migration
|
||||
),
|
||||
assigned_updated(row_number, id, updated_at_ms) AS (
|
||||
SELECT row_number, id, updated_at_base_ms
|
||||
FROM ordered_updated
|
||||
WHERE row_number = 1
|
||||
UNION ALL
|
||||
SELECT
|
||||
ordered_updated.row_number,
|
||||
ordered_updated.id,
|
||||
MAX(ordered_updated.updated_at_base_ms, assigned_updated.updated_at_ms + 1)
|
||||
FROM ordered_updated
|
||||
JOIN assigned_updated ON ordered_updated.row_number = assigned_updated.row_number + 1
|
||||
)
|
||||
UPDATE threads
|
||||
SET updated_at_ms = (
|
||||
SELECT updated_at_ms
|
||||
FROM assigned_updated
|
||||
WHERE assigned_updated.id = threads.id
|
||||
);
|
||||
|
||||
DROP TABLE thread_timestamp_migration;
|
||||
|
||||
CREATE TRIGGER threads_created_at_ms_after_insert
|
||||
AFTER INSERT ON threads
|
||||
WHEN NEW.created_at_ms IS NULL
|
||||
BEGIN
|
||||
UPDATE threads
|
||||
SET created_at_ms = NEW.created_at * 1000
|
||||
WHERE id = NEW.id;
|
||||
END;
|
||||
|
||||
CREATE TRIGGER threads_updated_at_ms_after_insert
|
||||
AFTER INSERT ON threads
|
||||
WHEN NEW.updated_at_ms IS NULL
|
||||
BEGIN
|
||||
UPDATE threads
|
||||
SET updated_at_ms = NEW.updated_at * 1000
|
||||
WHERE id = NEW.id;
|
||||
END;
|
||||
|
||||
CREATE TRIGGER threads_created_at_ms_after_update
|
||||
AFTER UPDATE OF created_at ON threads
|
||||
WHEN NEW.created_at != OLD.created_at
|
||||
AND NEW.created_at_ms IS OLD.created_at_ms
|
||||
BEGIN
|
||||
UPDATE threads
|
||||
SET created_at_ms = NEW.created_at * 1000
|
||||
WHERE id = NEW.id;
|
||||
END;
|
||||
|
||||
CREATE TRIGGER threads_updated_at_ms_after_update
|
||||
AFTER UPDATE OF updated_at ON threads
|
||||
WHEN NEW.updated_at != OLD.updated_at
|
||||
AND NEW.updated_at_ms IS OLD.updated_at_ms
|
||||
BEGIN
|
||||
UPDATE threads
|
||||
SET updated_at_ms = NEW.updated_at * 1000
|
||||
WHERE id = NEW.id;
|
||||
END;
|
||||
|
||||
CREATE INDEX idx_threads_created_at_ms ON threads(created_at_ms DESC, id DESC);
|
||||
CREATE INDEX idx_threads_updated_at_ms ON threads(updated_at_ms DESC, id DESC);
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE thread_dynamic_tools
|
||||
ADD COLUMN namespace TEXT;
|
||||
@@ -0,0 +1,2 @@
|
||||
CREATE INDEX idx_threads_archived_cwd_created_at_ms ON threads(archived, cwd, created_at_ms DESC, id DESC);
|
||||
CREATE INDEX idx_threads_archived_cwd_updated_at_ms ON threads(archived, cwd, updated_at_ms DESC, id DESC);
|
||||
7
akode-rs/state/migrations/0028_device_key_bindings.sql
Normal file
7
akode-rs/state/migrations/0028_device_key_bindings.sql
Normal file
@@ -0,0 +1,7 @@
|
||||
CREATE TABLE device_key_bindings (
|
||||
key_id TEXT PRIMARY KEY NOT NULL,
|
||||
account_user_id TEXT NOT NULL,
|
||||
client_id TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
11
akode-rs/state/migrations/0029_thread_goals.sql
Normal file
11
akode-rs/state/migrations/0029_thread_goals.sql
Normal file
@@ -0,0 +1,11 @@
|
||||
CREATE TABLE thread_goals (
|
||||
thread_id TEXT PRIMARY KEY NOT NULL REFERENCES threads(id) ON DELETE CASCADE,
|
||||
goal_id TEXT NOT NULL,
|
||||
objective TEXT NOT NULL,
|
||||
status TEXT NOT NULL CHECK(status IN ('active', 'paused', 'budget_limited', 'complete')),
|
||||
token_budget INTEGER,
|
||||
tokens_used INTEGER NOT NULL DEFAULT 0,
|
||||
time_used_seconds INTEGER NOT NULL DEFAULT 0,
|
||||
created_at_ms INTEGER NOT NULL,
|
||||
updated_at_ms INTEGER NOT NULL
|
||||
);
|
||||
1
akode-rs/state/migrations/0030_threads_thread_source.sql
Normal file
1
akode-rs/state/migrations/0030_threads_thread_source.sql
Normal file
@@ -0,0 +1 @@
|
||||
ALTER TABLE threads ADD COLUMN thread_source TEXT;
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE IF EXISTS device_key_bindings;
|
||||
19
akode-rs/state/migrations/0032_threads_preview.sql
Normal file
19
akode-rs/state/migrations/0032_threads_preview.sql
Normal file
@@ -0,0 +1,19 @@
|
||||
ALTER TABLE threads ADD COLUMN preview TEXT NOT NULL DEFAULT '';
|
||||
|
||||
UPDATE threads
|
||||
SET preview = first_user_message
|
||||
WHERE preview = '' AND first_user_message <> '';
|
||||
|
||||
UPDATE threads
|
||||
SET preview = (
|
||||
SELECT thread_goals.objective
|
||||
FROM thread_goals
|
||||
WHERE thread_goals.thread_id = threads.id
|
||||
)
|
||||
WHERE preview = ''
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM thread_goals
|
||||
WHERE thread_goals.thread_id = threads.id
|
||||
AND thread_goals.objective <> ''
|
||||
);
|
||||
@@ -0,0 +1,48 @@
|
||||
PRAGMA foreign_keys=OFF;
|
||||
|
||||
CREATE TABLE thread_goals_new (
|
||||
thread_id TEXT PRIMARY KEY NOT NULL REFERENCES threads(id) ON DELETE CASCADE,
|
||||
goal_id TEXT NOT NULL,
|
||||
objective TEXT NOT NULL,
|
||||
status TEXT NOT NULL CHECK(status IN (
|
||||
'active',
|
||||
'paused',
|
||||
'blocked',
|
||||
'usage_limited',
|
||||
'budget_limited',
|
||||
'complete'
|
||||
)),
|
||||
token_budget INTEGER,
|
||||
tokens_used INTEGER NOT NULL DEFAULT 0,
|
||||
time_used_seconds INTEGER NOT NULL DEFAULT 0,
|
||||
created_at_ms INTEGER NOT NULL,
|
||||
updated_at_ms INTEGER NOT NULL
|
||||
);
|
||||
|
||||
INSERT INTO thread_goals_new (
|
||||
thread_id,
|
||||
goal_id,
|
||||
objective,
|
||||
status,
|
||||
token_budget,
|
||||
tokens_used,
|
||||
time_used_seconds,
|
||||
created_at_ms,
|
||||
updated_at_ms
|
||||
)
|
||||
SELECT
|
||||
thread_id,
|
||||
goal_id,
|
||||
objective,
|
||||
status,
|
||||
token_budget,
|
||||
tokens_used,
|
||||
time_used_seconds,
|
||||
created_at_ms,
|
||||
updated_at_ms
|
||||
FROM thread_goals;
|
||||
|
||||
DROP TABLE thread_goals;
|
||||
ALTER TABLE thread_goals_new RENAME TO thread_goals;
|
||||
|
||||
PRAGMA foreign_keys=ON;
|
||||
1
akode-rs/state/migrations/0034_drop_thread_goals.sql
Normal file
1
akode-rs/state/migrations/0034_drop_thread_goals.sql
Normal file
@@ -0,0 +1 @@
|
||||
DROP TABLE IF EXISTS thread_goals;
|
||||
2
akode-rs/state/migrations/0035_drop_memory_tables.sql
Normal file
2
akode-rs/state/migrations/0035_drop_memory_tables.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
DROP TABLE IF EXISTS jobs;
|
||||
DROP TABLE IF EXISTS stage1_outputs;
|
||||
@@ -0,0 +1,7 @@
|
||||
CREATE INDEX idx_threads_visible_created_at_ms
|
||||
ON threads(archived, created_at_ms DESC)
|
||||
WHERE preview <> '';
|
||||
|
||||
CREATE INDEX idx_threads_visible_updated_at_ms
|
||||
ON threads(archived, updated_at_ms DESC)
|
||||
WHERE preview <> '';
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE remote_control_enrollments
|
||||
ADD COLUMN remote_control_enabled INTEGER;
|
||||
@@ -0,0 +1,6 @@
|
||||
CREATE TABLE external_agent_config_imports (
|
||||
import_id TEXT PRIMARY KEY,
|
||||
completed_at_ms INTEGER NOT NULL,
|
||||
successes TEXT NOT NULL,
|
||||
failures TEXT NOT NULL
|
||||
);
|
||||
28
akode-rs/state/migrations/0039_threads_recency_at.sql
Normal file
28
akode-rs/state/migrations/0039_threads_recency_at.sql
Normal file
@@ -0,0 +1,28 @@
|
||||
ALTER TABLE threads ADD COLUMN recency_at INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE threads ADD COLUMN recency_at_ms INTEGER NOT NULL DEFAULT 0;
|
||||
|
||||
UPDATE threads
|
||||
SET recency_at = updated_at,
|
||||
recency_at_ms = updated_at_ms;
|
||||
|
||||
-- Older binaries can open databases migrated by newer binaries. Seed recency
|
||||
-- when one of those binaries inserts a thread without the new columns.
|
||||
CREATE TRIGGER threads_recency_at_after_insert
|
||||
AFTER INSERT ON threads
|
||||
WHEN NEW.recency_at_ms = 0
|
||||
BEGIN
|
||||
UPDATE threads
|
||||
SET recency_at = NEW.updated_at,
|
||||
recency_at_ms = COALESCE(NEW.updated_at_ms, NEW.updated_at * 1000)
|
||||
WHERE id = NEW.id;
|
||||
END;
|
||||
|
||||
CREATE INDEX idx_threads_recency_at_ms
|
||||
ON threads(recency_at_ms DESC, id DESC);
|
||||
|
||||
CREATE INDEX idx_threads_archived_cwd_recency_at_ms
|
||||
ON threads(archived, cwd, recency_at_ms DESC, id DESC);
|
||||
|
||||
CREATE INDEX idx_threads_visible_recency_at_ms
|
||||
ON threads(archived, recency_at_ms DESC, id DESC)
|
||||
WHERE preview <> '';
|
||||
1
akode-rs/state/migrations/0040_threads_history_mode.sql
Normal file
1
akode-rs/state/migrations/0040_threads_history_mode.sql
Normal file
@@ -0,0 +1 @@
|
||||
ALTER TABLE threads ADD COLUMN history_mode TEXT NOT NULL DEFAULT 'legacy';
|
||||
1
akode-rs/state/migrations/0041_threads_name.sql
Normal file
1
akode-rs/state/migrations/0041_threads_name.sql
Normal file
@@ -0,0 +1 @@
|
||||
ALTER TABLE threads ADD COLUMN name TEXT;
|
||||
2
akode-rs/state/migrations/0042_drop_agent_jobs.sql
Normal file
2
akode-rs/state/migrations/0042_drop_agent_jobs.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
DROP TABLE IF EXISTS agent_job_items;
|
||||
DROP TABLE IF EXISTS agent_jobs;
|
||||
5
akode-rs/state/migrations/0043_threads_is_pinned.sql
Normal file
5
akode-rs/state/migrations/0043_threads_is_pinned.sql
Normal file
@@ -0,0 +1,5 @@
|
||||
ALTER TABLE threads ADD COLUMN is_pinned INTEGER NOT NULL DEFAULT 0;
|
||||
|
||||
CREATE INDEX idx_threads_pinned_recency_at_ms
|
||||
ON threads(archived, recency_at_ms DESC, id DESC)
|
||||
WHERE is_pinned = 1 AND preview <> '';
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE external_agent_config_imports
|
||||
ADD COLUMN provider_id TEXT;
|
||||
14
akode-rs/state/migrations/0045_threads_section.sql
Normal file
14
akode-rs/state/migrations/0045_threads_section.sql
Normal file
@@ -0,0 +1,14 @@
|
||||
CREATE TABLE thread_sections (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL
|
||||
);
|
||||
|
||||
INSERT INTO thread_sections (id, name)
|
||||
VALUES ('01984de2-8f74-7c91-a3b2-5c5e937cf318', 'Pinned');
|
||||
|
||||
ALTER TABLE threads ADD COLUMN thread_section_id TEXT
|
||||
REFERENCES thread_sections(id) ON DELETE SET NULL;
|
||||
|
||||
CREATE INDEX idx_threads_section_recency_at_ms
|
||||
ON threads(archived, thread_section_id, recency_at_ms DESC, id DESC)
|
||||
WHERE thread_section_id IS NOT NULL AND preview <> '';
|
||||
20
akode-rs/state/migrations/0046_threads_section_order.sql
Normal file
20
akode-rs/state/migrations/0046_threads_section_order.sql
Normal file
@@ -0,0 +1,20 @@
|
||||
ALTER TABLE threads ADD COLUMN section_position INTEGER;
|
||||
ALTER TABLE threads ADD COLUMN section_entered_at_ms INTEGER;
|
||||
|
||||
UPDATE threads
|
||||
SET section_position = ranked.position,
|
||||
section_entered_at_ms = threads.recency_at_ms
|
||||
FROM (
|
||||
SELECT id,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY thread_section_id
|
||||
ORDER BY recency_at_ms DESC, id DESC
|
||||
) * 1000000 AS position
|
||||
FROM threads
|
||||
WHERE thread_section_id IS NOT NULL
|
||||
) AS ranked
|
||||
WHERE threads.id = ranked.id;
|
||||
|
||||
CREATE INDEX idx_threads_section_position
|
||||
ON threads(archived, thread_section_id, section_position ASC, id ASC)
|
||||
WHERE thread_section_id IS NOT NULL AND preview <> '';
|
||||
16
akode-rs/state/migrations/0047_rollout_migration_state.sql
Normal file
16
akode-rs/state/migrations/0047_rollout_migration_state.sql
Normal file
@@ -0,0 +1,16 @@
|
||||
CREATE TABLE rollout_migration_state (
|
||||
migration_id TEXT PRIMARY KEY,
|
||||
last_checked_thread_created_at INTEGER,
|
||||
last_checked_thread_id TEXT,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE rollout_migration_skipped_rollouts (
|
||||
migration_id TEXT NOT NULL,
|
||||
rollout_path TEXT NOT NULL,
|
||||
rollout_size_bytes INTEGER NOT NULL,
|
||||
rollout_modified_at_ns INTEGER NOT NULL,
|
||||
skip_reason TEXT NOT NULL,
|
||||
skipped_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (migration_id, rollout_path)
|
||||
);
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE thread_sections ADD COLUMN appearance TEXT;
|
||||
30
akode-rs/state/migrations/0049_projects.sql
Normal file
30
akode-rs/state/migrations/0049_projects.sql
Normal file
@@ -0,0 +1,30 @@
|
||||
CREATE TABLE projects (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
metadata TEXT NOT NULL DEFAULT '{}',
|
||||
position INTEGER NOT NULL,
|
||||
created_at_ms INTEGER NOT NULL,
|
||||
updated_at_ms INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE project_roots (
|
||||
project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
||||
position INTEGER NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
PRIMARY KEY (project_id, position)
|
||||
);
|
||||
|
||||
CREATE TABLE project_idempotency_keys (
|
||||
key TEXT PRIMARY KEY,
|
||||
project_id TEXT NOT NULL,
|
||||
created_at_ms INTEGER NOT NULL
|
||||
);
|
||||
|
||||
ALTER TABLE threads ADD COLUMN project_id TEXT
|
||||
REFERENCES projects(id) ON DELETE SET NULL;
|
||||
|
||||
CREATE INDEX idx_projects_position
|
||||
ON projects(position ASC, id ASC);
|
||||
CREATE INDEX idx_threads_project_id
|
||||
ON threads(project_id, archived, created_at_ms DESC, id DESC)
|
||||
WHERE project_id IS NOT NULL;
|
||||
@@ -0,0 +1,10 @@
|
||||
DROP INDEX idx_threads_section_recency_at_ms;
|
||||
DROP INDEX idx_threads_section_position;
|
||||
|
||||
CREATE INDEX idx_threads_section_recency_at_ms
|
||||
ON threads(archived, thread_section_id, recency_at_ms DESC, id DESC)
|
||||
WHERE thread_section_id IS NOT NULL;
|
||||
|
||||
CREATE INDEX idx_threads_section_position
|
||||
ON threads(archived, thread_section_id, section_position ASC, id ASC)
|
||||
WHERE thread_section_id IS NOT NULL;
|
||||
12
akode-rs/state/migrations/0051_thread_artifacts.sql
Normal file
12
akode-rs/state/migrations/0051_thread_artifacts.sql
Normal file
@@ -0,0 +1,12 @@
|
||||
CREATE TABLE thread_artifacts (
|
||||
id TEXT PRIMARY KEY,
|
||||
thread_id TEXT NOT NULL REFERENCES threads(id) ON DELETE CASCADE,
|
||||
artifact_type TEXT NOT NULL,
|
||||
identity_key TEXT NOT NULL,
|
||||
payload TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
UNIQUE (thread_id, artifact_type, identity_key)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_thread_artifacts_thread_created_id
|
||||
ON thread_artifacts(thread_id, created_at, id);
|
||||
3
akode-rs/state/migrations/0052_projects_recency.sql
Normal file
3
akode-rs/state/migrations/0052_projects_recency.sql
Normal file
@@ -0,0 +1,3 @@
|
||||
CREATE INDEX idx_threads_project_recency
|
||||
ON threads(project_id, recency_at_ms DESC)
|
||||
WHERE archived = 0 AND project_id IS NOT NULL;
|
||||
1
akode-rs/state/migrations/0053_threads_originator.sql
Normal file
1
akode-rs/state/migrations/0053_threads_originator.sql
Normal file
@@ -0,0 +1 @@
|
||||
ALTER TABLE threads ADD COLUMN originator TEXT;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE threads ADD COLUMN daybreak_enabled BOOLEAN;
|
||||
6
akode-rs/state/migrations/0055_thread_attachments.sql
Normal file
6
akode-rs/state/migrations/0055_thread_attachments.sql
Normal file
@@ -0,0 +1,6 @@
|
||||
ALTER TABLE thread_artifacts RENAME TO thread_attachments;
|
||||
ALTER TABLE thread_attachments RENAME COLUMN artifact_type TO attachment_type;
|
||||
|
||||
DROP INDEX idx_thread_artifacts_thread_created_id;
|
||||
CREATE INDEX idx_thread_attachments_thread_created_id
|
||||
ON thread_attachments(thread_id, created_at, id);
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE threads ADD COLUMN creator_user_id TEXT;
|
||||
ALTER TABLE threads ADD COLUMN creator_account_id TEXT;
|
||||
@@ -0,0 +1,21 @@
|
||||
-- Guardian prompts are synthetic review context, not user-authored messages.
|
||||
-- Keep the SQLite projection small; rollout JSONL remains canonical.
|
||||
-- Legacy automatic titles were empty or copied first_user_message; preserve a
|
||||
-- different non-empty title because it may have been set explicitly.
|
||||
UPDATE threads
|
||||
SET title = CASE
|
||||
WHEN trim(title) = '' OR trim(title) = trim(first_user_message)
|
||||
THEN 'Guardian review'
|
||||
ELSE title
|
||||
END,
|
||||
name = CASE
|
||||
WHEN trim(COALESCE(name, '')) != ''
|
||||
THEN name
|
||||
WHEN trim(title) != ''
|
||||
AND trim(title) != trim(COALESCE(first_user_message, ''))
|
||||
THEN title
|
||||
ELSE 'Guardian review'
|
||||
END,
|
||||
preview = 'Approval review',
|
||||
first_user_message = ''
|
||||
WHERE source = '{"subagent":{"other":"guardian"}}';
|
||||
@@ -0,0 +1,12 @@
|
||||
-- Archived listings include empty previews and cannot use the visible-only indexes.
|
||||
CREATE INDEX idx_threads_archive_created_at_ms
|
||||
ON threads(archived, created_at_ms DESC, id DESC)
|
||||
WHERE archived = 1;
|
||||
|
||||
CREATE INDEX idx_threads_archive_updated_at_ms
|
||||
ON threads(archived, updated_at_ms DESC, id DESC)
|
||||
WHERE archived = 1;
|
||||
|
||||
CREATE INDEX idx_threads_archive_recency_at_ms
|
||||
ON threads(archived, recency_at_ms DESC, id DESC)
|
||||
WHERE archived = 1;
|
||||
@@ -0,0 +1,2 @@
|
||||
CREATE INDEX idx_thread_attachments_identity_thread
|
||||
ON thread_attachments(attachment_type, identity_key, thread_id);
|
||||
@@ -0,0 +1,5 @@
|
||||
CREATE TABLE guardian_review_feedback (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
thread_id TEXT NOT NULL REFERENCES threads(id) ON DELETE CASCADE,
|
||||
record BLOB NOT NULL
|
||||
);
|
||||
8
akode-rs/state/migrations/0061_thread_read_state.sql
Normal file
8
akode-rs/state/migrations/0061_thread_read_state.sql
Normal file
@@ -0,0 +1,8 @@
|
||||
-- Independent of rebuildable thread metadata: only actual thread deletion removes receipts.
|
||||
-- NULL means read; the empty string means manually unread from the start, even when empty.
|
||||
CREATE TABLE thread_read_receipts (
|
||||
thread_id TEXT PRIMARY KEY NOT NULL,
|
||||
first_unread_turn TEXT,
|
||||
revision TEXT NOT NULL,
|
||||
last_published_turn TEXT
|
||||
);
|
||||
@@ -0,0 +1,4 @@
|
||||
ALTER TABLE threads ADD COLUMN attached_thread_parent_id TEXT;
|
||||
|
||||
CREATE INDEX idx_threads_attached_parent ON threads(attached_thread_parent_id)
|
||||
WHERE attached_thread_parent_id IS NOT NULL;
|
||||
11
akode-rs/state/queue_migrations/0001_queued_items.sql
Normal file
11
akode-rs/state/queue_migrations/0001_queued_items.sql
Normal file
@@ -0,0 +1,11 @@
|
||||
CREATE TABLE queued_items (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
thread_id TEXT NOT NULL,
|
||||
payload_json TEXT NOT NULL,
|
||||
queue_order INTEGER NOT NULL,
|
||||
created_at_ms INTEGER NOT NULL,
|
||||
updated_at_ms INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX queued_items_thread_order_idx
|
||||
ON queued_items(thread_id, queue_order);
|
||||
@@ -0,0 +1,34 @@
|
||||
CREATE TABLE queued_thread_revisions (
|
||||
revision INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
thread_id TEXT NOT NULL UNIQUE
|
||||
);
|
||||
|
||||
INSERT INTO queued_thread_revisions (thread_id)
|
||||
SELECT DISTINCT thread_id FROM queued_items ORDER BY thread_id;
|
||||
|
||||
CREATE TRIGGER queued_items_revision_after_insert
|
||||
AFTER INSERT ON queued_items
|
||||
BEGIN
|
||||
INSERT INTO queued_thread_revisions (thread_id)
|
||||
VALUES (NEW.thread_id)
|
||||
ON CONFLICT(thread_id) DO UPDATE
|
||||
SET revision = (SELECT COALESCE(MAX(revision), 0) + 1 FROM queued_thread_revisions);
|
||||
END;
|
||||
|
||||
CREATE TRIGGER queued_items_revision_after_update
|
||||
AFTER UPDATE ON queued_items
|
||||
BEGIN
|
||||
INSERT INTO queued_thread_revisions (thread_id)
|
||||
VALUES (NEW.thread_id)
|
||||
ON CONFLICT(thread_id) DO UPDATE
|
||||
SET revision = (SELECT COALESCE(MAX(revision), 0) + 1 FROM queued_thread_revisions);
|
||||
END;
|
||||
|
||||
CREATE TRIGGER queued_items_revision_after_delete
|
||||
AFTER DELETE ON queued_items
|
||||
BEGIN
|
||||
INSERT INTO queued_thread_revisions (thread_id)
|
||||
VALUES (OLD.thread_id)
|
||||
ON CONFLICT(thread_id) DO UPDATE
|
||||
SET revision = (SELECT COALESCE(MAX(revision), 0) + 1 FROM queued_thread_revisions);
|
||||
END;
|
||||
65
akode-rs/state/src/audit.rs
Normal file
65
akode-rs/state/src/audit.rs
Normal file
@@ -0,0 +1,65 @@
|
||||
//! Read-only queries against an existing state database.
|
||||
|
||||
use anyhow::Result;
|
||||
use akode_protocol::ThreadId;
|
||||
use sqlx::Row;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::SqliteConfig;
|
||||
|
||||
/// Minimal thread metadata used by read-only state database audits.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ThreadStateAuditRow {
|
||||
pub id: String,
|
||||
pub rollout_path: PathBuf,
|
||||
pub archived: bool,
|
||||
pub source: String,
|
||||
pub model_provider: String,
|
||||
}
|
||||
|
||||
/// Read persisted thread rows from a state DB without creating, migrating, or repairing it.
|
||||
pub async fn read_thread_state_audit_rows(
|
||||
sqlite: &SqliteConfig,
|
||||
) -> Result<Vec<ThreadStateAuditRow>> {
|
||||
let pool = sqlite
|
||||
.open_read_only_pool(&sqlite.state_db_path(), /*busy_timeout*/ None)
|
||||
.await?;
|
||||
let rows = sqlx::query(
|
||||
r#"
|
||||
SELECT id, rollout_path, archived, source, model_provider
|
||||
FROM threads
|
||||
"#,
|
||||
)
|
||||
.fetch_all(&pool)
|
||||
.await?;
|
||||
pool.close().await;
|
||||
|
||||
rows.into_iter()
|
||||
.map(|row| {
|
||||
let archived: i64 = row.try_get("archived")?;
|
||||
Ok(ThreadStateAuditRow {
|
||||
id: row.try_get("id")?,
|
||||
rollout_path: PathBuf::from(row.try_get::<String, _>("rollout_path")?),
|
||||
archived: archived != 0,
|
||||
source: row.try_get("source")?,
|
||||
model_provider: row.try_get("model_provider")?,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Reads only the thread IDs and selected paths, without creating or migrating the state DB.
|
||||
pub async fn read_thread_rollout_paths(sqlite: &SqliteConfig) -> Result<Vec<(ThreadId, PathBuf)>> {
|
||||
// Migration can scan the rollout headers immediately if the index is locked.
|
||||
let pool = sqlite
|
||||
.open_read_only_pool(&sqlite.state_db_path(), Some(Duration::ZERO))
|
||||
.await?;
|
||||
let rows = sqlx::query_as::<_, (String, String)>("SELECT id, rollout_path FROM threads")
|
||||
.fetch_all(&pool)
|
||||
.await?;
|
||||
pool.close().await;
|
||||
rows.into_iter()
|
||||
.map(|(id, path)| Ok((ThreadId::from_string(&id)?, PathBuf::from(path))))
|
||||
.collect()
|
||||
}
|
||||
32
akode-rs/state/src/delegated_preview.rs
Normal file
32
akode-rs/state/src/delegated_preview.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
//! Display-only previews for recognized delegated inputs; model content is never rewritten.
|
||||
|
||||
use akode_protocol::items::FunctionCallOutputItem;
|
||||
|
||||
/// Extract the task text from a delegated input, ignoring unrelated tool outputs.
|
||||
pub fn delegated_output_preview(output: &FunctionCallOutputItem) -> Option<String> {
|
||||
if !matches!(output.namespace.as_deref(), Some("codex_app" | "akode_tui"))
|
||||
|| !matches!(
|
||||
output.name.as_str(),
|
||||
"create_thread" | "send_message_to_thread"
|
||||
)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let text = output.output.to_text()?;
|
||||
let preview = text
|
||||
.strip_prefix("<codex_delegation>\n <source_thread_id>")
|
||||
.and_then(|delegation| delegation.split_once("</source_thread_id>\n <input>"))
|
||||
.and_then(|(_, input)| input.strip_suffix("</input>\n</codex_delegation>"))
|
||||
.map(|input| {
|
||||
input
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
.replace("&", "&")
|
||||
})
|
||||
.unwrap_or(text);
|
||||
(!preview.trim().is_empty()).then_some(preview)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "delegated_preview_tests.rs"]
|
||||
mod tests;
|
||||
49
akode-rs/state/src/delegated_preview_tests.rs
Normal file
49
akode-rs/state/src/delegated_preview_tests.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
//! Verify delegated preview decoding and tool identity filtering.
|
||||
|
||||
use super::delegated_output_preview;
|
||||
use akode_protocol::items::FunctionCallOutputItem;
|
||||
use akode_protocol::models::FunctionCallOutputBody;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn delegated_previews_unwrap_only_recognized_inputs() {
|
||||
let wrapped = "<codex_delegation>\n <source_thread_id>source</source_thread_id>\n <input>Check <main> & &lt;literal&gt;</input>\n</codex_delegation>";
|
||||
for (namespace, name, text, expected) in [
|
||||
(
|
||||
Some("codex_app"),
|
||||
"create_thread",
|
||||
wrapped,
|
||||
Some("Check <main> & <literal>"),
|
||||
),
|
||||
(
|
||||
Some("akode_tui"),
|
||||
"send_message_to_thread",
|
||||
wrapped,
|
||||
Some("Check <main> & <literal>"),
|
||||
),
|
||||
(
|
||||
Some("codex_app"),
|
||||
"create_thread",
|
||||
"plain <text>",
|
||||
Some("plain <text>"),
|
||||
),
|
||||
(Some("akode_tui"), "create_thread", " ", None),
|
||||
(Some("other"), "create_thread", wrapped, None),
|
||||
(None, "create_thread", wrapped, None),
|
||||
(Some("codex_app"), "shell", wrapped, None),
|
||||
(
|
||||
Some("codex_app"),
|
||||
"create_thread",
|
||||
"<codex_delegation>incomplete",
|
||||
Some("<codex_delegation>incomplete"),
|
||||
),
|
||||
] {
|
||||
let output = FunctionCallOutputItem {
|
||||
id: "output".to_string(),
|
||||
name: name.to_string(),
|
||||
namespace: namespace.map(str::to_string),
|
||||
output: FunctionCallOutputBody::Text(text.to_string()),
|
||||
};
|
||||
assert_eq!(delegated_output_preview(&output).as_deref(), expected);
|
||||
}
|
||||
}
|
||||
877
akode-rs/state/src/extract.rs
Normal file
877
akode-rs/state/src/extract.rs
Normal file
@@ -0,0 +1,877 @@
|
||||
use crate::model::ThreadMetadata;
|
||||
use akode_history::RolloutItem;
|
||||
use akode_protocol::items::TurnItem;
|
||||
use akode_protocol::models::ResponseItem;
|
||||
use akode_protocol::protocol::EventMsg;
|
||||
use akode_protocol::protocol::SessionMetaLine;
|
||||
use akode_protocol::protocol::SessionSource;
|
||||
use akode_protocol::protocol::SubAgentSource;
|
||||
use akode_protocol::protocol::TurnContextItem;
|
||||
use akode_protocol::protocol::UserMessageEvent;
|
||||
use akode_protocol::protocol::strip_user_message_prefix;
|
||||
use akode_protocol::protocol::user_message_preview;
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
|
||||
pub const GUARDIAN_THREAD_TITLE: &str = "Guardian review";
|
||||
pub const GUARDIAN_THREAD_PREVIEW: &str = "Approval review";
|
||||
|
||||
/// Identifies internal review threads whose user messages are synthetic approval prompts.
|
||||
pub fn is_guardian_review_source(source: &SessionSource) -> bool {
|
||||
matches!(
|
||||
source,
|
||||
SessionSource::SubAgent(SubAgentSource::Other(name)) if name == "guardian"
|
||||
)
|
||||
}
|
||||
|
||||
/// Apply a rollout item to the metadata structure.
|
||||
pub fn apply_rollout_item(
|
||||
metadata: &mut ThreadMetadata,
|
||||
item: &RolloutItem,
|
||||
default_provider: &str,
|
||||
) {
|
||||
match item {
|
||||
RolloutItem::SessionMeta(meta_line) => apply_session_meta_from_item(metadata, meta_line),
|
||||
RolloutItem::TurnContext(turn_ctx) => apply_turn_context(metadata, turn_ctx),
|
||||
RolloutItem::EventMsg(event) => apply_event_msg(metadata, event),
|
||||
RolloutItem::ResponseItem(item) => apply_response_item(metadata, &item.item),
|
||||
RolloutItem::InterAgentCommunication(_)
|
||||
| RolloutItem::InterAgentCommunicationMetadata { .. } => {}
|
||||
RolloutItem::Compacted(_) => {}
|
||||
RolloutItem::WorldState(_) => {}
|
||||
RolloutItem::DynamicToolsUpdated { .. }
|
||||
| RolloutItem::RetainedContext(_)
|
||||
| RolloutItem::SecurityRiskScore(_) => {}
|
||||
RolloutItem::RealtimeItem(_) => {}
|
||||
RolloutItem::TokenUsageRecord(_) => {}
|
||||
}
|
||||
if metadata.model_provider.is_empty() {
|
||||
metadata.model_provider = default_provider.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
/// Return whether this rollout item can mutate thread metadata stored in SQLite.
|
||||
pub fn rollout_item_affects_thread_metadata(item: &RolloutItem) -> bool {
|
||||
match item {
|
||||
RolloutItem::SessionMeta(_) | RolloutItem::TurnContext(_) => true,
|
||||
RolloutItem::EventMsg(
|
||||
EventMsg::TokenCount(_)
|
||||
| EventMsg::UserMessage(_)
|
||||
| EventMsg::ThreadGoalUpdated(_)
|
||||
| EventMsg::ThreadSettingsApplied(_),
|
||||
) => true,
|
||||
RolloutItem::EventMsg(EventMsg::ItemCompleted(event))
|
||||
if matches!(
|
||||
event.item,
|
||||
TurnItem::UserMessage(_) | TurnItem::FunctionCallOutput(_)
|
||||
) =>
|
||||
{
|
||||
true
|
||||
}
|
||||
RolloutItem::EventMsg(_)
|
||||
| RolloutItem::ResponseItem(_)
|
||||
| RolloutItem::InterAgentCommunication(_)
|
||||
| RolloutItem::InterAgentCommunicationMetadata { .. }
|
||||
| RolloutItem::Compacted(_)
|
||||
| RolloutItem::RealtimeItem(_)
|
||||
| RolloutItem::RetainedContext(_)
|
||||
| RolloutItem::DynamicToolsUpdated { .. }
|
||||
| RolloutItem::SecurityRiskScore(_)
|
||||
| RolloutItem::TokenUsageRecord(_)
|
||||
| RolloutItem::WorldState(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_session_meta_from_item(metadata: &mut ThreadMetadata, meta_line: &SessionMetaLine) {
|
||||
if metadata.id != meta_line.meta.id {
|
||||
// Ignore session_meta lines that don't match the canonical thread ID,
|
||||
// e.g., forked rollouts that embed the source session metadata.
|
||||
return;
|
||||
}
|
||||
metadata.creator_user_id = metadata
|
||||
.creator_user_id
|
||||
.take()
|
||||
.or_else(|| meta_line.meta.creator_user_id.clone());
|
||||
metadata.creator_account_id = metadata
|
||||
.creator_account_id
|
||||
.take()
|
||||
.or_else(|| meta_line.meta.creator_account_id.clone());
|
||||
metadata.id = meta_line.meta.id;
|
||||
metadata.attached_thread_parent_id = meta_line
|
||||
.meta
|
||||
.forked_from_id
|
||||
.filter(|_| meta_line.meta.attached_thread);
|
||||
metadata.source = enum_to_string(&meta_line.meta.source);
|
||||
if metadata.originator.is_none() && !meta_line.meta.originator.is_empty() {
|
||||
metadata.originator = Some(meta_line.meta.originator.clone());
|
||||
}
|
||||
// Later SessionMeta lines do not redefine the canonical history_mode.
|
||||
metadata.thread_source = meta_line.meta.thread_source.clone();
|
||||
metadata.agent_nickname = meta_line.meta.agent_nickname.clone();
|
||||
metadata.agent_role = meta_line.meta.agent_role.clone();
|
||||
metadata.agent_path = meta_line.meta.agent_path.clone();
|
||||
if let Some(provider) = meta_line.meta.model_provider.as_deref() {
|
||||
metadata.model_provider = provider.to_string();
|
||||
}
|
||||
if !meta_line.meta.cli_version.is_empty() {
|
||||
metadata.cli_version = meta_line.meta.cli_version.clone();
|
||||
}
|
||||
if !meta_line.meta.cwd.as_os_str().is_empty() {
|
||||
metadata.cwd = meta_line.meta.cwd.clone();
|
||||
}
|
||||
if let Some(git) = meta_line.git.as_ref() {
|
||||
metadata.git_sha = git.commit_hash.as_ref().map(|sha| sha.0.clone());
|
||||
metadata.git_branch = git.branch.clone();
|
||||
metadata.git_origin_url = git.repository_url.clone();
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_turn_context(metadata: &mut ThreadMetadata, turn_ctx: &TurnContextItem) {
|
||||
if metadata.cwd.as_os_str().is_empty() {
|
||||
metadata.cwd = turn_ctx.cwd.clone().into_path_buf();
|
||||
}
|
||||
metadata.model = Some(turn_ctx.model.clone());
|
||||
metadata.reasoning_effort = turn_ctx.effort.clone();
|
||||
metadata.sandbox_policy =
|
||||
serde_json::to_string(&turn_ctx.permission_profile).unwrap_or_default();
|
||||
metadata.approval_mode = enum_to_string(&turn_ctx.approval_policy);
|
||||
}
|
||||
|
||||
fn apply_event_msg(metadata: &mut ThreadMetadata, event: &EventMsg) {
|
||||
match event {
|
||||
EventMsg::TokenCount(token_count) => {
|
||||
if let Some(info) = token_count.info.as_ref() {
|
||||
metadata.tokens_used = info.total_token_usage.total_tokens.max(0);
|
||||
}
|
||||
}
|
||||
EventMsg::UserMessage(user) if !metadata_is_guardian_review(metadata) => {
|
||||
apply_user_message(metadata, user);
|
||||
}
|
||||
EventMsg::ItemCompleted(event) => {
|
||||
if let TurnItem::UserMessage(user) = &event.item
|
||||
&& !metadata_is_guardian_review(metadata)
|
||||
{
|
||||
apply_user_message(metadata, &user.as_legacy_user_message_event());
|
||||
} else if let TurnItem::FunctionCallOutput(output) = &event.item
|
||||
&& !metadata_is_guardian_review(metadata)
|
||||
{
|
||||
// Delegated turns have no user message, but must still be discoverable.
|
||||
let preview = crate::delegated_output_preview(output);
|
||||
set_preview_if_empty(metadata, preview);
|
||||
}
|
||||
}
|
||||
EventMsg::ThreadGoalUpdated(event) if !metadata_is_guardian_review(metadata) => {
|
||||
let objective = event.goal.objective.trim();
|
||||
if !objective.is_empty() {
|
||||
set_preview_if_empty(metadata, Some(objective.to_string()));
|
||||
}
|
||||
}
|
||||
EventMsg::ThreadSettingsApplied(event) => {
|
||||
let settings = &event.thread_settings;
|
||||
metadata.model = Some(settings.model.clone());
|
||||
metadata.model_provider = settings.model_provider_id.clone();
|
||||
metadata.reasoning_effort = settings.reasoning_effort.clone();
|
||||
metadata.cwd = settings.cwd.clone().into_path_buf();
|
||||
metadata.sandbox_policy =
|
||||
serde_json::to_string(&settings.permission_profile).unwrap_or_default();
|
||||
metadata.approval_mode = enum_to_string(&settings.approval_policy);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_response_item(_metadata: &mut ThreadMetadata, _item: &ResponseItem) {}
|
||||
|
||||
pub(crate) fn metadata_is_guardian_review(metadata: &ThreadMetadata) -> bool {
|
||||
serde_json::from_str::<SessionSource>(metadata.source.as_str())
|
||||
.as_ref()
|
||||
.is_ok_and(is_guardian_review_source)
|
||||
}
|
||||
|
||||
fn apply_user_message(metadata: &mut ThreadMetadata, user: &UserMessageEvent) {
|
||||
let preview = user_message_preview(user);
|
||||
if metadata.first_user_message.is_none() {
|
||||
metadata.first_user_message = preview.clone();
|
||||
}
|
||||
set_preview_if_empty(metadata, preview);
|
||||
if metadata.title.is_empty() {
|
||||
let title = strip_user_message_prefix(user.message.as_str());
|
||||
if !title.is_empty() {
|
||||
metadata.title = title.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_preview_if_empty(metadata: &mut ThreadMetadata, preview: Option<String>) {
|
||||
if metadata.preview.is_none() {
|
||||
metadata.preview = preview;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn enum_to_string<T: Serialize>(value: &T) -> String {
|
||||
match serde_json::to_value(value) {
|
||||
Ok(Value::String(s)) => s,
|
||||
Ok(other) => other.to_string(),
|
||||
Err(_) => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::apply_rollout_item;
|
||||
use super::rollout_item_affects_thread_metadata;
|
||||
use crate::ThreadMetadataBuilder;
|
||||
use crate::model::ThreadMetadata;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use akode_history::RolloutItem;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::config_types::ApprovalsReviewer;
|
||||
use akode_protocol::config_types::CollaborationMode;
|
||||
use akode_protocol::config_types::ModeKind;
|
||||
use akode_protocol::config_types::ReasoningSummary;
|
||||
use akode_protocol::config_types::Settings;
|
||||
use akode_protocol::items::TurnItem;
|
||||
use akode_protocol::items::UserMessageItem;
|
||||
use akode_protocol::models::ContentItem;
|
||||
use akode_protocol::models::PermissionProfile;
|
||||
use akode_protocol::models::ResponseItem;
|
||||
use akode_protocol::openai_models::ReasoningEffort;
|
||||
use akode_protocol::protocol::AskForApproval;
|
||||
use akode_protocol::protocol::EventMsg;
|
||||
use akode_protocol::protocol::ItemCompletedEvent;
|
||||
use akode_protocol::protocol::SessionMeta;
|
||||
use akode_protocol::protocol::SessionMetaLine;
|
||||
use akode_protocol::protocol::SessionSource;
|
||||
use akode_protocol::protocol::SubAgentSource;
|
||||
use akode_protocol::protocol::ThreadGoal;
|
||||
use akode_protocol::protocol::ThreadGoalStatus;
|
||||
use akode_protocol::protocol::ThreadGoalUpdatedEvent;
|
||||
use akode_protocol::protocol::ThreadHistoryMode;
|
||||
use akode_protocol::protocol::ThreadSettingsAppliedEvent;
|
||||
use akode_protocol::protocol::ThreadSettingsSnapshot;
|
||||
use akode_protocol::protocol::TurnContextItem;
|
||||
use akode_protocol::protocol::USER_MESSAGE_BEGIN;
|
||||
use akode_protocol::protocol::UserMessageEvent;
|
||||
use akode_protocol::user_input::UserInput;
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::PathBuf;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[test]
|
||||
fn response_item_user_messages_do_not_set_title_or_first_user_message() {
|
||||
let mut metadata = metadata_for_test();
|
||||
let item = RolloutItem::ResponseItem(
|
||||
ResponseItem::Message {
|
||||
status: None,
|
||||
encrypted_content: None,
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![ContentItem::InputText {
|
||||
text: "hello from response item".to_string(),
|
||||
}],
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}
|
||||
.into(),
|
||||
);
|
||||
|
||||
apply_rollout_item(&mut metadata, &item, "test-provider");
|
||||
|
||||
assert_eq!(metadata.first_user_message, None);
|
||||
assert_eq!(metadata.preview, None);
|
||||
assert_eq!(metadata.title, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_msg_user_messages_set_title_and_first_user_message() {
|
||||
let mut metadata = metadata_for_test();
|
||||
let item = RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
|
||||
client_id: None,
|
||||
message: format!("{USER_MESSAGE_BEGIN} actual user request"),
|
||||
images: Some(vec![]),
|
||||
local_images: vec![],
|
||||
text_elements: vec![],
|
||||
..Default::default()
|
||||
}));
|
||||
|
||||
apply_rollout_item(&mut metadata, &item, "test-provider");
|
||||
|
||||
assert_eq!(
|
||||
metadata.first_user_message.as_deref(),
|
||||
Some("actual user request")
|
||||
);
|
||||
assert_eq!(metadata.preview.as_deref(), Some("actual user request"));
|
||||
assert_eq!(metadata.title, "actual user request");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delegated_turn_preview_preserves_user_message_metadata() {
|
||||
let mut metadata = metadata_for_test();
|
||||
let mut expected = metadata.clone();
|
||||
for text in [" ", "delegated task", "later output"] {
|
||||
let item = RolloutItem::EventMsg(EventMsg::ItemCompleted(ItemCompletedEvent {
|
||||
content_token_count: None,
|
||||
thread_id: metadata.id,
|
||||
turn_id: "turn-1".to_string(),
|
||||
item: TurnItem::FunctionCallOutput(akode_protocol::items::FunctionCallOutputItem {
|
||||
id: "output-1".to_string(),
|
||||
name: "create_thread".to_string(),
|
||||
namespace: Some("codex_app".to_string()),
|
||||
output: akode_protocol::models::FunctionCallOutputBody::Text(text.to_string()),
|
||||
}),
|
||||
started_at_ms: Some(0),
|
||||
completed_at_ms: 0,
|
||||
}));
|
||||
assert!(rollout_item_affects_thread_metadata(&item));
|
||||
apply_rollout_item(&mut metadata, &item, "test-provider");
|
||||
if text == "delegated task" {
|
||||
expected.preview = Some(text.to_string());
|
||||
}
|
||||
assert_eq!(metadata, expected);
|
||||
}
|
||||
let user_item = RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
|
||||
message: "actual user follow-up".to_string(),
|
||||
..Default::default()
|
||||
}));
|
||||
apply_rollout_item(&mut metadata, &user_item, "test-provider");
|
||||
expected.first_user_message = Some("actual user follow-up".to_string());
|
||||
expected.title = "actual user follow-up".to_string();
|
||||
assert_eq!(metadata, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_user_message_items_set_title_and_first_user_message() {
|
||||
let mut metadata = metadata_for_test();
|
||||
let item = RolloutItem::EventMsg(EventMsg::ItemCompleted(ItemCompletedEvent {
|
||||
content_token_count: None,
|
||||
thread_id: ThreadId::default(),
|
||||
turn_id: "turn-1".to_string(),
|
||||
item: TurnItem::UserMessage(UserMessageItem::new(&[UserInput::Text {
|
||||
text: format!("{USER_MESSAGE_BEGIN} actual user request"),
|
||||
text_elements: Vec::new(),
|
||||
}])),
|
||||
started_at_ms: Some(0),
|
||||
completed_at_ms: 0,
|
||||
}));
|
||||
|
||||
apply_rollout_item(&mut metadata, &item, "test-provider");
|
||||
|
||||
assert_eq!(
|
||||
metadata.first_user_message.as_deref(),
|
||||
Some("actual user request")
|
||||
);
|
||||
assert_eq!(metadata.preview.as_deref(), Some("actual user request"));
|
||||
assert_eq!(metadata.title, "actual user request");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guardian_projection_skips_prompts_and_preserves_custom_names() {
|
||||
let thread_id = ThreadId::new();
|
||||
let source = SessionSource::SubAgent(SubAgentSource::Other("guardian".to_string()));
|
||||
let mut metadata =
|
||||
ThreadMetadataBuilder::new(thread_id, PathBuf::new(), Utc::now(), source.clone())
|
||||
.build("test-provider");
|
||||
let session_meta = RolloutItem::SessionMeta(Box::new(SessionMetaLine {
|
||||
meta: SessionMeta {
|
||||
session_id: thread_id.into(),
|
||||
id: thread_id,
|
||||
source,
|
||||
..Default::default()
|
||||
},
|
||||
git: None,
|
||||
}));
|
||||
apply_rollout_item(&mut metadata, &session_meta, "test-provider");
|
||||
let mut expected = metadata.clone();
|
||||
expected.title = super::GUARDIAN_THREAD_TITLE.to_string();
|
||||
expected.name = None;
|
||||
expected.preview = Some(super::GUARDIAN_THREAD_PREVIEW.to_string());
|
||||
expected.first_user_message = None;
|
||||
|
||||
let user = UserMessageItem::new(&[UserInput::Text {
|
||||
text: "large synthetic guardian prompt".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}]);
|
||||
for event in [
|
||||
EventMsg::UserMessage(user.as_legacy_user_message_event()),
|
||||
EventMsg::ItemCompleted(ItemCompletedEvent {
|
||||
content_token_count: None,
|
||||
thread_id,
|
||||
turn_id: "turn-1".to_string(),
|
||||
item: TurnItem::UserMessage(user),
|
||||
started_at_ms: Some(0),
|
||||
completed_at_ms: 0,
|
||||
}),
|
||||
] {
|
||||
apply_rollout_item(
|
||||
&mut metadata,
|
||||
&RolloutItem::EventMsg(event),
|
||||
"test-provider",
|
||||
);
|
||||
assert_eq!(metadata, expected);
|
||||
}
|
||||
|
||||
let mut existing = metadata.clone();
|
||||
existing.title = "Named Guardian review".to_string();
|
||||
metadata.prefer_existing_explicit_title(&existing);
|
||||
assert_eq!(metadata, existing);
|
||||
|
||||
metadata.name = Some("Named Guardian review".to_string());
|
||||
let expected = metadata.clone();
|
||||
apply_rollout_item(&mut metadata, &session_meta, "test-provider");
|
||||
assert_eq!(metadata, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_msg_image_only_user_message_sets_image_placeholder_preview() {
|
||||
let mut metadata = metadata_for_test();
|
||||
let item = RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
|
||||
client_id: None,
|
||||
message: String::new(),
|
||||
images: Some(vec!["https://example.com/image.png".to_string()]),
|
||||
local_images: vec![],
|
||||
text_elements: vec![],
|
||||
..Default::default()
|
||||
}));
|
||||
|
||||
apply_rollout_item(&mut metadata, &item, "test-provider");
|
||||
|
||||
assert_eq!(metadata.first_user_message.as_deref(), Some("[Image]"));
|
||||
assert_eq!(metadata.preview.as_deref(), Some("[Image]"));
|
||||
assert_eq!(metadata.title, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_msg_audio_only_user_message_sets_audio_placeholder_preview() {
|
||||
let mut metadata = metadata_for_test();
|
||||
let item = RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
|
||||
client_id: None,
|
||||
message: String::new(),
|
||||
images: None,
|
||||
local_images: vec![],
|
||||
audio: Some(vec!["https://example.com/audio.mp3".to_string()]),
|
||||
local_audio: vec![],
|
||||
text_elements: vec![],
|
||||
..Default::default()
|
||||
}));
|
||||
|
||||
apply_rollout_item(&mut metadata, &item, "test-provider");
|
||||
|
||||
assert_eq!(metadata.first_user_message.as_deref(), Some("[Audio]"));
|
||||
assert_eq!(metadata.preview.as_deref(), Some("[Audio]"));
|
||||
assert_eq!(metadata.title, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_msg_blank_user_message_without_images_keeps_first_user_message_empty() {
|
||||
let mut metadata = metadata_for_test();
|
||||
let item = RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
|
||||
client_id: None,
|
||||
message: " ".to_string(),
|
||||
images: Some(vec![]),
|
||||
local_images: vec![],
|
||||
text_elements: vec![],
|
||||
..Default::default()
|
||||
}));
|
||||
|
||||
apply_rollout_item(&mut metadata, &item, "test-provider");
|
||||
|
||||
assert_eq!(metadata.first_user_message, None);
|
||||
assert_eq!(metadata.preview, None);
|
||||
assert_eq!(metadata.title, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_msg_thread_goal_sets_preview_only_and_later_user_sets_message_title() {
|
||||
let mut metadata = metadata_for_test();
|
||||
let goal_item =
|
||||
RolloutItem::EventMsg(EventMsg::ThreadGoalUpdated(ThreadGoalUpdatedEvent {
|
||||
thread_id: metadata.id,
|
||||
turn_id: None,
|
||||
goal: ThreadGoal {
|
||||
thread_id: metadata.id,
|
||||
objective: "optimize the benchmark".to_string(),
|
||||
status: ThreadGoalStatus::Active,
|
||||
token_budget: None,
|
||||
tokens_used: 0,
|
||||
time_used_seconds: 0,
|
||||
created_at: 1,
|
||||
updated_at: 1,
|
||||
},
|
||||
}));
|
||||
|
||||
apply_rollout_item(&mut metadata, &goal_item, "test-provider");
|
||||
|
||||
assert_eq!(metadata.preview.as_deref(), Some("optimize the benchmark"));
|
||||
assert_eq!(metadata.first_user_message, None);
|
||||
assert_eq!(metadata.title, "");
|
||||
|
||||
let user_item = RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
|
||||
client_id: None,
|
||||
message: format!("{USER_MESSAGE_BEGIN} next normal prompt"),
|
||||
images: Some(vec![]),
|
||||
local_images: vec![],
|
||||
text_elements: vec![],
|
||||
..Default::default()
|
||||
}));
|
||||
|
||||
apply_rollout_item(&mut metadata, &user_item, "test-provider");
|
||||
|
||||
assert_eq!(metadata.preview.as_deref(), Some("optimize the benchmark"));
|
||||
assert_eq!(
|
||||
metadata.first_user_message.as_deref(),
|
||||
Some("next normal prompt")
|
||||
);
|
||||
assert_eq!(metadata.title, "next normal prompt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_context_does_not_override_session_cwd() {
|
||||
let mut metadata = metadata_for_test();
|
||||
metadata.cwd = PathBuf::new();
|
||||
let thread_id = metadata.id;
|
||||
|
||||
apply_rollout_item(
|
||||
&mut metadata,
|
||||
&RolloutItem::SessionMeta(Box::new(SessionMetaLine {
|
||||
meta: SessionMeta {
|
||||
account_scoped: false,
|
||||
creator_user_id: None,
|
||||
attached_thread: false,
|
||||
creator_account_id: None,
|
||||
session_id: thread_id.into(),
|
||||
id: thread_id,
|
||||
forked_from_id: Some(
|
||||
ThreadId::from_string(&Uuid::now_v7().to_string()).expect("thread id"),
|
||||
),
|
||||
forked_from_ordinal_exclusive: None,
|
||||
parent_thread_id: None,
|
||||
timestamp: "2026-02-26T00:00:00.000Z".to_string(),
|
||||
cwd: PathBuf::from("/child/worktree"),
|
||||
runtime_workspace_roots: None,
|
||||
originator: "codex_cli_rs".to_string(),
|
||||
cli_version: "0.0.0".to_string(),
|
||||
source: SessionSource::Cli,
|
||||
thread_source: None,
|
||||
agent_path: None,
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
model_provider: Some("openai".to_string()),
|
||||
base_instructions: None,
|
||||
dynamic_tools: None,
|
||||
selected_capability_roots: Vec::new(),
|
||||
memory_mode: None,
|
||||
history_mode: Default::default(),
|
||||
history_base: None,
|
||||
subagent_history_start_ordinal: None,
|
||||
multi_agent_version: None,
|
||||
context_window: None,
|
||||
},
|
||||
git: None,
|
||||
})),
|
||||
"test-provider",
|
||||
);
|
||||
apply_rollout_item(
|
||||
&mut metadata,
|
||||
&RolloutItem::TurnContext(TurnContextItem {
|
||||
turn_id: Some("turn-1".to_string()),
|
||||
root_turn_id: None,
|
||||
direct_only_tool_namespaces: None,
|
||||
disabled_plugin_ids: None,
|
||||
cwd: serde_json::from_value(serde_json::json!(
|
||||
std::env::current_dir()
|
||||
.expect("current directory")
|
||||
.join("parent/workspace")
|
||||
))
|
||||
.expect("absolute parent cwd"),
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: None,
|
||||
permission_profile: PermissionProfile::Disabled,
|
||||
active_permission_profile: None,
|
||||
model: "gpt-5".to_string(),
|
||||
comp_hash: None,
|
||||
collaboration_mode: None,
|
||||
multi_agent_version: None,
|
||||
realtime_active: None,
|
||||
effort: None,
|
||||
summary: Some(akode_protocol::config_types::ReasoningSummary::Auto),
|
||||
}),
|
||||
"test-provider",
|
||||
);
|
||||
|
||||
assert_eq!(metadata.cwd, PathBuf::from("/child/worktree"));
|
||||
let permission_profile: PermissionProfile = PermissionProfile::Disabled;
|
||||
assert_eq!(
|
||||
metadata.sandbox_policy,
|
||||
serde_json::to_string(&permission_profile).expect("serialize permission profile")
|
||||
);
|
||||
assert_eq!(metadata.approval_mode, "never");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_context_sets_permission_profile_metadata() {
|
||||
let mut metadata = metadata_for_test();
|
||||
let permission_profile = PermissionProfile::workspace_write();
|
||||
|
||||
apply_rollout_item(
|
||||
&mut metadata,
|
||||
&RolloutItem::TurnContext(TurnContextItem {
|
||||
turn_id: Some("turn-1".to_string()),
|
||||
root_turn_id: None,
|
||||
direct_only_tool_namespaces: None,
|
||||
disabled_plugin_ids: None,
|
||||
cwd: serde_json::from_value(serde_json::json!(
|
||||
std::env::current_dir()
|
||||
.expect("current directory")
|
||||
.join("workspace")
|
||||
))
|
||||
.expect("absolute workspace cwd"),
|
||||
approval_policy: AskForApproval::OnRequest,
|
||||
approvals_reviewer: None,
|
||||
permission_profile: permission_profile.clone(),
|
||||
active_permission_profile: None,
|
||||
model: "gpt-5".to_string(),
|
||||
comp_hash: None,
|
||||
collaboration_mode: None,
|
||||
multi_agent_version: None,
|
||||
realtime_active: None,
|
||||
effort: None,
|
||||
summary: Some(akode_protocol::config_types::ReasoningSummary::Auto),
|
||||
}),
|
||||
"test-provider",
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
metadata.sandbox_policy,
|
||||
serde_json::to_string(&permission_profile).expect("serialize permission profile")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_context_sets_cwd_when_session_cwd_missing() {
|
||||
let mut metadata = metadata_for_test();
|
||||
metadata.cwd = PathBuf::new();
|
||||
let fallback_cwd = std::env::current_dir()
|
||||
.expect("current directory")
|
||||
.join("fallback/workspace");
|
||||
|
||||
apply_rollout_item(
|
||||
&mut metadata,
|
||||
&RolloutItem::TurnContext(TurnContextItem {
|
||||
turn_id: Some("turn-1".to_string()),
|
||||
root_turn_id: None,
|
||||
direct_only_tool_namespaces: None,
|
||||
disabled_plugin_ids: None,
|
||||
cwd: serde_json::from_value(serde_json::json!(&fallback_cwd))
|
||||
.expect("absolute fallback cwd"),
|
||||
approval_policy: AskForApproval::OnRequest,
|
||||
approvals_reviewer: None,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
model: "gpt-5".to_string(),
|
||||
comp_hash: None,
|
||||
collaboration_mode: None,
|
||||
multi_agent_version: None,
|
||||
realtime_active: None,
|
||||
effort: Some(ReasoningEffort::High),
|
||||
summary: Some(akode_protocol::config_types::ReasoningSummary::Auto),
|
||||
}),
|
||||
"test-provider",
|
||||
);
|
||||
|
||||
assert_eq!(metadata.cwd, fallback_cwd);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_context_sets_model_and_reasoning_effort() {
|
||||
let mut metadata = metadata_for_test();
|
||||
|
||||
apply_rollout_item(
|
||||
&mut metadata,
|
||||
&RolloutItem::TurnContext(TurnContextItem {
|
||||
turn_id: Some("turn-1".to_string()),
|
||||
root_turn_id: None,
|
||||
direct_only_tool_namespaces: None,
|
||||
disabled_plugin_ids: None,
|
||||
cwd: serde_json::from_value(serde_json::json!(
|
||||
std::env::current_dir()
|
||||
.expect("current directory")
|
||||
.join("fallback/workspace")
|
||||
))
|
||||
.expect("absolute fallback cwd"),
|
||||
approval_policy: AskForApproval::OnRequest,
|
||||
approvals_reviewer: None,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
model: "gpt-5".to_string(),
|
||||
comp_hash: None,
|
||||
collaboration_mode: None,
|
||||
multi_agent_version: None,
|
||||
realtime_active: None,
|
||||
effort: Some(ReasoningEffort::High),
|
||||
summary: Some(akode_protocol::config_types::ReasoningSummary::Auto),
|
||||
}),
|
||||
"test-provider",
|
||||
);
|
||||
|
||||
assert_eq!(metadata.model.as_deref(), Some("gpt-5"));
|
||||
assert_eq!(metadata.reasoning_effort, Some(ReasoningEffort::High));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_settings_applied_updates_resume_metadata() {
|
||||
let mut metadata = metadata_for_test();
|
||||
let permission_profile = PermissionProfile::workspace_write();
|
||||
let cwd = std::env::current_dir()
|
||||
.expect("current directory")
|
||||
.join("updated/workspace");
|
||||
let item = RolloutItem::EventMsg(EventMsg::ThreadSettingsApplied(
|
||||
ThreadSettingsAppliedEvent {
|
||||
thread_id: None,
|
||||
thread_settings: ThreadSettingsSnapshot {
|
||||
disabled_plugin_ids: Vec::new(),
|
||||
model: "gpt-5.2-codex".to_string(),
|
||||
model_provider_id: "updated-provider".to_string(),
|
||||
service_tier: None,
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
requested_approvals_reviewer: None,
|
||||
permission_profile: permission_profile.clone(),
|
||||
active_permission_profile: None,
|
||||
cwd: cwd.clone().try_into().expect("absolute settings cwd"),
|
||||
runtime_workspace_roots: None,
|
||||
reasoning_effort: Some(ReasoningEffort::Ultra),
|
||||
reasoning_summary: Some(ReasoningSummary::Auto),
|
||||
personality: None,
|
||||
collaboration_mode: CollaborationMode {
|
||||
mode: ModeKind::Default,
|
||||
settings: Settings {
|
||||
model: "gpt-5.2-codex".to_string(),
|
||||
reasoning_effort: Some(ReasoningEffort::Ultra),
|
||||
developer_instructions: None,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
));
|
||||
|
||||
assert!(rollout_item_affects_thread_metadata(&item));
|
||||
apply_rollout_item(&mut metadata, &item, "test-provider");
|
||||
|
||||
assert_eq!(metadata.model.as_deref(), Some("gpt-5.2-codex"));
|
||||
assert_eq!(metadata.model_provider, "updated-provider");
|
||||
assert_eq!(metadata.reasoning_effort, Some(ReasoningEffort::Ultra));
|
||||
assert_eq!(metadata.cwd, cwd);
|
||||
assert_eq!(metadata.approval_mode, "never");
|
||||
assert_eq!(
|
||||
metadata.sandbox_policy,
|
||||
serde_json::to_string(&permission_profile)
|
||||
.expect("permission profile should serialize")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_meta_does_not_set_model_or_reasoning_effort() {
|
||||
let mut metadata = metadata_for_test();
|
||||
metadata.history_mode = ThreadHistoryMode::Paginated;
|
||||
let thread_id = metadata.id;
|
||||
|
||||
apply_rollout_item(
|
||||
&mut metadata,
|
||||
&RolloutItem::SessionMeta(Box::new(SessionMetaLine {
|
||||
meta: SessionMeta {
|
||||
account_scoped: false,
|
||||
creator_user_id: None,
|
||||
attached_thread: false,
|
||||
creator_account_id: None,
|
||||
session_id: thread_id.into(),
|
||||
id: thread_id,
|
||||
forked_from_id: None,
|
||||
forked_from_ordinal_exclusive: None,
|
||||
parent_thread_id: None,
|
||||
timestamp: "2026-02-26T00:00:00.000Z".to_string(),
|
||||
cwd: PathBuf::from("/workspace"),
|
||||
runtime_workspace_roots: None,
|
||||
originator: "codex_cli_rs".to_string(),
|
||||
cli_version: "0.0.0".to_string(),
|
||||
source: SessionSource::Cli,
|
||||
thread_source: None,
|
||||
agent_path: None,
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
model_provider: Some("openai".to_string()),
|
||||
base_instructions: None,
|
||||
dynamic_tools: None,
|
||||
selected_capability_roots: Vec::new(),
|
||||
memory_mode: None,
|
||||
history_mode: ThreadHistoryMode::Legacy,
|
||||
history_base: None,
|
||||
subagent_history_start_ordinal: None,
|
||||
multi_agent_version: None,
|
||||
context_window: None,
|
||||
},
|
||||
git: None,
|
||||
})),
|
||||
"test-provider",
|
||||
);
|
||||
|
||||
assert_eq!(metadata.model, None);
|
||||
assert_eq!(metadata.reasoning_effort, None);
|
||||
assert_eq!(metadata.history_mode, ThreadHistoryMode::Paginated);
|
||||
}
|
||||
|
||||
fn metadata_for_test() -> ThreadMetadata {
|
||||
let id = ThreadId::from_string(&Uuid::from_u128(42).to_string()).expect("thread id");
|
||||
let created_at = DateTime::<Utc>::from_timestamp(1_735_689_600, 0).expect("timestamp");
|
||||
ThreadMetadata {
|
||||
creator_user_id: None,
|
||||
attached_thread_parent_id: None,
|
||||
creator_account_id: None,
|
||||
originator: None,
|
||||
id,
|
||||
rollout_path: PathBuf::from("/tmp/a.jsonl"),
|
||||
created_at,
|
||||
updated_at: created_at,
|
||||
recency_at: created_at,
|
||||
source: "cli".to_string(),
|
||||
history_mode: Default::default(),
|
||||
thread_source: None,
|
||||
agent_path: None,
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
model_provider: "openai".to_string(),
|
||||
model: None,
|
||||
reasoning_effort: None,
|
||||
cwd: PathBuf::from("/tmp"),
|
||||
cli_version: "0.0.0".to_string(),
|
||||
title: String::new(),
|
||||
name: None,
|
||||
preview: None,
|
||||
sandbox_policy: "read-only".to_string(),
|
||||
approval_mode: "on-request".to_string(),
|
||||
tokens_used: 1,
|
||||
first_user_message: None,
|
||||
archived_at: None,
|
||||
section: None,
|
||||
section_position: None,
|
||||
section_entered_at: None,
|
||||
project_id: None,
|
||||
git_sha: None,
|
||||
git_branch: None,
|
||||
git_origin_url: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diff_fields_detects_changes() {
|
||||
let mut base = metadata_for_test();
|
||||
base.id = ThreadId::from_string(&Uuid::now_v7().to_string()).expect("thread id");
|
||||
base.title = "hello".to_string();
|
||||
let mut other = base.clone();
|
||||
other.tokens_used = 2;
|
||||
other.title = "world".to_string();
|
||||
let diffs = base.diff_fields(&other);
|
||||
assert_eq!(diffs, vec!["title", "tokens_used"]);
|
||||
}
|
||||
}
|
||||
172
akode-rs/state/src/lib.rs
Normal file
172
akode-rs/state/src/lib.rs
Normal file
@@ -0,0 +1,172 @@
|
||||
//! SQLite-backed state for rollout metadata.
|
||||
//!
|
||||
//! This crate is intentionally small and focused: it extracts rollout metadata
|
||||
//! from JSONL rollouts and mirrors it into a local SQLite database. Backfill
|
||||
//! orchestration and rollout scanning live in `akode-core`.
|
||||
|
||||
const _: () = assert!(
|
||||
libsqlite3_sys::SQLITE_VERSION_NUMBER >= 3_051_003,
|
||||
"bundled SQLite must include the WAL-reset corruption fix",
|
||||
);
|
||||
|
||||
mod audit;
|
||||
mod delegated_preview;
|
||||
mod extract;
|
||||
pub mod log_db;
|
||||
mod migrations;
|
||||
mod model;
|
||||
mod nfs_migration;
|
||||
mod paths;
|
||||
mod runtime;
|
||||
mod sqlite;
|
||||
mod telemetry;
|
||||
|
||||
pub use log_db::LogWriteFailureReporter;
|
||||
pub use model::CreatedProject;
|
||||
pub use model::LogEntry;
|
||||
pub use model::LogQuery;
|
||||
pub use model::LogRow;
|
||||
pub use model::Phase2JobClaimOutcome;
|
||||
pub use model::Project;
|
||||
pub use model::ProjectRoot;
|
||||
pub use model::ProjectSortKey;
|
||||
pub use model::ProjectsPage;
|
||||
pub use model::QueuedUserSubmissionRecord;
|
||||
pub use model::RolloutMigrationCursor;
|
||||
pub use model::RolloutMigrationSkippedRollout;
|
||||
pub use model::RolloutMigrationState;
|
||||
pub use nfs_migration::NfsDbMigration;
|
||||
pub use nfs_migration::NfsDbMigrationOutcome;
|
||||
pub use runtime::GuardianReviewRecord;
|
||||
pub use runtime::MAX_GUARDIAN_REVIEW_BYTES;
|
||||
pub use runtime::MAX_GUARDIAN_REVIEW_RECORDS;
|
||||
pub use runtime::MAX_GUARDIAN_REVIEW_RECORDS_PER_THREAD;
|
||||
/// Preferred entrypoint: owns configuration and metrics.
|
||||
pub use runtime::StateRuntime;
|
||||
pub use sqlite::SqliteConfig;
|
||||
pub use sqlite::SqlitePoolWriteExt;
|
||||
|
||||
pub use audit::ThreadStateAuditRow;
|
||||
pub use audit::read_thread_rollout_paths;
|
||||
pub use audit::read_thread_state_audit_rows;
|
||||
pub use delegated_preview::delegated_output_preview;
|
||||
pub use extract::GUARDIAN_THREAD_PREVIEW;
|
||||
pub use extract::GUARDIAN_THREAD_TITLE;
|
||||
/// Low-level storage engine: useful for focused tests.
|
||||
///
|
||||
/// Most consumers should prefer [`StateRuntime`].
|
||||
pub use extract::apply_rollout_item;
|
||||
pub use extract::is_guardian_review_source;
|
||||
pub use extract::rollout_item_affects_thread_metadata;
|
||||
pub use model::AddThreadAttachmentOutcome;
|
||||
pub use model::Anchor;
|
||||
pub use model::BackfillState;
|
||||
pub use model::BackfillStats;
|
||||
pub use model::BackfillStatus;
|
||||
pub use model::DirectionalThreadSpawnEdgeStatus;
|
||||
pub use model::ExtractionOutcome;
|
||||
pub use model::RemoveThreadAttachmentOutcome;
|
||||
pub use model::SortDirection;
|
||||
pub use model::SortKey;
|
||||
pub use model::Stage1JobClaim;
|
||||
pub use model::Stage1JobClaimOutcome;
|
||||
pub use model::Stage1Output;
|
||||
pub use model::Stage1StartupClaimParams;
|
||||
pub use model::ThreadAttachment;
|
||||
pub use model::ThreadAttachmentArchiveFilter;
|
||||
pub use model::ThreadAttachmentOwner;
|
||||
pub use model::ThreadAttachmentOwnerPage;
|
||||
pub use model::ThreadAttachmentPage;
|
||||
pub use model::ThreadGoal;
|
||||
pub use model::ThreadGoalStatus;
|
||||
pub use model::ThreadMetadata;
|
||||
pub use model::ThreadMetadataBuilder;
|
||||
pub use model::ThreadRelationFilter;
|
||||
pub use model::ThreadSection;
|
||||
pub use model::ThreadSectionAppearance;
|
||||
pub use model::ThreadSectionsPage;
|
||||
pub use model::ThreadsPage;
|
||||
pub use runtime::ExternalAgentConfigImportDetailsRecord;
|
||||
pub use runtime::ExternalAgentConfigImportFailureRecord;
|
||||
pub use runtime::ExternalAgentConfigImportHistoryRecord;
|
||||
pub use runtime::ExternalAgentConfigImportSuccessRecord;
|
||||
pub use runtime::GoalAccountingMode;
|
||||
pub use runtime::GoalAccountingOutcome;
|
||||
pub use runtime::GoalStore;
|
||||
pub use runtime::GoalUpdate;
|
||||
pub use runtime::MemoryStore;
|
||||
pub use runtime::ReadStateOperation;
|
||||
pub use runtime::ReadStateUpdate;
|
||||
pub use runtime::RemoteControlEnrollmentRecord;
|
||||
pub use runtime::SqliteIntegrityCheck;
|
||||
pub use runtime::SqliteQueueStore;
|
||||
pub use runtime::ThreadFilterOptions;
|
||||
pub use runtime::ThreadReadState;
|
||||
pub use runtime::backup_runtime_db_for_fresh_start;
|
||||
pub use runtime::collect_runtime_db_backups;
|
||||
pub use runtime::is_sqlite_corruption_error;
|
||||
pub use runtime::open_thread_history_db;
|
||||
pub use runtime::recovery::RuntimeDbBackup;
|
||||
pub use runtime::runtime_db_path_for_corruption_error;
|
||||
pub use runtime::sqlite_error_detail_is_lock;
|
||||
pub use runtime::sqlite_integrity_check;
|
||||
pub use sqlite::RuntimeDbPath;
|
||||
pub use telemetry::DbTelemetry;
|
||||
pub use telemetry::DbTelemetryHandle;
|
||||
pub use telemetry::install_process_db_telemetry;
|
||||
pub use telemetry::record_backfill_gate;
|
||||
pub use telemetry::record_fallback;
|
||||
|
||||
/// Maximum number of pending user submissions permitted for one thread.
|
||||
pub const MAX_QUEUE_ITEMS: usize = 100;
|
||||
|
||||
/// Maximum serialized size of one persisted thread-attachment payload.
|
||||
pub const MAX_THREAD_ATTACHMENT_PAYLOAD_BYTES: usize = 64 * 1024;
|
||||
|
||||
/// Maximum byte length of a persisted attachment type.
|
||||
pub const MAX_THREAD_ATTACHMENT_TYPE_BYTES: usize = 256;
|
||||
|
||||
/// Maximum byte length of a persisted stable attachment identity key.
|
||||
pub const MAX_THREAD_ATTACHMENT_IDENTITY_KEY_BYTES: usize = 256;
|
||||
|
||||
/// Maximum number of attachments returned in one page.
|
||||
pub const MAX_THREAD_ATTACHMENT_LIST_PAGE_SIZE: usize = 100;
|
||||
|
||||
/// Maximum number of active attachments retained for one thread.
|
||||
pub const MAX_THREAD_ATTACHMENTS_PER_THREAD: usize = 100;
|
||||
|
||||
/// Stable UUIDv7 identifying the built-in pinned thread section.
|
||||
pub const PINNED_THREAD_SECTION_ID: &str = "01984de2-8f74-7c91-a3b2-5c5e937cf318";
|
||||
|
||||
/// User-facing name of the built-in pinned thread section.
|
||||
pub const PINNED_THREAD_SECTION_NAME: &str = "Pinned";
|
||||
|
||||
/// Environment variable for overriding the SQLite state database home directory.
|
||||
pub const SQLITE_HOME_ENV: &str = "AKODE_SQLITE_HOME";
|
||||
|
||||
/// Errors encountered during DB operations. Tags: [stage]
|
||||
pub const DB_ERROR_METRIC: &str = "codex.db.error";
|
||||
/// Metrics on backfill process. Tags: [status]
|
||||
pub const DB_METRIC_BACKFILL: &str = "codex.db.backfill";
|
||||
/// Metrics on backfill duration. Tags: [status]
|
||||
pub const DB_METRIC_BACKFILL_DURATION_MS: &str = "codex.db.backfill.duration_ms";
|
||||
/// Confirmed SQLite quick-check corruption findings. Tags: [db]
|
||||
pub const DB_CORRUPTION_METRIC: &str = "codex.sqlite.corruption.count";
|
||||
/// SQLite initialization attempts. Tags: [status, phase, db, error]
|
||||
pub const DB_INIT_METRIC: &str = "codex.sqlite.init.count";
|
||||
/// SQLite initialization latency. Tags: [status, phase, db, error]
|
||||
pub const DB_INIT_DURATION_METRIC: &str = "codex.sqlite.init.duration_ms";
|
||||
/// Rollout fallback attempts. Tags: [caller, reason]
|
||||
pub const DB_FALLBACK_METRIC: &str = "codex.sqlite.fallback.count";
|
||||
/// SQLite log batch write attempts. Tags: [status, error]
|
||||
pub const LOG_WRITE_METRIC: &str = "codex.sqlite.logs.write.count";
|
||||
/// SQLite log batch write latency. Tags: [status, error]
|
||||
pub const LOG_WRITE_DURATION_METRIC: &str = "codex.sqlite.logs.write.duration_ms";
|
||||
/// Estimated bytes in each SQLite log batch. Tags: [status, error]
|
||||
pub const LOG_WRITE_BYTES_METRIC: &str = "codex.sqlite.logs.write.bytes";
|
||||
/// Number of entries in each SQLite log batch. Tags: [status, error]
|
||||
pub const LOG_WRITE_ENTRIES_METRIC: &str = "codex.sqlite.logs.write.entries";
|
||||
/// Largest estimated entry size in each SQLite log batch. Tags: [status, error]
|
||||
pub const LOG_WRITE_MAX_ENTRY_BYTES_METRIC: &str = "codex.sqlite.logs.write.max_entry_bytes";
|
||||
/// SQLite log entries discarded before they can be queued. Tags: [reason]
|
||||
pub const LOG_QUEUE_DROPPED_METRIC: &str = "codex.sqlite.logs.queue.dropped";
|
||||
972
akode-rs/state/src/log_db.rs
Normal file
972
akode-rs/state/src/log_db.rs
Normal file
@@ -0,0 +1,972 @@
|
||||
//! Tracing log export into the local SQLite log database.
|
||||
//!
|
||||
//! This module provides a `tracing_subscriber::Layer` that captures events,
|
||||
//! formats each one into a `LogEntry`, and sends entries to a bounded background
|
||||
//! queue. The background task inserts into the dedicated `logs` SQLite database
|
||||
//! in batches to keep logging overhead low.
|
||||
//! SQLx events are excluded so database writes cannot generate more writes.
|
||||
//! Flush failures go to the supplied failure reporter without re-entering tracing.
|
||||
//!
|
||||
//! ## Usage
|
||||
//!
|
||||
//! ```no_run
|
||||
//! use akode_state::log_db;
|
||||
//! use tracing_subscriber::prelude::*;
|
||||
//!
|
||||
//! # async fn example(state_db: std::sync::Arc<akode_state::StateRuntime>, reporter: std::sync::Arc<dyn akode_state::LogWriteFailureReporter>) {
|
||||
//! let layer = log_db::start(state_db, reporter);
|
||||
//! let _ = tracing_subscriber::registry()
|
||||
//! .with(layer)
|
||||
//! .try_init();
|
||||
//! # }
|
||||
//! ```
|
||||
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::RwLock;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
use std::time::SystemTime;
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tracing::Event;
|
||||
use tracing::field::Field;
|
||||
use tracing::field::Visit;
|
||||
use tracing::level_filters::LevelFilter;
|
||||
use tracing::span::Attributes;
|
||||
use tracing::span::Id;
|
||||
use tracing::span::Record;
|
||||
use tracing_subscriber::Layer;
|
||||
use tracing_subscriber::field::RecordFields;
|
||||
use tracing_subscriber::filter::Targets;
|
||||
use tracing_subscriber::fmt::FormatFields;
|
||||
use tracing_subscriber::fmt::FormattedFields;
|
||||
use tracing_subscriber::fmt::format::DefaultFields;
|
||||
use tracing_subscriber::registry::LookupSpan;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::LogEntry;
|
||||
use crate::StateRuntime;
|
||||
|
||||
const LOG_QUEUE_CAPACITY: usize = 2048;
|
||||
const LOG_BATCH_SIZE: usize = 512;
|
||||
const LOG_FLUSH_INTERVAL: Duration = Duration::from_secs(10);
|
||||
const SQLX_LOG_TARGETS: [&str; 3] = ["sqlx", "sqlx_core", "sqlx_sqlite"];
|
||||
|
||||
pub fn default_filter() -> Targets {
|
||||
Targets::new()
|
||||
.with_default(LevelFilter::TRACE)
|
||||
.with_target("h2", LevelFilter::WARN)
|
||||
.with_target("hyper_util", LevelFilter::WARN)
|
||||
.with_target("log", LevelFilter::OFF)
|
||||
// Avoid constructing backend diagnostics when no other layer needs them.
|
||||
.with_targets(SQLX_LOG_TARGETS.map(|target| (format!("{target}::"), LevelFilter::OFF)))
|
||||
.with_target("akode_rmcp_client", LevelFilter::INFO)
|
||||
.with_target("tonic::transport", LevelFilter::WARN)
|
||||
.with_target("tower::buffer", LevelFilter::WARN)
|
||||
.with_target("akode_otel.log_only", LevelFilter::OFF)
|
||||
.with_target("akode_otel.trace_safe", LevelFilter::OFF)
|
||||
.with_target("rmcp", LevelFilter::INFO)
|
||||
.with_target("tokio::", LevelFilter::INFO)
|
||||
.with_target("runtime::", LevelFilter::INFO)
|
||||
.with_target("tokio_graceful::guard", LevelFilter::DEBUG)
|
||||
.with_target("tokio_graceful::trigger", LevelFilter::DEBUG)
|
||||
.with_target("akode_api::responses_websocket_timing", LevelFilter::OFF)
|
||||
.with_target("akode_core::post_sampling_token_estimate", LevelFilter::OFF)
|
||||
// Full model request bodies and streamed response payloads overwhelm the
|
||||
// SQLite log database, but remain available to explicit TRACE subscribers.
|
||||
.with_target("akode_http_client::transport", LevelFilter::DEBUG)
|
||||
.with_target("akode_api::sse", LevelFilter::DEBUG)
|
||||
// Per-chunk streaming traces otherwise flood the bounded SQLite log queue.
|
||||
.with_target("akode_tui::streaming::controller", LevelFilter::DEBUG)
|
||||
.with_target("akode_tui::streaming::table_holdback", LevelFilter::DEBUG)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct LogSinkQueueConfig {
|
||||
pub queue_capacity: usize,
|
||||
pub batch_size: usize,
|
||||
pub flush_interval: Duration,
|
||||
}
|
||||
|
||||
impl Default for LogSinkQueueConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
queue_capacity: LOG_QUEUE_CAPACITY,
|
||||
batch_size: LOG_BATCH_SIZE,
|
||||
flush_interval: LOG_FLUSH_INTERVAL,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LogSinkQueueConfig {
|
||||
fn normalized(self) -> Self {
|
||||
Self {
|
||||
queue_capacity: self.queue_capacity.max(1),
|
||||
batch_size: self.batch_size.max(1),
|
||||
flush_interval: if self.flush_interval.is_zero() {
|
||||
LOG_FLUSH_INTERVAL
|
||||
} else {
|
||||
self.flush_interval
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A tracing log writer that can flush entries accepted by its queue.
|
||||
///
|
||||
/// Implementations should keep `Layer::on_event` non-blocking for ordinary log
|
||||
/// events. `flush` should wait for entries accepted before the flush command to
|
||||
/// be processed by the writer.
|
||||
pub trait LogWriter<S>: Layer<S>
|
||||
where
|
||||
S: tracing::Subscriber + for<'a> LookupSpan<'a>,
|
||||
{
|
||||
fn flush(&self) -> impl Future<Output = ()> + Send + '_;
|
||||
}
|
||||
|
||||
/// Receives a formatted, redacted diagnostic when a SQLite log batch is lost
|
||||
/// this propagatest to telemetry and feedback memory buffer to avoid lost reports
|
||||
pub trait LogWriteFailureReporter: Send + Sync {
|
||||
fn report_failure(&self, diagnostic: &str);
|
||||
}
|
||||
|
||||
pub struct LogDbLayer {
|
||||
sender: mpsc::Sender<LogDbCommand>,
|
||||
has_write_failure: Arc<AtomicBool>,
|
||||
failure_reporter: Arc<RwLock<Arc<dyn LogWriteFailureReporter>>>,
|
||||
process_uuid: String,
|
||||
}
|
||||
|
||||
/// Starts the SQLite log writer with a shared, independent failure reporter.
|
||||
pub fn start(
|
||||
state_db: std::sync::Arc<StateRuntime>,
|
||||
failure_reporter: Arc<dyn LogWriteFailureReporter>,
|
||||
) -> LogDbLayer {
|
||||
LogDbLayer::start(state_db, failure_reporter)
|
||||
}
|
||||
|
||||
impl Clone for LogDbLayer {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
sender: self.sender.clone(),
|
||||
has_write_failure: self.has_write_failure.clone(),
|
||||
failure_reporter: self.failure_reporter.clone(),
|
||||
process_uuid: self.process_uuid.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LogDbLayer {
|
||||
pub fn start(
|
||||
state_db: std::sync::Arc<StateRuntime>,
|
||||
failure_reporter: Arc<dyn LogWriteFailureReporter>,
|
||||
) -> Self {
|
||||
Self::start_with_config(state_db, failure_reporter, LogSinkQueueConfig::default())
|
||||
}
|
||||
|
||||
pub fn start_with_config(
|
||||
state_db: std::sync::Arc<StateRuntime>,
|
||||
failure_reporter: Arc<dyn LogWriteFailureReporter>,
|
||||
config: LogSinkQueueConfig,
|
||||
) -> Self {
|
||||
let config = config.normalized();
|
||||
let (sender, receiver) = mpsc::channel(config.queue_capacity);
|
||||
let has_write_failure = Arc::new(AtomicBool::new(false));
|
||||
let failure_reporter = Arc::new(RwLock::new(failure_reporter));
|
||||
tokio::spawn(run_inserter(
|
||||
state_db,
|
||||
receiver,
|
||||
config,
|
||||
failure_reporter.clone(),
|
||||
has_write_failure.clone(),
|
||||
));
|
||||
Self {
|
||||
sender,
|
||||
has_write_failure,
|
||||
failure_reporter,
|
||||
process_uuid: current_process_log_uuid().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces the startup reporter once the client notification destination is available.
|
||||
pub fn set_failure_reporter(&self, reporter: Arc<dyn LogWriteFailureReporter>) {
|
||||
*self
|
||||
.failure_reporter
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = reporter;
|
||||
}
|
||||
|
||||
/// Whether this writer has lost logs, making SQLite incomplete for feedback.
|
||||
pub fn has_write_failure(&self) -> bool {
|
||||
self.has_write_failure.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub async fn flush(&self) {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
if self.sender.send(LogDbCommand::Flush(tx)).await.is_ok() {
|
||||
let _ = rx.await;
|
||||
}
|
||||
}
|
||||
|
||||
fn try_send(&self, entry: LogEntry) {
|
||||
if let Err(error) = self.sender.try_send(LogDbCommand::Entry(Box::new(entry))) {
|
||||
let reason = match error {
|
||||
mpsc::error::TrySendError::Full(_) => "full",
|
||||
mpsc::error::TrySendError::Closed(_) => "closed",
|
||||
};
|
||||
crate::telemetry::record_log_queue_drop(reason, /*telemetry*/ None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Layer<S> for LogDbLayer
|
||||
where
|
||||
S: tracing::Subscriber + for<'a> LookupSpan<'a>,
|
||||
{
|
||||
fn on_new_span(
|
||||
&self,
|
||||
attrs: &Attributes<'_>,
|
||||
id: &Id,
|
||||
ctx: tracing_subscriber::layer::Context<'_, S>,
|
||||
) {
|
||||
let mut visitor = SpanFieldVisitor::default();
|
||||
attrs.record(&mut visitor);
|
||||
|
||||
if let Some(span) = ctx.span(id) {
|
||||
span.extensions_mut().insert(SpanLogContext {
|
||||
name: span.metadata().name().to_string(),
|
||||
formatted_fields: format_fields(attrs),
|
||||
thread_id: visitor.thread_id,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn on_record(
|
||||
&self,
|
||||
id: &Id,
|
||||
values: &Record<'_>,
|
||||
ctx: tracing_subscriber::layer::Context<'_, S>,
|
||||
) {
|
||||
let mut visitor = SpanFieldVisitor::default();
|
||||
values.record(&mut visitor);
|
||||
|
||||
if let Some(span) = ctx.span(id) {
|
||||
let mut extensions = span.extensions_mut();
|
||||
if let Some(log_context) = extensions.get_mut::<SpanLogContext>() {
|
||||
if let Some(thread_id) = visitor.thread_id {
|
||||
log_context.thread_id = Some(thread_id);
|
||||
}
|
||||
append_fields(&mut log_context.formatted_fields, values);
|
||||
} else {
|
||||
extensions.insert(SpanLogContext {
|
||||
name: span.metadata().name().to_string(),
|
||||
formatted_fields: format_fields(values),
|
||||
thread_id: visitor.thread_id,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn on_event(&self, event: &Event<'_>, ctx: tracing_subscriber::layer::Context<'_, S>) {
|
||||
let metadata = event.metadata();
|
||||
let target = metadata.target();
|
||||
// SQLx can emit from both the inserter task and its separate worker threads.
|
||||
// This guard must remain local to the sink and independent of optional filters.
|
||||
if target
|
||||
.split("::")
|
||||
.next()
|
||||
.is_some_and(|target| SQLX_LOG_TARGETS.contains(&target))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Channel sends and timer polls from this sink must not enqueue more
|
||||
// SQLite writes when Tokio runtime tracing is enabled.
|
||||
if *metadata.level() == tracing::Level::TRACE
|
||||
&& matches!(target.split("::").next(), Some("tokio" | "runtime"))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// `tracing-log` checks filters with the original log target before
|
||||
// dispatching an event whose tracing target is `log`, so the outer
|
||||
// target filter cannot reliably reject these bridged events.
|
||||
if target == "log" {
|
||||
return;
|
||||
}
|
||||
|
||||
// The SDK emits DEBUG timer meta-events every second per process; these
|
||||
// were over 30% of retained logs in measured high-fanout Codex environments.
|
||||
if target == "opentelemetry_sdk"
|
||||
&& matches!(
|
||||
*metadata.level(),
|
||||
tracing::Level::TRACE | tracing::Level::DEBUG
|
||||
)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let mut visitor = MessageVisitor::default();
|
||||
event.record(&mut visitor);
|
||||
// gRPC connections run on their own task, so an unsolicited PING
|
||||
// ACK can emit this benign warning after every otherwise successful
|
||||
// export. Drop only that warning before queue/drop accounting; other
|
||||
// HTTP/2 diagnostics must remain available to unrelated clients.
|
||||
if target == "h2::proto::ping_pong"
|
||||
&& visitor
|
||||
.message
|
||||
.as_deref()
|
||||
.is_some_and(|message| message.starts_with("recv PING ack that we never sent: "))
|
||||
{
|
||||
return;
|
||||
}
|
||||
let thread_id = visitor
|
||||
.thread_id
|
||||
.clone()
|
||||
.or_else(|| event_thread_id(event, &ctx));
|
||||
let feedback_log_body = format_feedback_log_body(event, &ctx);
|
||||
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_else(|_| Duration::from_secs(0));
|
||||
let entry = LogEntry {
|
||||
ts: now.as_secs() as i64,
|
||||
ts_nanos: now.subsec_nanos() as i64,
|
||||
level: metadata.level().as_str().to_string(),
|
||||
target: metadata.target().to_string(),
|
||||
message: visitor.message,
|
||||
feedback_log_body: Some(feedback_log_body),
|
||||
thread_id,
|
||||
process_uuid: Some(self.process_uuid.clone()),
|
||||
module_path: metadata.module_path().map(ToString::to_string),
|
||||
file: metadata.file().map(ToString::to_string),
|
||||
line: metadata.line().map(|line| line as i64),
|
||||
};
|
||||
|
||||
self.try_send(entry);
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> LogWriter<S> for LogDbLayer
|
||||
where
|
||||
S: tracing::Subscriber + for<'a> LookupSpan<'a>,
|
||||
{
|
||||
fn flush(&self) -> impl Future<Output = ()> + Send + '_ {
|
||||
LogDbLayer::flush(self)
|
||||
}
|
||||
}
|
||||
|
||||
enum LogDbCommand {
|
||||
Entry(Box<LogEntry>),
|
||||
Flush(oneshot::Sender<()>),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct SpanLogContext {
|
||||
name: String,
|
||||
formatted_fields: String,
|
||||
thread_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct SpanFieldVisitor {
|
||||
thread_id: Option<String>,
|
||||
}
|
||||
|
||||
impl SpanFieldVisitor {
|
||||
fn record_field(&mut self, field: &Field, value: String) {
|
||||
if field.name() == "thread_id" && self.thread_id.is_none() {
|
||||
self.thread_id = Some(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Visit for SpanFieldVisitor {
|
||||
fn record_i64(&mut self, field: &Field, value: i64) {
|
||||
self.record_field(field, value.to_string());
|
||||
}
|
||||
|
||||
fn record_u64(&mut self, field: &Field, value: u64) {
|
||||
self.record_field(field, value.to_string());
|
||||
}
|
||||
|
||||
fn record_bool(&mut self, field: &Field, value: bool) {
|
||||
self.record_field(field, value.to_string());
|
||||
}
|
||||
|
||||
fn record_f64(&mut self, field: &Field, value: f64) {
|
||||
self.record_field(field, value.to_string());
|
||||
}
|
||||
|
||||
fn record_str(&mut self, field: &Field, value: &str) {
|
||||
self.record_field(field, value.to_string());
|
||||
}
|
||||
|
||||
fn record_error(&mut self, field: &Field, value: &(dyn std::error::Error + 'static)) {
|
||||
self.record_field(field, value.to_string());
|
||||
}
|
||||
|
||||
fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
|
||||
self.record_field(field, format!("{value:?}"));
|
||||
}
|
||||
}
|
||||
|
||||
fn event_thread_id<S>(
|
||||
event: &Event<'_>,
|
||||
ctx: &tracing_subscriber::layer::Context<'_, S>,
|
||||
) -> Option<String>
|
||||
where
|
||||
S: tracing::Subscriber + for<'a> LookupSpan<'a>,
|
||||
{
|
||||
let mut thread_id = None;
|
||||
if let Some(scope) = ctx.event_scope(event) {
|
||||
for span in scope.from_root() {
|
||||
let extensions = span.extensions();
|
||||
if let Some(log_context) = extensions.get::<SpanLogContext>()
|
||||
&& log_context.thread_id.is_some()
|
||||
{
|
||||
thread_id = log_context.thread_id.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
thread_id
|
||||
}
|
||||
|
||||
fn format_feedback_log_body<S>(
|
||||
event: &Event<'_>,
|
||||
ctx: &tracing_subscriber::layer::Context<'_, S>,
|
||||
) -> String
|
||||
where
|
||||
S: tracing::Subscriber + for<'a> LookupSpan<'a>,
|
||||
{
|
||||
let mut feedback_log_body = String::new();
|
||||
if let Some(scope) = ctx.event_scope(event) {
|
||||
for span in scope.from_root() {
|
||||
let extensions = span.extensions();
|
||||
if let Some(log_context) = extensions.get::<SpanLogContext>() {
|
||||
feedback_log_body.push_str(&log_context.name);
|
||||
if !log_context.formatted_fields.is_empty() {
|
||||
feedback_log_body.push('{');
|
||||
feedback_log_body.push_str(&log_context.formatted_fields);
|
||||
feedback_log_body.push('}');
|
||||
}
|
||||
} else {
|
||||
feedback_log_body.push_str(span.metadata().name());
|
||||
}
|
||||
feedback_log_body.push(':');
|
||||
}
|
||||
if !feedback_log_body.is_empty() {
|
||||
feedback_log_body.push(' ');
|
||||
}
|
||||
}
|
||||
feedback_log_body.push_str(&format_fields(event));
|
||||
feedback_log_body
|
||||
}
|
||||
|
||||
fn format_fields<R>(fields: R) -> String
|
||||
where
|
||||
R: RecordFields,
|
||||
{
|
||||
let formatter = DefaultFields::default();
|
||||
let mut formatted = FormattedFields::<DefaultFields>::new(String::new());
|
||||
let _ = formatter.format_fields(formatted.as_writer(), fields);
|
||||
formatted.fields
|
||||
}
|
||||
|
||||
fn append_fields(fields: &mut String, values: &Record<'_>) {
|
||||
let formatter = DefaultFields::default();
|
||||
let mut formatted = FormattedFields::<DefaultFields>::new(std::mem::take(fields));
|
||||
let _ = formatter.add_fields(&mut formatted, values);
|
||||
*fields = formatted.fields;
|
||||
}
|
||||
|
||||
fn current_process_log_uuid() -> &'static str {
|
||||
static PROCESS_LOG_UUID: OnceLock<String> = OnceLock::new();
|
||||
PROCESS_LOG_UUID.get_or_init(|| {
|
||||
let pid = std::process::id();
|
||||
let process_uuid = Uuid::new_v4();
|
||||
format!("pid:{pid}:{process_uuid}")
|
||||
})
|
||||
}
|
||||
|
||||
async fn run_inserter(
|
||||
state_db: std::sync::Arc<StateRuntime>,
|
||||
mut receiver: mpsc::Receiver<LogDbCommand>,
|
||||
config: LogSinkQueueConfig,
|
||||
failure_reporter: Arc<RwLock<Arc<dyn LogWriteFailureReporter>>>,
|
||||
has_write_failure: Arc<AtomicBool>,
|
||||
) {
|
||||
let mut buffer = Vec::with_capacity(config.batch_size);
|
||||
let mut ticker = tokio::time::interval(config.flush_interval);
|
||||
// Consume the immediate startup tick so entries flush after the interval.
|
||||
ticker.tick().await;
|
||||
loop {
|
||||
tokio::select! {
|
||||
maybe_command = receiver.recv() => {
|
||||
match maybe_command {
|
||||
Some(LogDbCommand::Entry(entry)) => {
|
||||
buffer.push(*entry);
|
||||
if buffer.len() >= config.batch_size {
|
||||
flush(&state_db, &mut buffer, failure_reporter.as_ref(), &has_write_failure).await;
|
||||
}
|
||||
}
|
||||
Some(LogDbCommand::Flush(reply)) => {
|
||||
flush(&state_db, &mut buffer, failure_reporter.as_ref(), &has_write_failure).await;
|
||||
let _ = reply.send(());
|
||||
}
|
||||
None => {
|
||||
flush(&state_db, &mut buffer, failure_reporter.as_ref(), &has_write_failure).await;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = ticker.tick() => {
|
||||
flush(&state_db, &mut buffer, failure_reporter.as_ref(), &has_write_failure).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn flush(
|
||||
state_db: &StateRuntime,
|
||||
buffer: &mut Vec<LogEntry>,
|
||||
failure_reporter: &RwLock<Arc<dyn LogWriteFailureReporter>>,
|
||||
has_write_failure: &AtomicBool,
|
||||
) {
|
||||
if buffer.is_empty() {
|
||||
return;
|
||||
}
|
||||
let entries = buffer.split_off(0);
|
||||
let started = Instant::now();
|
||||
let result = state_db.insert_logs(entries.as_slice()).await;
|
||||
let duration = started.elapsed();
|
||||
// if log flushing failed it means that likely something is wrong with the logs database,
|
||||
// so store the logs in the memory buffer to avoid them being lost during /feedback
|
||||
// the entries are dropped because the in memory buffer has it's own space-constrainted rules for preserving logs
|
||||
if let Err(error) = &result {
|
||||
let error = crate::telemetry::classify_error(error);
|
||||
let timestamp =
|
||||
chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, /*use_z*/ true);
|
||||
let entry_count = entries.len();
|
||||
has_write_failure.store(true, Ordering::Relaxed);
|
||||
failure_reporter.read().unwrap_or_else(std::sync::PoisonError::into_inner).report_failure(&format!(
|
||||
"{timestamp} ERROR failed to flush logs to SQLite error={error:?} entries={entry_count}\n"
|
||||
));
|
||||
}
|
||||
|
||||
crate::telemetry::record_log_write(
|
||||
/*telemetry*/ None,
|
||||
duration,
|
||||
entries.as_slice(),
|
||||
&result,
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct MessageVisitor {
|
||||
message: Option<String>,
|
||||
thread_id: Option<String>,
|
||||
}
|
||||
|
||||
impl MessageVisitor {
|
||||
fn record_field(&mut self, field: &Field, value: String) {
|
||||
if field.name() == "message" && self.message.is_none() {
|
||||
self.message = Some(value.clone());
|
||||
}
|
||||
if field.name() == "thread_id" && self.thread_id.is_none() {
|
||||
self.thread_id = Some(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Visit for MessageVisitor {
|
||||
fn record_i64(&mut self, field: &Field, value: i64) {
|
||||
self.record_field(field, value.to_string());
|
||||
}
|
||||
|
||||
fn record_u64(&mut self, field: &Field, value: u64) {
|
||||
self.record_field(field, value.to_string());
|
||||
}
|
||||
|
||||
fn record_bool(&mut self, field: &Field, value: bool) {
|
||||
self.record_field(field, value.to_string());
|
||||
}
|
||||
|
||||
fn record_f64(&mut self, field: &Field, value: f64) {
|
||||
self.record_field(field, value.to_string());
|
||||
}
|
||||
|
||||
fn record_str(&mut self, field: &Field, value: &str) {
|
||||
self.record_field(field, value.to_string());
|
||||
}
|
||||
|
||||
fn record_error(&mut self, field: &Field, value: &(dyn std::error::Error + 'static)) {
|
||||
self.record_field(field, value.to_string());
|
||||
}
|
||||
|
||||
fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
|
||||
self.record_field(field, format!("{value:?}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "log_db_filter_tests.rs"]
|
||||
mod filter_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "log_db_failure_tests.rs"]
|
||||
mod failure_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::io;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use akode_utils_absolute_path::test_support::PathExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tracing_subscriber::filter::Targets;
|
||||
use tracing_subscriber::fmt::writer::MakeWriter;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
use tracing_subscriber::util::SubscriberInitExt;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn temp_codex_home() -> std::path::PathBuf {
|
||||
std::env::temp_dir().join(format!("codex-state-log-db-{}", Uuid::new_v4()))
|
||||
}
|
||||
|
||||
async fn wait_for_log_count(runtime: &StateRuntime, expected: usize) -> Vec<crate::LogRow> {
|
||||
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2);
|
||||
loop {
|
||||
let rows = runtime
|
||||
.query_logs(&crate::LogQuery::default())
|
||||
.await
|
||||
.expect("query logs");
|
||||
if rows.len() == expected {
|
||||
return rows;
|
||||
}
|
||||
assert!(
|
||||
tokio::time::Instant::now() < deadline,
|
||||
"timed out waiting for {expected} logs; saw {}",
|
||||
rows.len()
|
||||
);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
}
|
||||
|
||||
fn test_entry(message: &str) -> LogEntry {
|
||||
LogEntry {
|
||||
ts: 1,
|
||||
ts_nanos: 2,
|
||||
level: "INFO".to_string(),
|
||||
target: "test".to_string(),
|
||||
message: Some(message.to_string()),
|
||||
feedback_log_body: Some(message.to_string()),
|
||||
thread_id: Some("thread-1".to_string()),
|
||||
process_uuid: Some("process-1".to_string()),
|
||||
module_path: Some("module".to_string()),
|
||||
file: Some("file.rs".to_string()),
|
||||
line: Some(7),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct SharedWriter {
|
||||
bytes: Arc<Mutex<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl SharedWriter {
|
||||
pub(super) fn snapshot(&self) -> String {
|
||||
String::from_utf8(self.bytes.lock().expect("writer mutex poisoned").clone())
|
||||
.expect("valid utf-8")
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct SharedWriterGuard {
|
||||
bytes: Arc<Mutex<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl LogWriteFailureReporter for SharedWriter {
|
||||
fn report_failure(&self, diagnostic: &str) {
|
||||
std::io::Write::write_all(&mut self.make_writer(), diagnostic.as_bytes())
|
||||
.expect("write diagnostic to test buffer");
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> MakeWriter<'a> for SharedWriter {
|
||||
type Writer = SharedWriterGuard;
|
||||
|
||||
fn make_writer(&'a self) -> Self::Writer {
|
||||
SharedWriterGuard {
|
||||
bytes: Arc::clone(&self.bytes),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl io::Write for SharedWriterGuard {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
self.bytes
|
||||
.lock()
|
||||
.expect("writer mutex poisoned")
|
||||
.extend_from_slice(buf);
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sqlite_feedback_logs_match_feedback_formatter_shape() {
|
||||
let codex_home = temp_codex_home();
|
||||
let runtime = StateRuntime::init(
|
||||
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
|
||||
"test-provider".to_string(),
|
||||
)
|
||||
.await
|
||||
.expect("initialize runtime");
|
||||
let writer = SharedWriter::default();
|
||||
let layer = start(runtime.clone(), Arc::new(SharedWriter::default()));
|
||||
|
||||
let subscriber = tracing_subscriber::registry()
|
||||
.with(
|
||||
tracing_subscriber::fmt::layer()
|
||||
.with_writer(writer.clone())
|
||||
.with_ansi(false)
|
||||
.with_target(false)
|
||||
.with_filter(default_filter()),
|
||||
)
|
||||
.with(layer.clone().with_filter(default_filter()));
|
||||
let guard = subscriber.set_default();
|
||||
|
||||
tracing::trace!("threadless-before");
|
||||
tracing::info_span!("feedback-thread", thread_id = "thread-1", turn = 1).in_scope(|| {
|
||||
tracing::info!(foo = 2, "thread-scoped");
|
||||
});
|
||||
tracing::debug!("threadless-after");
|
||||
|
||||
layer.flush().await;
|
||||
drop(guard);
|
||||
|
||||
let feedback_logs = writer.snapshot();
|
||||
let without_timestamps = |logs: &str| {
|
||||
logs.lines()
|
||||
.map(|line| match line.split_once(' ') {
|
||||
Some((_, rest)) => rest,
|
||||
None => line,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
};
|
||||
let sqlite_logs = String::from_utf8(
|
||||
runtime
|
||||
.query_feedback_logs("thread-1")
|
||||
.await
|
||||
.expect("query feedback logs"),
|
||||
)
|
||||
.expect("valid utf-8");
|
||||
assert_eq!(
|
||||
without_timestamps(&sqlite_logs),
|
||||
without_timestamps(&feedback_logs)
|
||||
);
|
||||
|
||||
let _ = tokio::fs::remove_dir_all(codex_home).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn flush_persists_logs_for_query() {
|
||||
let codex_home = temp_codex_home();
|
||||
let runtime = StateRuntime::init(
|
||||
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
|
||||
"test-provider".to_string(),
|
||||
)
|
||||
.await
|
||||
.expect("initialize runtime");
|
||||
let layer = start(runtime.clone(), Arc::new(SharedWriter::default()));
|
||||
|
||||
let guard = tracing_subscriber::registry()
|
||||
.with(
|
||||
layer
|
||||
.clone()
|
||||
.with_filter(Targets::new().with_default(tracing::Level::TRACE)),
|
||||
)
|
||||
.set_default();
|
||||
|
||||
tracing::info!("buffered-log");
|
||||
|
||||
layer.flush().await;
|
||||
drop(guard);
|
||||
|
||||
let after_flush = runtime
|
||||
.query_logs(&crate::LogQuery::default())
|
||||
.await
|
||||
.expect("query logs after flush");
|
||||
assert_eq!(after_flush.len(), 1);
|
||||
assert_eq!(after_flush[0].message.as_deref(), Some("buffered-log"));
|
||||
|
||||
let _ = tokio::fs::remove_dir_all(codex_home).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn configured_batch_size_flushes_without_explicit_flush() {
|
||||
let codex_home = temp_codex_home();
|
||||
let runtime = StateRuntime::init(
|
||||
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
|
||||
"test-provider".to_string(),
|
||||
)
|
||||
.await
|
||||
.expect("initialize runtime");
|
||||
let layer = LogDbLayer::start_with_config(
|
||||
runtime.clone(),
|
||||
Arc::new(SharedWriter::default()),
|
||||
LogSinkQueueConfig {
|
||||
queue_capacity: 8,
|
||||
batch_size: 2,
|
||||
flush_interval: std::time::Duration::from_secs(60),
|
||||
},
|
||||
);
|
||||
|
||||
let guard = tracing_subscriber::registry()
|
||||
.with(
|
||||
layer
|
||||
.clone()
|
||||
.with_filter(Targets::new().with_default(tracing::Level::TRACE)),
|
||||
)
|
||||
.set_default();
|
||||
|
||||
tracing::info!("first-batch-log");
|
||||
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
|
||||
assert_eq!(
|
||||
runtime
|
||||
.query_logs(&crate::LogQuery::default())
|
||||
.await
|
||||
.expect("query logs before batch fills")
|
||||
.len(),
|
||||
0
|
||||
);
|
||||
|
||||
tracing::info!("second-batch-log");
|
||||
let after_batch = wait_for_log_count(&runtime, /*expected*/ 2).await;
|
||||
drop(guard);
|
||||
|
||||
assert_eq!(
|
||||
after_batch
|
||||
.iter()
|
||||
.map(|row| row.message.as_deref())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![Some("first-batch-log"), Some("second-batch-log")]
|
||||
);
|
||||
|
||||
let _ = tokio::fs::remove_dir_all(codex_home).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn configured_flush_interval_persists_buffered_logs() {
|
||||
let codex_home = temp_codex_home();
|
||||
let runtime = StateRuntime::init(
|
||||
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
|
||||
"test-provider".to_string(),
|
||||
)
|
||||
.await
|
||||
.expect("initialize runtime");
|
||||
let layer = LogDbLayer::start_with_config(
|
||||
runtime.clone(),
|
||||
Arc::new(SharedWriter::default()),
|
||||
LogSinkQueueConfig {
|
||||
queue_capacity: 8,
|
||||
batch_size: 128,
|
||||
flush_interval: std::time::Duration::from_millis(10),
|
||||
},
|
||||
);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
|
||||
let guard = tracing_subscriber::registry()
|
||||
.with(
|
||||
layer
|
||||
.clone()
|
||||
.with_filter(Targets::new().with_default(tracing::Level::TRACE)),
|
||||
)
|
||||
.set_default();
|
||||
|
||||
tracing::info!("interval-log");
|
||||
let after_interval = wait_for_log_count(&runtime, /*expected*/ 1).await;
|
||||
drop(guard);
|
||||
|
||||
assert_eq!(after_interval[0].message.as_deref(), Some("interval-log"));
|
||||
|
||||
let _ = tokio::fs::remove_dir_all(codex_home).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn event_queue_drops_new_entries_when_full() {
|
||||
let (sender, mut receiver) = mpsc::channel(1);
|
||||
let layer = LogDbLayer {
|
||||
sender,
|
||||
has_write_failure: Arc::new(AtomicBool::new(false)),
|
||||
failure_reporter: Arc::new(RwLock::new(Arc::new(SharedWriter::default()))),
|
||||
process_uuid: "process-1".to_string(),
|
||||
};
|
||||
|
||||
layer.try_send(test_entry("first-queued-log"));
|
||||
layer.try_send(test_entry("dropped-log"));
|
||||
|
||||
match receiver.try_recv().expect("first entry queued") {
|
||||
LogDbCommand::Entry(entry) => {
|
||||
assert_eq!(entry.message.as_deref(), Some("first-queued-log"));
|
||||
}
|
||||
LogDbCommand::Flush(_) => panic!("expected queued entry"),
|
||||
}
|
||||
assert!(receiver.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn flush_waits_for_queue_capacity_and_receiver_processing() {
|
||||
let (sender, mut receiver) = mpsc::channel(1);
|
||||
let layer = LogDbLayer {
|
||||
sender,
|
||||
has_write_failure: Arc::new(AtomicBool::new(false)),
|
||||
failure_reporter: Arc::new(RwLock::new(Arc::new(SharedWriter::default()))),
|
||||
process_uuid: "process-1".to_string(),
|
||||
};
|
||||
|
||||
layer.try_send(test_entry("queued-before-flush"));
|
||||
let mut flush_task = tokio::spawn({
|
||||
let layer = layer.clone();
|
||||
async move {
|
||||
layer.flush().await;
|
||||
}
|
||||
});
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
assert!(!flush_task.is_finished());
|
||||
|
||||
match receiver.recv().await.expect("queued entry") {
|
||||
LogDbCommand::Entry(entry) => {
|
||||
assert_eq!(entry.message.as_deref(), Some("queued-before-flush"));
|
||||
}
|
||||
LogDbCommand::Flush(_) => panic!("expected queued entry"),
|
||||
}
|
||||
|
||||
match receiver.recv().await.expect("flush command") {
|
||||
LogDbCommand::Flush(reply) => {
|
||||
assert!(!flush_task.is_finished());
|
||||
let _ = reply.send(());
|
||||
}
|
||||
LogDbCommand::Entry(_) => panic!("expected flush command"),
|
||||
}
|
||||
|
||||
tokio::time::timeout(std::time::Duration::from_secs(1), &mut flush_task)
|
||||
.await
|
||||
.expect("flush task completes")
|
||||
.expect("flush task succeeds");
|
||||
}
|
||||
}
|
||||
86
akode-rs/state/src/log_db_failure_tests.rs
Normal file
86
akode-rs/state/src/log_db_failure_tests.rs
Normal file
@@ -0,0 +1,86 @@
|
||||
//! Regression coverage for flush diagnostics, recovery, and sink recursion prevention.
|
||||
|
||||
use akode_utils_absolute_path::test_support::PathExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
use tracing_subscriber::util::SubscriberInitExt;
|
||||
|
||||
use super::tests::SharedWriter;
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_batch_is_reported_once_and_later_writes_recover() {
|
||||
let codex_home =
|
||||
std::env::temp_dir().join(format!("codex-state-log-failure-{}", Uuid::new_v4()));
|
||||
let _cleanup = scopeguard::guard(codex_home.clone(), |codex_home| {
|
||||
let _ = std::fs::remove_dir_all(codex_home);
|
||||
});
|
||||
let sqlite = crate::SqliteConfig::new_for_testing(codex_home.as_path().abs());
|
||||
let runtime = StateRuntime::init(sqlite.clone(), "test-provider".to_string())
|
||||
.await
|
||||
.expect("initialize runtime");
|
||||
let pool = sqlite
|
||||
.open_read_write_pool(&sqlite.logs_db_path())
|
||||
.await
|
||||
.expect("open logs database");
|
||||
sqlx::query("CREATE TRIGGER fail_log_insert BEFORE INSERT ON logs BEGIN SELECT RAISE(ABORT, 'synthetic-secret'); END")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("install failure trigger");
|
||||
let diagnostics = SharedWriter::default();
|
||||
let layer = start(runtime.clone(), Arc::new(diagnostics.clone()));
|
||||
assert_eq!(layer.has_write_failure(), false);
|
||||
let writer = SharedWriter::default();
|
||||
let guard = tracing_subscriber::registry()
|
||||
.with(
|
||||
tracing_subscriber::fmt::layer()
|
||||
.with_writer(writer.clone())
|
||||
.without_time()
|
||||
.with_level(/*display_level*/ false)
|
||||
.with_target(/*display_target*/ false)
|
||||
.with_ansi(/*ansi*/ false)
|
||||
.with_filter(LevelFilter::ERROR),
|
||||
)
|
||||
// No diagnostic filter is needed: the diagnostic writer bypasses tracing.
|
||||
.with(layer.clone())
|
||||
.set_default();
|
||||
|
||||
tracing::info!("sensitive log body");
|
||||
layer.flush().await;
|
||||
assert_eq!(layer.has_write_failure(), true);
|
||||
let diagnostic = diagnostics.snapshot();
|
||||
assert_eq!(
|
||||
diagnostic.split_once(" ERROR ").unwrap().1,
|
||||
"failed to flush logs to SQLite error=\"constraint\" entries=1\n"
|
||||
);
|
||||
assert_eq!(writer.snapshot(), "");
|
||||
|
||||
// Reporting the first failure must not enqueue a second failing batch.
|
||||
layer.flush().await;
|
||||
assert_eq!(diagnostics.snapshot(), diagnostic);
|
||||
assert_eq!(writer.snapshot(), "");
|
||||
|
||||
sqlx::query("DROP TRIGGER fail_log_insert")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("remove failure trigger");
|
||||
tracing::info!("recovered log");
|
||||
layer.flush().await;
|
||||
assert_eq!(diagnostics.snapshot(), diagnostic);
|
||||
assert_eq!(writer.snapshot(), "");
|
||||
assert_eq!(layer.has_write_failure(), true);
|
||||
drop(guard);
|
||||
|
||||
let logs = runtime
|
||||
.query_logs(&crate::LogQuery::default())
|
||||
.await
|
||||
.expect("query logs");
|
||||
assert_eq!(
|
||||
logs.iter()
|
||||
.map(|log| log.message.as_deref())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![Some("recovered log")]
|
||||
);
|
||||
pool.close().await;
|
||||
runtime.close().await;
|
||||
}
|
||||
172
akode-rs/state/src/log_db_filter_tests.rs
Normal file
172
akode-rs/state/src/log_db_filter_tests.rs
Normal file
@@ -0,0 +1,172 @@
|
||||
use akode_utils_absolute_path::test_support::PathExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
use tracing_subscriber::util::SubscriberInitExt;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn sqlite_sink_filters_noisy_targets_without_dropping_useful_diagnostics() {
|
||||
let codex_home =
|
||||
std::env::temp_dir().join(format!("codex-state-log-db-filter-{}", Uuid::new_v4()));
|
||||
let _cleanup = scopeguard::guard(codex_home.clone(), |codex_home| {
|
||||
let _ = std::fs::remove_dir_all(codex_home);
|
||||
});
|
||||
let runtime = StateRuntime::init(
|
||||
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
|
||||
"test-provider".to_string(),
|
||||
)
|
||||
.await
|
||||
.expect("initialize runtime");
|
||||
let layer = start(
|
||||
runtime.clone(),
|
||||
Arc::new(super::tests::SharedWriter::default()),
|
||||
);
|
||||
|
||||
let guard = tracing_subscriber::registry()
|
||||
.with(layer.clone().with_filter(default_filter()))
|
||||
.set_default();
|
||||
|
||||
tracing::trace!(target: "opentelemetry_sdk", "dropped-trace");
|
||||
tracing::debug!(target: "opentelemetry_sdk", "dropped-debug");
|
||||
tracing::info!(target: "opentelemetry_sdk", "retained-info");
|
||||
tracing::warn!(target: "sqlx::query", "dropped-slow-query-warning");
|
||||
tracing::warn!(target: "sqlx::pool::acquire", "dropped-slow-acquire-warning");
|
||||
tracing::warn!(target: "sqlx::other", "dropped-sqlx-warning");
|
||||
tracing::info!(target: "sqlx_application", "retained-unrelated-target");
|
||||
tracing::trace!(target: "h2::proto::streams", "dropped-http2-trace");
|
||||
tracing::debug!(target: "tonic::transport::channel", "dropped-grpc-transport-debug");
|
||||
tracing::debug!(target: "tower::buffer::worker", "dropped-grpc-buffer-debug");
|
||||
tracing::warn!(
|
||||
target: "h2::proto::ping_pong",
|
||||
"recv PING ack that we never sent: {:?}",
|
||||
"synthetic-ack"
|
||||
);
|
||||
tracing::warn!(target: "h2::proto::ping_pong", "retained-http2-ping-warning");
|
||||
tracing::warn!(target: "h2::proto::streams", "retained-http2-warning");
|
||||
tracing::debug!(target: "rmcp::transport", "dropped-rmcp-debug");
|
||||
tracing::info!(target: "rmcp::transport", "retained-rmcp-info");
|
||||
tracing::trace!(target: "tokio_graceful::guard", "dropped-guard-trace");
|
||||
tracing::debug!(target: "tokio_graceful::guard", "retained-guard-debug");
|
||||
tracing::trace!(target: "tokio_graceful::trigger", "dropped-trigger-trace");
|
||||
tracing::debug!(target: "tokio_graceful::trigger", "retained-trigger-debug");
|
||||
tracing::trace!(target: "tokio_graceful::shutdown", "retained-shutdown-trace");
|
||||
tracing::debug!(
|
||||
target: "akode_rmcp_client::oauth",
|
||||
"dropped-codex-rmcp-client-debug"
|
||||
);
|
||||
tracing::info!(
|
||||
target: "akode_rmcp_client::oauth",
|
||||
"retained-codex-rmcp-client-info"
|
||||
);
|
||||
tracing::trace!(target: "akode_http_client::transport", "dropped-request-body");
|
||||
tracing::debug!(target: "akode_http_client::transport", "retained-request-diagnostic");
|
||||
tracing::trace!(target: "akode_api::sse", "dropped-sse-parent");
|
||||
tracing::trace!(target: "akode_api::sse::responses", "dropped-sse-payload");
|
||||
tracing::debug!(target: "akode_api::sse::responses", "retained-sse-diagnostic");
|
||||
tracing::trace!(target: "akode_state", "retained-trace");
|
||||
tracing::trace!(
|
||||
target: "akode_tui::streaming::controller",
|
||||
"dropped-controller-trace"
|
||||
);
|
||||
tracing::debug!(
|
||||
target: "akode_tui::streaming::controller",
|
||||
"retained-controller-debug"
|
||||
);
|
||||
tracing::trace!(
|
||||
target: "akode_tui::streaming::table_holdback",
|
||||
"dropped-table-holdback-trace"
|
||||
);
|
||||
tracing::debug!(
|
||||
target: "akode_tui::streaming::table_holdback",
|
||||
"retained-table-holdback-debug"
|
||||
);
|
||||
tracing::trace!(
|
||||
target: "akode_tui::streaming::commit_tick",
|
||||
"retained-commit-tick-trace"
|
||||
);
|
||||
tracing::trace!(
|
||||
target: "akode_api::responses_websocket_timing",
|
||||
payload = "complete timing payload",
|
||||
"dropped-websocket-timing"
|
||||
);
|
||||
|
||||
layer.flush().await;
|
||||
drop(guard);
|
||||
|
||||
let logs = runtime
|
||||
.query_logs(&crate::LogQuery::default())
|
||||
.await
|
||||
.expect("query logs after flush");
|
||||
assert_eq!(
|
||||
logs.iter()
|
||||
.map(|row| (
|
||||
row.level.as_str(),
|
||||
row.target.as_str(),
|
||||
row.message.as_deref()
|
||||
))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
("INFO", "opentelemetry_sdk", Some("retained-info")),
|
||||
(
|
||||
"INFO",
|
||||
"sqlx_application",
|
||||
Some("retained-unrelated-target")
|
||||
),
|
||||
(
|
||||
"WARN",
|
||||
"h2::proto::ping_pong",
|
||||
Some("retained-http2-ping-warning")
|
||||
),
|
||||
("WARN", "h2::proto::streams", Some("retained-http2-warning")),
|
||||
("INFO", "rmcp::transport", Some("retained-rmcp-info")),
|
||||
(
|
||||
"DEBUG",
|
||||
"tokio_graceful::guard",
|
||||
Some("retained-guard-debug")
|
||||
),
|
||||
(
|
||||
"DEBUG",
|
||||
"tokio_graceful::trigger",
|
||||
Some("retained-trigger-debug")
|
||||
),
|
||||
(
|
||||
"TRACE",
|
||||
"tokio_graceful::shutdown",
|
||||
Some("retained-shutdown-trace")
|
||||
),
|
||||
(
|
||||
"INFO",
|
||||
"akode_rmcp_client::oauth",
|
||||
Some("retained-codex-rmcp-client-info")
|
||||
),
|
||||
(
|
||||
"DEBUG",
|
||||
"akode_http_client::transport",
|
||||
Some("retained-request-diagnostic")
|
||||
),
|
||||
(
|
||||
"DEBUG",
|
||||
"akode_api::sse::responses",
|
||||
Some("retained-sse-diagnostic")
|
||||
),
|
||||
("TRACE", "akode_state", Some("retained-trace")),
|
||||
(
|
||||
"DEBUG",
|
||||
"akode_tui::streaming::controller",
|
||||
Some("retained-controller-debug"),
|
||||
),
|
||||
(
|
||||
"DEBUG",
|
||||
"akode_tui::streaming::table_holdback",
|
||||
Some("retained-table-holdback-debug"),
|
||||
),
|
||||
(
|
||||
"TRACE",
|
||||
"akode_tui::streaming::commit_tick",
|
||||
Some("retained-commit-tick-trace"),
|
||||
),
|
||||
]
|
||||
);
|
||||
}
|
||||
147
akode-rs/state/src/log_write_telemetry_tests.rs
Normal file
147
akode-rs/state/src/log_write_telemetry_tests.rs
Normal file
@@ -0,0 +1,147 @@
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::DbTelemetry;
|
||||
use super::record_log_queue_drop;
|
||||
use super::record_log_write;
|
||||
use crate::LOG_QUEUE_DROPPED_METRIC;
|
||||
use crate::LOG_WRITE_BYTES_METRIC;
|
||||
use crate::LOG_WRITE_DURATION_METRIC;
|
||||
use crate::LOG_WRITE_ENTRIES_METRIC;
|
||||
use crate::LOG_WRITE_MAX_ENTRY_BYTES_METRIC;
|
||||
use crate::LOG_WRITE_METRIC;
|
||||
use crate::LogEntry;
|
||||
|
||||
type MetricEvent = (String, i64, Vec<(String, String)>);
|
||||
|
||||
#[derive(Default)]
|
||||
struct TestTelemetry(Mutex<Vec<MetricEvent>>);
|
||||
|
||||
impl TestTelemetry {
|
||||
fn record(&self, name: &str, value: i64, tags: &[(&str, &str)]) {
|
||||
self.0.lock().expect("telemetry lock").push((
|
||||
name.to_string(),
|
||||
value,
|
||||
tags.iter()
|
||||
.map(|(key, value)| ((*key).to_string(), (*value).to_string()))
|
||||
.collect(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
impl DbTelemetry for TestTelemetry {
|
||||
fn counter(&self, name: &str, inc: i64, tags: &[(&str, &str)]) {
|
||||
self.record(name, inc, tags);
|
||||
}
|
||||
|
||||
fn histogram(&self, name: &str, value: i64, tags: &[(&str, &str)]) {
|
||||
self.record(name, value, tags);
|
||||
}
|
||||
|
||||
fn record_duration(&self, name: &str, duration: Duration, tags: &[(&str, &str)]) {
|
||||
self.record(name, duration.as_millis() as i64, tags);
|
||||
}
|
||||
}
|
||||
|
||||
fn log_entry(message: &str, feedback_log_body: Option<&str>) -> LogEntry {
|
||||
LogEntry {
|
||||
ts: 1,
|
||||
ts_nanos: 2,
|
||||
level: "INFO".to_string(),
|
||||
target: "t".to_string(),
|
||||
message: Some(message.to_string()),
|
||||
feedback_log_body: feedback_log_body.map(str::to_string),
|
||||
thread_id: None,
|
||||
process_uuid: None,
|
||||
module_path: Some("m".to_string()),
|
||||
file: Some("f".to_string()),
|
||||
line: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn expected_events(metrics: &[(&str, i64)], tags: &[(&str, &str)]) -> Vec<MetricEvent> {
|
||||
metrics
|
||||
.iter()
|
||||
.map(|(name, value)| {
|
||||
(
|
||||
(*name).to_string(),
|
||||
*value,
|
||||
tags.iter()
|
||||
.map(|(key, value)| ((*key).to_string(), (*value).to_string()))
|
||||
.collect(),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn records_successful_log_write_duration_batch_size_and_largest_entry() {
|
||||
let telemetry = TestTelemetry::default();
|
||||
let entries = [
|
||||
log_entry("abc", /*feedback_log_body*/ None),
|
||||
log_entry("ignored", Some("longer")),
|
||||
];
|
||||
|
||||
record_log_write(
|
||||
Some(&telemetry),
|
||||
Duration::from_millis(17),
|
||||
&entries,
|
||||
&Ok(()),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
*telemetry.0.lock().expect("telemetry lock"),
|
||||
expected_events(
|
||||
&[
|
||||
(LOG_WRITE_METRIC, 1),
|
||||
(LOG_WRITE_DURATION_METRIC, 17),
|
||||
(LOG_WRITE_BYTES_METRIC, 23),
|
||||
(LOG_WRITE_ENTRIES_METRIC, 2),
|
||||
(LOG_WRITE_MAX_ENTRY_BYTES_METRIC, 13),
|
||||
],
|
||||
&[("status", "success"), ("error", "none")],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn records_failed_log_write_with_bounded_sqlite_error() {
|
||||
let telemetry = TestTelemetry::default();
|
||||
let entries = [log_entry("abc", /*feedback_log_body*/ None)];
|
||||
let result = Err(anyhow::Error::from(sqlx::Error::PoolTimedOut));
|
||||
|
||||
record_log_write(
|
||||
Some(&telemetry),
|
||||
Duration::from_millis(35),
|
||||
&entries,
|
||||
&result,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
*telemetry.0.lock().expect("telemetry lock"),
|
||||
expected_events(
|
||||
&[
|
||||
(LOG_WRITE_METRIC, 1),
|
||||
(LOG_WRITE_DURATION_METRIC, 35),
|
||||
(LOG_WRITE_BYTES_METRIC, 10),
|
||||
(LOG_WRITE_ENTRIES_METRIC, 1),
|
||||
(LOG_WRITE_MAX_ENTRY_BYTES_METRIC, 10),
|
||||
],
|
||||
&[("status", "failed"), ("error", "pool_timeout")],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn records_queue_drop_reason() {
|
||||
let telemetry = TestTelemetry::default();
|
||||
|
||||
record_log_queue_drop("full", Some(&telemetry));
|
||||
|
||||
assert_eq!(
|
||||
*telemetry.0.lock().expect("telemetry lock"),
|
||||
expected_events(&[(LOG_QUEUE_DROPPED_METRIC, 1)], &[("reason", "full")]),
|
||||
);
|
||||
}
|
||||
123
akode-rs/state/src/migrations.rs
Normal file
123
akode-rs/state/src/migrations.rs
Normal file
@@ -0,0 +1,123 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::sqlite::SqliteWriteQueryExt;
|
||||
use sqlx::migrate::Migrator;
|
||||
use sqlx_sqlite::SqlitePool;
|
||||
|
||||
pub(crate) static STATE_MIGRATOR: Migrator = sqlx_macros::migrate!("./migrations");
|
||||
pub(crate) static LOGS_MIGRATOR: Migrator = sqlx_macros::migrate!("./logs_migrations");
|
||||
pub(crate) static GOALS_MIGRATOR: Migrator = sqlx_macros::migrate!("./goals_migrations");
|
||||
pub(crate) static MEMORIES_MIGRATOR: Migrator = sqlx_macros::migrate!("./memory_migrations");
|
||||
pub(crate) static QUEUE_MIGRATOR: Migrator = sqlx_macros::migrate!("./queue_migrations");
|
||||
pub(crate) static THREAD_HISTORY_MIGRATOR: Migrator =
|
||||
sqlx_macros::migrate!("./thread_history_migrations");
|
||||
|
||||
/// Allow an older Codex binary to open a database that has already been
|
||||
/// migrated by a newer binary running in parallel.
|
||||
///
|
||||
/// We intentionally ignore applied migration versions that are newer than the
|
||||
/// embedded migration set. Known migration versions are still validated by
|
||||
/// checksum, so this only relaxes the "database is ahead of me" case.
|
||||
fn runtime_migrator(base: &'static Migrator) -> Migrator {
|
||||
Migrator {
|
||||
migrations: Cow::Borrowed(base.migrations.as_ref()),
|
||||
ignore_missing: true,
|
||||
locking: base.locking,
|
||||
no_tx: base.no_tx,
|
||||
table_name: base.table_name.clone(),
|
||||
create_schemas: base.create_schemas.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn runtime_state_migrator() -> Migrator {
|
||||
runtime_migrator(&STATE_MIGRATOR)
|
||||
}
|
||||
|
||||
pub(crate) fn runtime_logs_migrator() -> Migrator {
|
||||
runtime_migrator(&LOGS_MIGRATOR)
|
||||
}
|
||||
|
||||
pub(crate) fn runtime_goals_migrator() -> Migrator {
|
||||
runtime_migrator(&GOALS_MIGRATOR)
|
||||
}
|
||||
|
||||
pub(crate) fn runtime_memories_migrator() -> Migrator {
|
||||
runtime_migrator(&MEMORIES_MIGRATOR)
|
||||
}
|
||||
|
||||
pub(crate) fn runtime_queue_migrator() -> Migrator {
|
||||
runtime_migrator(&QUEUE_MIGRATOR)
|
||||
}
|
||||
|
||||
// The paginated history projector will call this when it takes ownership of opening the database.
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn runtime_thread_history_migrator() -> Migrator {
|
||||
runtime_migrator(&THREAD_HISTORY_MIGRATOR)
|
||||
}
|
||||
|
||||
pub(crate) async fn repair_legacy_recency_migration_version(
|
||||
pool: &SqlitePool,
|
||||
migrator: &Migrator,
|
||||
) -> anyhow::Result<()> {
|
||||
let Some(recency_migration) = migrator
|
||||
.migrations
|
||||
.iter()
|
||||
.find(|migration| migration.version == 39)
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let migrations_table_exists = sqlx::query_scalar::<_, i64>(
|
||||
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = '_sqlx_migrations'",
|
||||
)
|
||||
.fetch_optional(pool)
|
||||
.await?
|
||||
.is_some();
|
||||
if !migrations_table_exists {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let legacy_recency_needs_repair = sqlx::query_scalar::<_, i64>(
|
||||
r#"
|
||||
SELECT 1
|
||||
FROM _sqlx_migrations
|
||||
WHERE version = ?
|
||||
AND checksum = ?
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM _sqlx_migrations WHERE version = ?
|
||||
)
|
||||
"#,
|
||||
)
|
||||
.bind(38_i64)
|
||||
.bind(recency_migration.checksum.as_ref())
|
||||
.bind(recency_migration.version)
|
||||
.fetch_optional(pool)
|
||||
.await?
|
||||
.is_some();
|
||||
if !legacy_recency_needs_repair {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
sqlx::query(
|
||||
r#"
|
||||
UPDATE _sqlx_migrations
|
||||
SET version = ?, description = ?
|
||||
WHERE version = ?
|
||||
AND checksum = ?
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM _sqlx_migrations WHERE version = ?
|
||||
)
|
||||
"#,
|
||||
)
|
||||
.bind(recency_migration.version)
|
||||
.bind(recency_migration.description.as_ref())
|
||||
.bind(38_i64)
|
||||
.bind(recency_migration.checksum.as_ref())
|
||||
.bind(recency_migration.version)
|
||||
.execute_with_busy_retry(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "migrations_tests.rs"]
|
||||
mod tests;
|
||||
1108
akode-rs/state/src/migrations_tests.rs
Normal file
1108
akode-rs/state/src/migrations_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
73
akode-rs/state/src/model/backfill_state.rs
Normal file
73
akode-rs/state/src/model/backfill_state.rs
Normal file
@@ -0,0 +1,73 @@
|
||||
use anyhow::Result;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use sqlx::Row;
|
||||
use sqlx::sqlite::SqliteRow;
|
||||
|
||||
/// Persisted lifecycle state for rollout metadata backfill.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct BackfillState {
|
||||
/// Current lifecycle status.
|
||||
pub status: BackfillStatus,
|
||||
/// Last processed rollout watermark.
|
||||
pub last_watermark: Option<String>,
|
||||
/// Last successful completion time.
|
||||
pub last_success_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
impl Default for BackfillState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
status: BackfillStatus::Pending,
|
||||
last_watermark: None,
|
||||
last_success_at: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BackfillState {
|
||||
pub(crate) fn try_from_row(row: &SqliteRow) -> Result<Self> {
|
||||
let status: String = row.try_get("status")?;
|
||||
let last_success_at = row
|
||||
.try_get::<Option<i64>, _>("last_success_at")?
|
||||
.map(epoch_seconds_to_datetime)
|
||||
.transpose()?;
|
||||
Ok(Self {
|
||||
status: BackfillStatus::parse(status.as_str())?,
|
||||
last_watermark: row.try_get("last_watermark")?,
|
||||
last_success_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Backfill lifecycle status.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BackfillStatus {
|
||||
Pending,
|
||||
Running,
|
||||
Complete,
|
||||
}
|
||||
|
||||
impl BackfillStatus {
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
BackfillStatus::Pending => "pending",
|
||||
BackfillStatus::Running => "running",
|
||||
BackfillStatus::Complete => "complete",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(value: &str) -> Result<Self> {
|
||||
match value {
|
||||
"pending" => Ok(Self::Pending),
|
||||
"running" => Ok(Self::Running),
|
||||
"complete" => Ok(Self::Complete),
|
||||
_ => Err(anyhow::anyhow!("invalid backfill status: {value}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn epoch_seconds_to_datetime(secs: i64) -> Result<DateTime<Utc>> {
|
||||
DateTime::<Utc>::from_timestamp(secs, 0)
|
||||
.ok_or_else(|| anyhow::anyhow!("invalid unix timestamp: {secs}"))
|
||||
}
|
||||
11
akode-rs/state/src/model/graph.rs
Normal file
11
akode-rs/state/src/model/graph.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
use strum::AsRefStr;
|
||||
use strum::Display;
|
||||
use strum::EnumString;
|
||||
|
||||
/// Status attached to a directional thread-spawn edge.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, AsRefStr, Display, EnumString)]
|
||||
#[strum(serialize_all = "snake_case")]
|
||||
pub enum DirectionalThreadSpawnEdgeStatus {
|
||||
Open,
|
||||
Closed,
|
||||
}
|
||||
57
akode-rs/state/src/model/log.rs
Normal file
57
akode-rs/state/src/model/log.rs
Normal file
@@ -0,0 +1,57 @@
|
||||
use serde::Serialize;
|
||||
use sqlx_macros::FromRow;
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct LogEntry {
|
||||
pub ts: i64,
|
||||
pub ts_nanos: i64,
|
||||
pub level: String,
|
||||
pub target: String,
|
||||
pub message: Option<String>,
|
||||
pub feedback_log_body: Option<String>,
|
||||
pub thread_id: Option<String>,
|
||||
pub process_uuid: Option<String>,
|
||||
pub module_path: Option<String>,
|
||||
pub file: Option<String>,
|
||||
pub line: Option<i64>,
|
||||
}
|
||||
|
||||
impl LogEntry {
|
||||
pub(crate) fn estimated_bytes(&self) -> i64 {
|
||||
let feedback_log_body = self.feedback_log_body.as_ref().or(self.message.as_ref());
|
||||
feedback_log_body.map_or(0, String::len) as i64
|
||||
+ self.level.len() as i64
|
||||
+ self.target.len() as i64
|
||||
+ self.module_path.as_ref().map_or(0, String::len) as i64
|
||||
+ self.file.as_ref().map_or(0, String::len) as i64
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, FromRow)]
|
||||
pub struct LogRow {
|
||||
pub id: i64,
|
||||
pub ts: i64,
|
||||
pub ts_nanos: i64,
|
||||
pub level: String,
|
||||
pub target: String,
|
||||
pub message: Option<String>,
|
||||
pub thread_id: Option<String>,
|
||||
pub process_uuid: Option<String>,
|
||||
pub file: Option<String>,
|
||||
pub line: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct LogQuery {
|
||||
pub levels_upper: Vec<String>,
|
||||
pub from_ts: Option<i64>,
|
||||
pub to_ts: Option<i64>,
|
||||
pub module_like: Vec<String>,
|
||||
pub file_like: Vec<String>,
|
||||
pub thread_ids: Vec<String>,
|
||||
pub search: Option<String>,
|
||||
pub include_threadless: bool,
|
||||
pub after_id: Option<i64>,
|
||||
pub limit: Option<usize>,
|
||||
pub descending: bool,
|
||||
}
|
||||
69
akode-rs/state/src/model/memories.rs
Normal file
69
akode-rs/state/src/model/memories.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use akode_protocol::ThreadId;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::ThreadMetadata;
|
||||
|
||||
/// Stored stage-1 memory extraction output for a single thread.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Stage1Output {
|
||||
pub thread_id: ThreadId,
|
||||
pub rollout_path: PathBuf,
|
||||
pub source_updated_at: DateTime<Utc>,
|
||||
pub raw_memory: String,
|
||||
pub rollout_summary: String,
|
||||
pub rollout_slug: Option<String>,
|
||||
pub cwd: PathBuf,
|
||||
pub git_branch: Option<String>,
|
||||
pub generated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// Result of trying to claim a stage-1 memory extraction job.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Stage1JobClaimOutcome {
|
||||
/// The caller owns the job and should continue with extraction.
|
||||
Claimed { ownership_token: String },
|
||||
/// Existing output is already newer than or equal to the source rollout.
|
||||
SkippedUpToDate,
|
||||
/// Another worker currently owns a fresh lease for this job.
|
||||
SkippedRunning,
|
||||
/// The job is in backoff and should not be retried yet.
|
||||
SkippedRetryBackoff,
|
||||
/// The job has exhausted retries and should not be retried automatically.
|
||||
SkippedRetryExhausted,
|
||||
}
|
||||
|
||||
/// Claimed stage-1 job with thread metadata.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Stage1JobClaim {
|
||||
pub thread: ThreadMetadata,
|
||||
pub ownership_token: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Stage1StartupClaimParams<'a> {
|
||||
pub scan_limit: usize,
|
||||
pub max_claimed: usize,
|
||||
pub max_age_days: i64,
|
||||
pub min_rollout_idle_hours: i64,
|
||||
pub allowed_sources: &'a [String],
|
||||
pub lease_seconds: i64,
|
||||
}
|
||||
|
||||
/// Result of trying to claim a phase-2 consolidation job.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Phase2JobClaimOutcome {
|
||||
/// The caller owns the global lock and may inspect the memory workspace.
|
||||
Claimed {
|
||||
ownership_token: String,
|
||||
/// Snapshot of `input_watermark` at claim time.
|
||||
input_watermark: i64,
|
||||
},
|
||||
/// The global job is in retry backoff.
|
||||
SkippedRetryUnavailable,
|
||||
/// The global job completed recently enough that consolidation is cooling down.
|
||||
SkippedCooldown,
|
||||
/// Another worker currently owns a fresh global consolidation lease.
|
||||
SkippedRunning,
|
||||
}
|
||||
59
akode-rs/state/src/model/mod.rs
Normal file
59
akode-rs/state/src/model/mod.rs
Normal file
@@ -0,0 +1,59 @@
|
||||
mod backfill_state;
|
||||
mod graph;
|
||||
mod log;
|
||||
mod memories;
|
||||
mod project;
|
||||
mod queued_item;
|
||||
mod rollout_migration_state;
|
||||
mod thread_attachment;
|
||||
mod thread_goal;
|
||||
mod thread_metadata;
|
||||
|
||||
pub use backfill_state::BackfillState;
|
||||
pub use backfill_state::BackfillStatus;
|
||||
pub use graph::DirectionalThreadSpawnEdgeStatus;
|
||||
pub use log::LogEntry;
|
||||
pub use log::LogQuery;
|
||||
pub use log::LogRow;
|
||||
pub use memories::Phase2JobClaimOutcome;
|
||||
pub use memories::Stage1JobClaim;
|
||||
pub use memories::Stage1JobClaimOutcome;
|
||||
pub use memories::Stage1Output;
|
||||
pub use memories::Stage1StartupClaimParams;
|
||||
pub use project::CreatedProject;
|
||||
pub use project::Project;
|
||||
pub use project::ProjectRoot;
|
||||
pub use project::ProjectSortKey;
|
||||
pub use project::ProjectsPage;
|
||||
pub use queued_item::QueuedUserSubmissionRecord;
|
||||
pub use rollout_migration_state::RolloutMigrationCursor;
|
||||
pub use rollout_migration_state::RolloutMigrationSkippedRollout;
|
||||
pub use rollout_migration_state::RolloutMigrationState;
|
||||
pub use thread_attachment::AddThreadAttachmentOutcome;
|
||||
pub use thread_attachment::RemoveThreadAttachmentOutcome;
|
||||
pub use thread_attachment::ThreadAttachment;
|
||||
pub use thread_attachment::ThreadAttachmentArchiveFilter;
|
||||
pub use thread_attachment::ThreadAttachmentOwner;
|
||||
pub use thread_attachment::ThreadAttachmentOwnerPage;
|
||||
pub use thread_attachment::ThreadAttachmentPage;
|
||||
pub use thread_goal::ThreadGoal;
|
||||
pub use thread_goal::ThreadGoalStatus;
|
||||
pub use thread_metadata::Anchor;
|
||||
pub use thread_metadata::BackfillStats;
|
||||
pub use thread_metadata::ExtractionOutcome;
|
||||
pub use thread_metadata::SortDirection;
|
||||
pub use thread_metadata::SortKey;
|
||||
pub use thread_metadata::ThreadMetadata;
|
||||
pub use thread_metadata::ThreadMetadataBuilder;
|
||||
pub use thread_metadata::ThreadRelationFilter;
|
||||
pub use thread_metadata::ThreadSection;
|
||||
pub use thread_metadata::ThreadSectionAppearance;
|
||||
pub use thread_metadata::ThreadSectionsPage;
|
||||
pub use thread_metadata::ThreadsPage;
|
||||
|
||||
pub(crate) use thread_goal::ThreadGoalRow;
|
||||
pub(crate) use thread_metadata::ThreadRow;
|
||||
pub(crate) use thread_metadata::anchor_from_item;
|
||||
pub(crate) use thread_metadata::datetime_to_epoch_millis;
|
||||
pub(crate) use thread_metadata::datetime_to_epoch_seconds;
|
||||
pub(crate) use thread_metadata::epoch_millis_to_datetime;
|
||||
39
akode-rs/state/src/model/project.rs
Normal file
39
akode-rs/state/src/model/project.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ProjectRoot {
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Project {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub roots: Vec<ProjectRoot>,
|
||||
pub metadata: BTreeMap<String, String>,
|
||||
pub position: i64,
|
||||
pub created_at_ms: i64,
|
||||
pub updated_at_ms: i64,
|
||||
pub recency_at_ms: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ProjectSortKey {
|
||||
Position,
|
||||
RecencyAt,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CreatedProject {
|
||||
pub project: Project,
|
||||
pub created: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProjectsPage {
|
||||
pub projects: Vec<Project>,
|
||||
pub next_cursor: Option<String>,
|
||||
}
|
||||
22
akode-rs/state/src/model/queued_item.rs
Normal file
22
akode-rs/state/src/model/queued_item.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
use anyhow::Result;
|
||||
use akode_protocol::ThreadId;
|
||||
use sqlx::Row;
|
||||
use sqlx::sqlite::SqliteRow;
|
||||
|
||||
/// One durable, ordered user submission for a thread.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct QueuedUserSubmissionRecord {
|
||||
pub id: String,
|
||||
pub thread_id: ThreadId,
|
||||
pub payload: String,
|
||||
}
|
||||
|
||||
impl QueuedUserSubmissionRecord {
|
||||
pub(crate) fn try_from_row(row: &SqliteRow) -> Result<Self> {
|
||||
Ok(Self {
|
||||
id: row.try_get("id")?,
|
||||
thread_id: ThreadId::try_from(row.try_get::<String, _>("thread_id")?)?,
|
||||
payload: row.try_get("payload_json")?,
|
||||
})
|
||||
}
|
||||
}
|
||||
67
akode-rs/state/src/model/rollout_migration_state.rs
Normal file
67
akode-rs/state/src/model/rollout_migration_state.rs
Normal file
@@ -0,0 +1,67 @@
|
||||
//! SQLite-backed bookkeeping types shared by rollout migrations.
|
||||
//!
|
||||
//! A migration cursor says “everything through this creation-ordered thread was checked.” A
|
||||
//! skipped rollout stores enough file fingerprint information to tell whether a previously
|
||||
//! unmigratable rollout is still unchanged.
|
||||
//!
|
||||
//! These types are intentionally generic so future rollout migrations can reuse the same state
|
||||
//! shape without depending on legacy -> paginated policy.
|
||||
|
||||
use anyhow::Result;
|
||||
use sqlx::Row;
|
||||
use sqlx::sqlite::SqliteRow;
|
||||
|
||||
/// Creation-ordered thread frontier checked by one rollout migration.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct RolloutMigrationCursor {
|
||||
pub thread_created_at: i64,
|
||||
pub thread_id: String,
|
||||
}
|
||||
|
||||
/// Persisted progress for one rollout migration.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RolloutMigrationState {
|
||||
pub last_checked_thread: Option<RolloutMigrationCursor>,
|
||||
}
|
||||
|
||||
impl RolloutMigrationState {
|
||||
pub(crate) fn try_from_row(row: &SqliteRow) -> Result<Self> {
|
||||
let thread_created_at = row.try_get("last_checked_thread_created_at")?;
|
||||
let thread_id = row.try_get("last_checked_thread_id")?;
|
||||
let last_checked_thread = match (thread_created_at, thread_id) {
|
||||
(Some(thread_created_at), Some(thread_id)) => Some(RolloutMigrationCursor {
|
||||
thread_created_at,
|
||||
thread_id,
|
||||
}),
|
||||
(None, None) => None,
|
||||
_ => {
|
||||
return Err(anyhow::anyhow!(
|
||||
"rollout migration state has incomplete last checked thread"
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
last_checked_thread,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// An unchanged rollout that one migration can safely skip.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RolloutMigrationSkippedRollout {
|
||||
pub rollout_path: String,
|
||||
pub rollout_size_bytes: i64,
|
||||
pub rollout_modified_at_ns: i64,
|
||||
pub skip_reason: String,
|
||||
}
|
||||
|
||||
impl RolloutMigrationSkippedRollout {
|
||||
pub(crate) fn try_from_row(row: &SqliteRow) -> Result<Self> {
|
||||
Ok(Self {
|
||||
rollout_path: row.try_get("rollout_path")?,
|
||||
rollout_size_bytes: row.try_get("rollout_size_bytes")?,
|
||||
rollout_modified_at_ns: row.try_get("rollout_modified_at_ns")?,
|
||||
skip_reason: row.try_get("skip_reason")?,
|
||||
})
|
||||
}
|
||||
}
|
||||
70
akode-rs/state/src/model/thread_attachment.rs
Normal file
70
akode-rs/state/src/model/thread_attachment.rs
Normal file
@@ -0,0 +1,70 @@
|
||||
//! Thread attachment records and outcomes; membership changes independently of resource contents.
|
||||
|
||||
use akode_protocol::ThreadId;
|
||||
use serde_json::Value;
|
||||
|
||||
/// A bounded attachment durably associated with one thread.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ThreadAttachment {
|
||||
/// Stable, server-assigned UUIDv7 attachment identity.
|
||||
pub id: String,
|
||||
/// Thread that owns this attachment.
|
||||
pub thread_id: ThreadId,
|
||||
/// Client-defined attachment category.
|
||||
pub attachment_type: String,
|
||||
/// Client-defined stable identity within the owning thread and attachment category.
|
||||
pub identity_key: String,
|
||||
/// Bounded, client-defined attachment metadata.
|
||||
pub payload: Value,
|
||||
/// Integer Unix timestamp in seconds when the attachment was attached.
|
||||
pub created_at: i64,
|
||||
}
|
||||
|
||||
/// Result of attaching one uniquely identified thread attachment.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum AddThreadAttachmentOutcome {
|
||||
/// A new durable attachment was created.
|
||||
Created(ThreadAttachment),
|
||||
/// The attachment was already attached; its payload and creation time are unchanged.
|
||||
Existing(ThreadAttachment),
|
||||
}
|
||||
|
||||
/// Result of removing a thread attachment.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RemoveThreadAttachmentOutcome {
|
||||
/// An attached attachment was removed.
|
||||
Removed(ThreadAttachment),
|
||||
/// No attachment with the requested identity was attached.
|
||||
NotFound,
|
||||
}
|
||||
|
||||
/// One deterministically ordered page of attachments across selected threads.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ThreadAttachmentPage {
|
||||
/// Attachments ordered by thread identity, creation time, and attachment identity.
|
||||
pub attachments: Vec<ThreadAttachment>,
|
||||
/// Opaque cursor for the next page, or `None` when the selection is exhausted.
|
||||
pub next_cursor: Option<String>,
|
||||
}
|
||||
|
||||
/// Selects attachment owners by their persisted archive state.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ThreadAttachmentArchiveFilter {
|
||||
All,
|
||||
NonArchived,
|
||||
Archived,
|
||||
}
|
||||
|
||||
/// A thread whose current attachment membership contains the requested resource.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ThreadAttachmentOwner {
|
||||
pub thread_id: ThreadId,
|
||||
pub archived: bool,
|
||||
}
|
||||
|
||||
/// One page of attachment owners, ordered by thread ID.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ThreadAttachmentOwnerPage {
|
||||
pub threads: Vec<ThreadAttachmentOwner>,
|
||||
pub next_cursor: Option<String>,
|
||||
}
|
||||
117
akode-rs/state/src/model/thread_goal.rs
Normal file
117
akode-rs/state/src/model/thread_goal.rs
Normal file
@@ -0,0 +1,117 @@
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use akode_protocol::ThreadId;
|
||||
use serde::Serialize;
|
||||
use sqlx::Row;
|
||||
use sqlx::sqlite::SqliteRow;
|
||||
|
||||
use super::epoch_millis_to_datetime;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ThreadGoalStatus {
|
||||
Active,
|
||||
Paused,
|
||||
Blocked,
|
||||
UsageLimited,
|
||||
BudgetLimited,
|
||||
Complete,
|
||||
}
|
||||
|
||||
impl ThreadGoalStatus {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Active => "active",
|
||||
Self::Paused => "paused",
|
||||
Self::Blocked => "blocked",
|
||||
Self::UsageLimited => "usage_limited",
|
||||
Self::BudgetLimited => "budget_limited",
|
||||
Self::Complete => "complete",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_active(self) -> bool {
|
||||
self == Self::Active
|
||||
}
|
||||
|
||||
pub fn is_terminal(self) -> bool {
|
||||
matches!(self, Self::BudgetLimited | Self::Complete)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&str> for ThreadGoalStatus {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(value: &str) -> Result<Self> {
|
||||
match value {
|
||||
"active" => Ok(Self::Active),
|
||||
"paused" => Ok(Self::Paused),
|
||||
"blocked" => Ok(Self::Blocked),
|
||||
"usage_limited" => Ok(Self::UsageLimited),
|
||||
"budget_limited" => Ok(Self::BudgetLimited),
|
||||
"complete" => Ok(Self::Complete),
|
||||
other => Err(anyhow!("unknown thread goal status `{other}`")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ThreadGoal {
|
||||
pub thread_id: ThreadId,
|
||||
pub goal_id: String,
|
||||
pub objective: String,
|
||||
pub status: ThreadGoalStatus,
|
||||
pub token_budget: Option<i64>,
|
||||
pub tokens_used: i64,
|
||||
pub time_used_seconds: i64,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
pub(crate) struct ThreadGoalRow {
|
||||
pub thread_id: String,
|
||||
pub goal_id: String,
|
||||
pub objective: String,
|
||||
pub status: String,
|
||||
pub token_budget: Option<i64>,
|
||||
pub tokens_used: i64,
|
||||
pub time_used_seconds: i64,
|
||||
pub created_at_ms: i64,
|
||||
pub updated_at_ms: i64,
|
||||
}
|
||||
|
||||
impl ThreadGoalRow {
|
||||
pub(crate) fn try_from_row(row: &SqliteRow) -> Result<Self> {
|
||||
Ok(Self {
|
||||
thread_id: row.try_get("thread_id")?,
|
||||
goal_id: row.try_get("goal_id")?,
|
||||
objective: row.try_get("objective")?,
|
||||
status: row.try_get("status")?,
|
||||
token_budget: row.try_get("token_budget")?,
|
||||
tokens_used: row.try_get("tokens_used")?,
|
||||
time_used_seconds: row.try_get("time_used_seconds")?,
|
||||
created_at_ms: row.try_get("created_at_ms")?,
|
||||
updated_at_ms: row.try_get("updated_at_ms")?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<ThreadGoalRow> for ThreadGoal {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(row: ThreadGoalRow) -> Result<Self> {
|
||||
Ok(Self {
|
||||
thread_id: ThreadId::try_from(row.thread_id)?,
|
||||
goal_id: row.goal_id,
|
||||
objective: row.objective,
|
||||
status: ThreadGoalStatus::try_from(row.status.as_str())?,
|
||||
token_budget: row.token_budget,
|
||||
tokens_used: row.tokens_used,
|
||||
time_used_seconds: row.time_used_seconds,
|
||||
created_at: epoch_millis_to_datetime(row.created_at_ms)?,
|
||||
updated_at: epoch_millis_to_datetime(row.updated_at_ms)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
889
akode-rs/state/src/model/thread_metadata.rs
Normal file
889
akode-rs/state/src/model/thread_metadata.rs
Normal file
@@ -0,0 +1,889 @@
|
||||
use anyhow::Result;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use akode_protocol::SanitizedGitUrl;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::openai_models::ReasoningEffort;
|
||||
use akode_protocol::protocol::AskForApproval;
|
||||
use akode_protocol::protocol::SandboxPolicy;
|
||||
use akode_protocol::protocol::SessionSource;
|
||||
use akode_protocol::protocol::ThreadHistoryMode;
|
||||
use akode_protocol::protocol::ThreadSource;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use sqlx::Row;
|
||||
use sqlx::sqlite::SqliteRow;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// The sort key to use when listing threads.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SortKey {
|
||||
/// Sort by the thread's creation timestamp.
|
||||
CreatedAt,
|
||||
/// Sort by the thread's last update timestamp.
|
||||
UpdatedAt,
|
||||
/// Sort by the thread's product recency timestamp.
|
||||
RecencyAt,
|
||||
/// Sort by the thread's stable position within its user-selected section.
|
||||
SectionPosition,
|
||||
}
|
||||
|
||||
/// Sort direction to use when listing threads.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SortDirection {
|
||||
Asc,
|
||||
Desc,
|
||||
}
|
||||
|
||||
/// Thread relationship used to filter thread listings.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ThreadRelationFilter {
|
||||
/// Return only threads whose immediate parent is the given thread.
|
||||
DirectChildrenOf(ThreadId),
|
||||
/// Return every thread transitively descended from the given thread.
|
||||
DescendantsOf(ThreadId),
|
||||
/// Return only saved threads attached to this parent.
|
||||
AttachedThreadsOf(ThreadId),
|
||||
}
|
||||
|
||||
/// A pagination anchor used for keyset pagination.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Anchor {
|
||||
/// The timestamp component of the anchor.
|
||||
pub ts: DateTime<Utc>,
|
||||
/// The thread ID component used to disambiguate equal recency timestamps.
|
||||
pub id: Option<ThreadId>,
|
||||
}
|
||||
|
||||
/// Visual presentation metadata owned by a thread section.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ThreadSectionAppearance {
|
||||
pub icon: Option<String>,
|
||||
pub color: Option<String>,
|
||||
}
|
||||
|
||||
/// An independently persisted thread section and its user-facing presentation.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ThreadSection {
|
||||
/// Opaque UUIDv7 identifying the section independently of its name.
|
||||
pub id: String,
|
||||
/// User-facing section name.
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub appearance: Option<ThreadSectionAppearance>,
|
||||
}
|
||||
|
||||
impl ThreadSection {
|
||||
pub(crate) fn from_row(
|
||||
(id, name, appearance): (String, String, Option<String>),
|
||||
) -> Result<Self> {
|
||||
Ok(Self {
|
||||
id,
|
||||
name,
|
||||
appearance: appearance
|
||||
.map(|appearance| serde_json::from_str(&appearance))
|
||||
.transpose()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor-paginated page of independently persisted thread sections.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ThreadSectionsPage {
|
||||
/// Sections in ascending identifier order.
|
||||
pub sections: Vec<ThreadSection>,
|
||||
/// Identifier after which the next page starts, if any.
|
||||
pub next_cursor: Option<String>,
|
||||
}
|
||||
|
||||
/// A single page of thread metadata results.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ThreadsPage {
|
||||
/// The thread metadata items in this page.
|
||||
pub items: Vec<ThreadMetadata>,
|
||||
/// Immediate parents for page items found through the persisted spawn graph.
|
||||
pub parent_thread_ids: HashMap<ThreadId, ThreadId>,
|
||||
/// The next anchor to use for pagination, if any.
|
||||
pub next_anchor: Option<Anchor>,
|
||||
/// The number of rows scanned to produce this page.
|
||||
pub num_scanned_rows: usize,
|
||||
}
|
||||
|
||||
/// The outcome of extracting metadata from a rollout.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ExtractionOutcome {
|
||||
/// The extracted thread metadata.
|
||||
pub metadata: ThreadMetadata,
|
||||
/// The explicit thread memory mode from rollout metadata, if present.
|
||||
pub memory_mode: Option<String>,
|
||||
/// The number of rollout lines that failed to parse.
|
||||
pub parse_errors: usize,
|
||||
}
|
||||
|
||||
/// Canonical persisted thread metadata.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ThreadMetadata {
|
||||
/// The parent of an attached thread, derived from canonical rollout metadata.
|
||||
pub attached_thread_parent_id: Option<ThreadId>,
|
||||
/// Originator recorded at creation, if available.
|
||||
pub originator: Option<String>,
|
||||
/// ChatGPT user that created the thread, if known.
|
||||
pub creator_user_id: Option<String>,
|
||||
/// ChatGPT account at creation, if known.
|
||||
pub creator_account_id: Option<String>,
|
||||
/// The thread identifier.
|
||||
pub id: ThreadId,
|
||||
/// The absolute rollout path on disk.
|
||||
pub rollout_path: PathBuf,
|
||||
/// The creation timestamp.
|
||||
pub created_at: DateTime<Utc>,
|
||||
/// The last update timestamp.
|
||||
pub updated_at: DateTime<Utc>,
|
||||
/// The product recency timestamp.
|
||||
pub recency_at: DateTime<Utc>,
|
||||
/// The session source (stringified enum).
|
||||
pub source: String,
|
||||
/// Persisted thread history contract selected when this thread was created.
|
||||
pub history_mode: ThreadHistoryMode,
|
||||
/// Optional source classification for this thread.
|
||||
pub thread_source: Option<ThreadSource>,
|
||||
/// Optional random unique nickname assigned to an AgentControl-spawned sub-agent.
|
||||
pub agent_nickname: Option<String>,
|
||||
/// Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.
|
||||
pub agent_role: Option<String>,
|
||||
/// Optional canonical agent path assigned to an AgentControl-spawned sub-agent.
|
||||
pub agent_path: Option<String>,
|
||||
/// The model provider identifier.
|
||||
pub model_provider: String,
|
||||
/// The latest observed model for the thread.
|
||||
pub model: Option<String>,
|
||||
/// The latest observed reasoning effort for the thread.
|
||||
pub reasoning_effort: Option<ReasoningEffort>,
|
||||
/// The working directory for the thread.
|
||||
pub cwd: PathBuf,
|
||||
/// Version of the CLI that created the thread.
|
||||
pub cli_version: String,
|
||||
/// A best-effort thread title.
|
||||
pub title: String,
|
||||
/// Explicit user-facing thread name, if one was set.
|
||||
pub name: Option<String>,
|
||||
/// Best available user-facing preview for discovery and list display.
|
||||
pub preview: Option<String>,
|
||||
/// The sandbox policy (stringified enum).
|
||||
pub sandbox_policy: String,
|
||||
/// The approval mode (stringified enum).
|
||||
pub approval_mode: String,
|
||||
/// The last observed token usage.
|
||||
pub tokens_used: i64,
|
||||
/// First user message observed for this thread, if any.
|
||||
pub first_user_message: Option<String>,
|
||||
/// The archive timestamp, if the thread is archived.
|
||||
pub archived_at: Option<DateTime<Utc>>,
|
||||
/// The user-selected section for this thread, if any.
|
||||
pub section: Option<ThreadSection>,
|
||||
/// The stable sparse ordering rank within the user-selected section.
|
||||
pub section_position: Option<i64>,
|
||||
/// The time when the thread most recently entered its current section.
|
||||
pub section_entered_at: Option<DateTime<Utc>>,
|
||||
/// Canonical project assignment owned by app-server, if any.
|
||||
pub project_id: Option<String>,
|
||||
/// The git commit SHA, if known.
|
||||
pub git_sha: Option<String>,
|
||||
/// The git branch name, if known.
|
||||
pub git_branch: Option<String>,
|
||||
/// The git origin URL, if known.
|
||||
pub git_origin_url: Option<SanitizedGitUrl>,
|
||||
}
|
||||
|
||||
/// Builder data required to construct [`ThreadMetadata`] without parsing filenames.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ThreadMetadataBuilder {
|
||||
/// Originator recorded at creation, if available.
|
||||
pub originator: Option<String>,
|
||||
/// ChatGPT user that created the thread, if known.
|
||||
pub creator_user_id: Option<String>,
|
||||
/// ChatGPT account at creation, if known.
|
||||
pub creator_account_id: Option<String>,
|
||||
/// The thread identifier.
|
||||
pub id: ThreadId,
|
||||
/// The absolute rollout path on disk.
|
||||
pub rollout_path: PathBuf,
|
||||
/// The creation timestamp.
|
||||
pub created_at: DateTime<Utc>,
|
||||
/// The last update timestamp, if known.
|
||||
pub updated_at: Option<DateTime<Utc>>,
|
||||
/// The product recency timestamp, if known.
|
||||
pub recency_at: Option<DateTime<Utc>>,
|
||||
/// The session source.
|
||||
pub source: SessionSource,
|
||||
/// Persisted thread history contract selected when this thread was created.
|
||||
pub history_mode: ThreadHistoryMode,
|
||||
/// Optional source classification for this thread.
|
||||
pub thread_source: Option<ThreadSource>,
|
||||
/// Optional random unique nickname assigned to the session.
|
||||
pub agent_nickname: Option<String>,
|
||||
/// Optional role (agent_role) assigned to the session.
|
||||
pub agent_role: Option<String>,
|
||||
/// Optional canonical agent path assigned to the session.
|
||||
pub agent_path: Option<String>,
|
||||
/// The model provider identifier, if known.
|
||||
pub model_provider: Option<String>,
|
||||
/// The working directory for the thread.
|
||||
pub cwd: PathBuf,
|
||||
/// Version of the CLI that created the thread.
|
||||
pub cli_version: Option<String>,
|
||||
/// The sandbox policy.
|
||||
pub sandbox_policy: SandboxPolicy,
|
||||
/// The approval mode.
|
||||
pub approval_mode: AskForApproval,
|
||||
/// The archive timestamp, if the thread is archived.
|
||||
pub archived_at: Option<DateTime<Utc>>,
|
||||
/// The git commit SHA, if known.
|
||||
pub git_sha: Option<String>,
|
||||
/// The git branch name, if known.
|
||||
pub git_branch: Option<String>,
|
||||
/// The git origin URL, if known.
|
||||
pub git_origin_url: Option<SanitizedGitUrl>,
|
||||
}
|
||||
|
||||
impl ThreadMetadataBuilder {
|
||||
/// Create a new builder with required fields and sensible defaults.
|
||||
pub fn new(
|
||||
id: ThreadId,
|
||||
rollout_path: PathBuf,
|
||||
created_at: DateTime<Utc>,
|
||||
source: SessionSource,
|
||||
) -> Self {
|
||||
Self {
|
||||
id,
|
||||
rollout_path,
|
||||
created_at,
|
||||
updated_at: None,
|
||||
recency_at: None,
|
||||
originator: None,
|
||||
creator_user_id: None,
|
||||
creator_account_id: None,
|
||||
source,
|
||||
history_mode: ThreadHistoryMode::Legacy,
|
||||
thread_source: None,
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
agent_path: None,
|
||||
model_provider: None,
|
||||
cwd: PathBuf::new(),
|
||||
cli_version: None,
|
||||
sandbox_policy: SandboxPolicy::new_read_only_policy(),
|
||||
approval_mode: AskForApproval::OnRequest,
|
||||
archived_at: None,
|
||||
git_sha: None,
|
||||
git_branch: None,
|
||||
git_origin_url: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Build canonical thread metadata, filling missing values from defaults.
|
||||
pub fn build(&self, default_provider: &str) -> ThreadMetadata {
|
||||
let source = crate::extract::enum_to_string(&self.source);
|
||||
let sandbox_policy = crate::extract::enum_to_string(&self.sandbox_policy);
|
||||
let approval_mode = crate::extract::enum_to_string(&self.approval_mode);
|
||||
let created_at = canonicalize_datetime(self.created_at);
|
||||
let updated_at = self
|
||||
.updated_at
|
||||
.map(canonicalize_datetime)
|
||||
.unwrap_or(created_at);
|
||||
let recency_at = self
|
||||
.recency_at
|
||||
.map(canonicalize_datetime)
|
||||
.unwrap_or(updated_at);
|
||||
let guardian_review = crate::is_guardian_review_source(&self.source);
|
||||
ThreadMetadata {
|
||||
attached_thread_parent_id: None,
|
||||
originator: self.originator.clone(),
|
||||
creator_user_id: self.creator_user_id.clone(),
|
||||
creator_account_id: self.creator_account_id.clone(),
|
||||
id: self.id,
|
||||
rollout_path: self.rollout_path.clone(),
|
||||
created_at,
|
||||
updated_at,
|
||||
recency_at,
|
||||
source,
|
||||
history_mode: self.history_mode,
|
||||
thread_source: self.thread_source.clone(),
|
||||
agent_nickname: self.agent_nickname.clone(),
|
||||
agent_role: self.agent_role.clone(),
|
||||
agent_path: self
|
||||
.agent_path
|
||||
.clone()
|
||||
.or_else(|| self.source.get_agent_path().map(Into::into)),
|
||||
model_provider: self
|
||||
.model_provider
|
||||
.clone()
|
||||
.unwrap_or_else(|| default_provider.to_string()),
|
||||
model: None,
|
||||
reasoning_effort: None,
|
||||
cwd: self.cwd.clone(),
|
||||
cli_version: self.cli_version.clone().unwrap_or_default(),
|
||||
title: if guardian_review {
|
||||
crate::GUARDIAN_THREAD_TITLE.to_string()
|
||||
} else {
|
||||
String::new()
|
||||
},
|
||||
name: (guardian_review && self.history_mode == ThreadHistoryMode::Paginated)
|
||||
.then(|| crate::GUARDIAN_THREAD_TITLE.to_string()),
|
||||
preview: guardian_review.then(|| crate::GUARDIAN_THREAD_PREVIEW.to_string()),
|
||||
sandbox_policy,
|
||||
approval_mode,
|
||||
tokens_used: 0,
|
||||
first_user_message: None,
|
||||
archived_at: self.archived_at.map(canonicalize_datetime),
|
||||
section: None,
|
||||
section_position: None,
|
||||
section_entered_at: None,
|
||||
project_id: None,
|
||||
git_sha: self.git_sha.clone(),
|
||||
git_branch: self.git_branch.clone(),
|
||||
git_origin_url: self.git_origin_url.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadMetadata {
|
||||
/// Preserve SQLite-owned Git fields when rollout-derived metadata is reconciled.
|
||||
pub fn prefer_existing_git_info(&mut self, existing: &Self) {
|
||||
if matches!(self.history_mode, ThreadHistoryMode::Paginated)
|
||||
&& matches!(existing.history_mode, ThreadHistoryMode::Paginated)
|
||||
{
|
||||
// `self` was rebuilt from the rollout's initial SessionMeta. `existing` is the
|
||||
// current SQLite row. Once that row says paginated, metadata updates are SQLite-only,
|
||||
// so a NULL is an explicit clear, not missing data. Copy the whole tuple or the stale
|
||||
// rollout value would be written back during reconciliation.
|
||||
self.git_sha = existing.git_sha.clone();
|
||||
self.git_branch = existing.git_branch.clone();
|
||||
self.git_origin_url = existing.git_origin_url.clone();
|
||||
return;
|
||||
}
|
||||
if existing.git_sha.is_some() {
|
||||
self.git_sha = existing.git_sha.clone();
|
||||
}
|
||||
if existing.git_branch.is_some() {
|
||||
self.git_branch = existing.git_branch.clone();
|
||||
}
|
||||
if existing.git_origin_url.is_some() {
|
||||
self.git_origin_url = existing.git_origin_url.clone();
|
||||
}
|
||||
}
|
||||
|
||||
/// Preserve an existing user-facing title when reconciling rollout-derived metadata.
|
||||
pub fn prefer_existing_explicit_title(&mut self, existing: &Self) {
|
||||
let existing_title = existing.title.trim();
|
||||
if existing_title.is_empty()
|
||||
|| existing.first_user_message.as_deref().map(str::trim) == Some(existing_title)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let title = self.title.trim();
|
||||
if title.is_empty()
|
||||
|| self.first_user_message.as_deref().map(str::trim) == Some(title)
|
||||
|| (title == crate::GUARDIAN_THREAD_TITLE
|
||||
&& crate::extract::metadata_is_guardian_review(self))
|
||||
{
|
||||
self.title = existing.title.clone();
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the list of field names that differ between `self` and `other`.
|
||||
pub fn diff_fields(&self, other: &Self) -> Vec<&'static str> {
|
||||
let mut diffs = Vec::new();
|
||||
if self.id != other.id {
|
||||
diffs.push("id");
|
||||
}
|
||||
if self.rollout_path != other.rollout_path {
|
||||
diffs.push("rollout_path");
|
||||
}
|
||||
if self.created_at != other.created_at {
|
||||
diffs.push("created_at");
|
||||
}
|
||||
if self.updated_at != other.updated_at {
|
||||
diffs.push("updated_at");
|
||||
}
|
||||
if self.source != other.source {
|
||||
diffs.push("source");
|
||||
}
|
||||
if self.creator_user_id != other.creator_user_id {
|
||||
diffs.push("creator_user_id");
|
||||
}
|
||||
if self.creator_account_id != other.creator_account_id {
|
||||
diffs.push("creator_account_id");
|
||||
}
|
||||
if self.originator != other.originator {
|
||||
diffs.push("originator");
|
||||
}
|
||||
if self.agent_nickname != other.agent_nickname {
|
||||
diffs.push("agent_nickname");
|
||||
}
|
||||
if self.agent_role != other.agent_role {
|
||||
diffs.push("agent_role");
|
||||
}
|
||||
if self.agent_path != other.agent_path {
|
||||
diffs.push("agent_path");
|
||||
}
|
||||
if self.model_provider != other.model_provider {
|
||||
diffs.push("model_provider");
|
||||
}
|
||||
if self.model != other.model {
|
||||
diffs.push("model");
|
||||
}
|
||||
if self.reasoning_effort != other.reasoning_effort {
|
||||
diffs.push("reasoning_effort");
|
||||
}
|
||||
if self.cwd != other.cwd {
|
||||
diffs.push("cwd");
|
||||
}
|
||||
if self.cli_version != other.cli_version {
|
||||
diffs.push("cli_version");
|
||||
}
|
||||
if self.title != other.title {
|
||||
diffs.push("title");
|
||||
}
|
||||
if self.name != other.name {
|
||||
diffs.push("name");
|
||||
}
|
||||
if self.preview != other.preview {
|
||||
diffs.push("preview");
|
||||
}
|
||||
if self.sandbox_policy != other.sandbox_policy {
|
||||
diffs.push("sandbox_policy");
|
||||
}
|
||||
if self.approval_mode != other.approval_mode {
|
||||
diffs.push("approval_mode");
|
||||
}
|
||||
if self.tokens_used != other.tokens_used {
|
||||
diffs.push("tokens_used");
|
||||
}
|
||||
if self.first_user_message != other.first_user_message {
|
||||
diffs.push("first_user_message");
|
||||
}
|
||||
if self.archived_at != other.archived_at {
|
||||
diffs.push("archived_at");
|
||||
}
|
||||
if self.section != other.section {
|
||||
diffs.push("section");
|
||||
}
|
||||
if self.section_position != other.section_position {
|
||||
diffs.push("section_position");
|
||||
}
|
||||
if self.section_entered_at != other.section_entered_at {
|
||||
diffs.push("section_entered_at");
|
||||
}
|
||||
if self.project_id != other.project_id {
|
||||
diffs.push("project_id");
|
||||
}
|
||||
if self.git_sha != other.git_sha {
|
||||
diffs.push("git_sha");
|
||||
}
|
||||
if self.git_branch != other.git_branch {
|
||||
diffs.push("git_branch");
|
||||
}
|
||||
if self.git_origin_url != other.git_origin_url {
|
||||
diffs.push("git_origin_url");
|
||||
}
|
||||
diffs
|
||||
}
|
||||
}
|
||||
|
||||
fn canonicalize_datetime(dt: DateTime<Utc>) -> DateTime<Utc> {
|
||||
epoch_millis_to_datetime(datetime_to_epoch_millis(dt)).unwrap_or(dt)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ThreadRow {
|
||||
attached_thread_parent_id: Option<String>,
|
||||
originator: Option<String>,
|
||||
creator_user_id: Option<String>,
|
||||
creator_account_id: Option<String>,
|
||||
id: String,
|
||||
rollout_path: String,
|
||||
created_at: i64,
|
||||
updated_at: i64,
|
||||
recency_at: i64,
|
||||
source: String,
|
||||
history_mode: String,
|
||||
thread_source: Option<String>,
|
||||
agent_nickname: Option<String>,
|
||||
agent_role: Option<String>,
|
||||
agent_path: Option<String>,
|
||||
model_provider: String,
|
||||
model: Option<String>,
|
||||
reasoning_effort: Option<String>,
|
||||
cwd: String,
|
||||
cli_version: String,
|
||||
title: String,
|
||||
name: Option<String>,
|
||||
preview: String,
|
||||
sandbox_policy: String,
|
||||
approval_mode: String,
|
||||
tokens_used: i64,
|
||||
first_user_message: String,
|
||||
archived_at: Option<i64>,
|
||||
section: Option<String>,
|
||||
section_name: Option<String>,
|
||||
section_appearance: Option<String>,
|
||||
section_position: Option<i64>,
|
||||
section_entered_at_ms: Option<i64>,
|
||||
project_id: Option<String>,
|
||||
git_sha: Option<String>,
|
||||
git_branch: Option<String>,
|
||||
git_origin_url: Option<String>,
|
||||
}
|
||||
|
||||
impl ThreadRow {
|
||||
pub(crate) fn try_from_row(row: &SqliteRow) -> Result<Self> {
|
||||
Ok(Self {
|
||||
attached_thread_parent_id: row.try_get("attached_thread_parent_id")?,
|
||||
originator: row.try_get("originator")?,
|
||||
creator_user_id: row.try_get("creator_user_id")?,
|
||||
creator_account_id: row.try_get("creator_account_id")?,
|
||||
id: row.try_get("id")?,
|
||||
rollout_path: row.try_get("rollout_path")?,
|
||||
created_at: row.try_get("created_at")?,
|
||||
updated_at: row.try_get("updated_at")?,
|
||||
recency_at: row.try_get("recency_at")?,
|
||||
source: row.try_get("source")?,
|
||||
history_mode: row.try_get("history_mode")?,
|
||||
thread_source: row.try_get("thread_source")?,
|
||||
agent_nickname: row.try_get("agent_nickname")?,
|
||||
agent_role: row.try_get("agent_role")?,
|
||||
agent_path: row.try_get("agent_path")?,
|
||||
model_provider: row.try_get("model_provider")?,
|
||||
model: row.try_get("model")?,
|
||||
reasoning_effort: row.try_get("reasoning_effort")?,
|
||||
cwd: row.try_get("cwd")?,
|
||||
cli_version: row.try_get("cli_version")?,
|
||||
title: row.try_get("title")?,
|
||||
name: row.try_get("name")?,
|
||||
preview: row.try_get("preview")?,
|
||||
sandbox_policy: row.try_get("sandbox_policy")?,
|
||||
approval_mode: row.try_get("approval_mode")?,
|
||||
tokens_used: row.try_get("tokens_used")?,
|
||||
first_user_message: row.try_get("first_user_message")?,
|
||||
archived_at: row.try_get("archived_at")?,
|
||||
section: row.try_get("section")?,
|
||||
section_name: row.try_get("section_name")?,
|
||||
section_appearance: row.try_get("section_appearance")?,
|
||||
section_position: row.try_get("section_position")?,
|
||||
section_entered_at_ms: row.try_get("section_entered_at_ms")?,
|
||||
project_id: row.try_get("project_id")?,
|
||||
git_sha: row.try_get("git_sha")?,
|
||||
git_branch: row.try_get("git_branch")?,
|
||||
git_origin_url: row.try_get("git_origin_url")?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<ThreadRow> for ThreadMetadata {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(row: ThreadRow) -> std::result::Result<Self, Self::Error> {
|
||||
let ThreadRow {
|
||||
attached_thread_parent_id,
|
||||
originator,
|
||||
creator_user_id,
|
||||
creator_account_id,
|
||||
id,
|
||||
rollout_path,
|
||||
created_at,
|
||||
updated_at,
|
||||
recency_at,
|
||||
source,
|
||||
history_mode,
|
||||
thread_source,
|
||||
agent_nickname,
|
||||
agent_role,
|
||||
agent_path,
|
||||
model_provider,
|
||||
model,
|
||||
reasoning_effort,
|
||||
cwd,
|
||||
cli_version,
|
||||
title,
|
||||
name,
|
||||
preview,
|
||||
sandbox_policy,
|
||||
approval_mode,
|
||||
tokens_used,
|
||||
first_user_message,
|
||||
archived_at,
|
||||
section,
|
||||
section_name,
|
||||
section_appearance,
|
||||
section_position,
|
||||
section_entered_at_ms,
|
||||
project_id,
|
||||
git_sha,
|
||||
git_branch,
|
||||
git_origin_url,
|
||||
} = row;
|
||||
let thread_source = thread_source
|
||||
.map(|thread_source| thread_source.parse())
|
||||
.transpose()
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let history_mode = history_mode.parse().map_err(anyhow::Error::msg)?;
|
||||
let section = match (section, section_name) {
|
||||
(Some(id), Some(name)) => {
|
||||
Some(ThreadSection::from_row((id, name, section_appearance))?)
|
||||
}
|
||||
(None, None) => None,
|
||||
(Some(id), None) => {
|
||||
return Err(anyhow::anyhow!(
|
||||
"thread references an unknown section: {id}"
|
||||
));
|
||||
}
|
||||
(None, Some(name)) => {
|
||||
return Err(anyhow::anyhow!(
|
||||
"thread has a section name without a section id: {name}"
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: ThreadId::try_from(id)?,
|
||||
attached_thread_parent_id: attached_thread_parent_id
|
||||
.map(ThreadId::try_from)
|
||||
.transpose()?,
|
||||
originator,
|
||||
creator_user_id,
|
||||
creator_account_id,
|
||||
rollout_path: PathBuf::from(rollout_path),
|
||||
created_at: epoch_millis_to_datetime(created_at)?,
|
||||
updated_at: epoch_millis_to_datetime(updated_at)?,
|
||||
recency_at: epoch_millis_to_datetime(recency_at)?,
|
||||
source,
|
||||
history_mode,
|
||||
thread_source,
|
||||
agent_nickname,
|
||||
agent_role,
|
||||
agent_path,
|
||||
model_provider,
|
||||
model,
|
||||
reasoning_effort: reasoning_effort
|
||||
.and_then(|value| value.parse::<ReasoningEffort>().ok()),
|
||||
cwd: PathBuf::from(cwd),
|
||||
cli_version,
|
||||
title,
|
||||
name,
|
||||
preview: (!preview.is_empty()).then_some(preview),
|
||||
sandbox_policy,
|
||||
approval_mode,
|
||||
tokens_used,
|
||||
first_user_message: (!first_user_message.is_empty()).then_some(first_user_message),
|
||||
archived_at: archived_at.map(epoch_seconds_to_datetime).transpose()?,
|
||||
section,
|
||||
section_position,
|
||||
section_entered_at: section_entered_at_ms
|
||||
.map(epoch_millis_to_datetime)
|
||||
.transpose()?,
|
||||
project_id,
|
||||
git_sha,
|
||||
git_branch,
|
||||
git_origin_url: git_origin_url
|
||||
.and_then(|origin_url| SanitizedGitUrl::try_from(origin_url).ok()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn anchor_from_item(item: &ThreadMetadata, sort_key: SortKey) -> Option<Anchor> {
|
||||
let ts = match sort_key {
|
||||
SortKey::CreatedAt => item.created_at,
|
||||
SortKey::UpdatedAt => item.updated_at,
|
||||
SortKey::RecencyAt => item.recency_at,
|
||||
SortKey::SectionPosition => DateTime::<Utc>::from_timestamp_millis(item.section_position?)?,
|
||||
};
|
||||
Some(Anchor {
|
||||
ts,
|
||||
id: Some(item.id),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn datetime_to_epoch_millis(dt: DateTime<Utc>) -> i64 {
|
||||
dt.timestamp_millis()
|
||||
}
|
||||
|
||||
pub(crate) fn datetime_to_epoch_seconds(dt: DateTime<Utc>) -> i64 {
|
||||
dt.timestamp()
|
||||
}
|
||||
|
||||
pub(crate) fn epoch_millis_to_datetime(value: i64) -> Result<DateTime<Utc>> {
|
||||
// Values older than 2020 if interpreted as milliseconds are legacy second-precision rows.
|
||||
// Convert them in memory so old state DBs keep ordering correctly after new writes use ms.
|
||||
const MIN_EPOCH_MILLIS: i64 = 1_577_836_800_000;
|
||||
let millis = if value < MIN_EPOCH_MILLIS {
|
||||
value.saturating_mul(1000)
|
||||
} else {
|
||||
value
|
||||
};
|
||||
DateTime::<Utc>::from_timestamp_millis(millis)
|
||||
.ok_or_else(|| anyhow::anyhow!("invalid unix timestamp millis: {value}"))
|
||||
}
|
||||
|
||||
pub(crate) fn epoch_seconds_to_datetime(value: i64) -> Result<DateTime<Utc>> {
|
||||
DateTime::<Utc>::from_timestamp(value, 0)
|
||||
.ok_or_else(|| anyhow::anyhow!("invalid unix timestamp seconds: {value}"))
|
||||
}
|
||||
|
||||
/// Statistics about a backfill operation.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BackfillStats {
|
||||
/// The number of rollout files scanned.
|
||||
pub scanned: usize,
|
||||
/// The number of rows upserted successfully.
|
||||
pub upserted: usize,
|
||||
/// The number of rows that failed to upsert.
|
||||
pub failed: usize,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::ThreadMetadata;
|
||||
use super::ThreadRow;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use akode_protocol::SanitizedGitUrl;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::openai_models::ReasoningEffort;
|
||||
use akode_protocol::protocol::ThreadHistoryMode;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn thread_row(reasoning_effort: Option<&str>) -> ThreadRow {
|
||||
ThreadRow {
|
||||
attached_thread_parent_id: None,
|
||||
originator: None,
|
||||
creator_user_id: None,
|
||||
creator_account_id: None,
|
||||
id: "00000000-0000-0000-0000-000000000123".to_string(),
|
||||
rollout_path: "/tmp/rollout-123.jsonl".to_string(),
|
||||
created_at: 1_700_000_000,
|
||||
updated_at: 1_700_000_100,
|
||||
recency_at: 1_700_000_100,
|
||||
source: "cli".to_string(),
|
||||
history_mode: "legacy".to_string(),
|
||||
thread_source: None,
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
agent_path: None,
|
||||
model_provider: "openai".to_string(),
|
||||
model: Some("gpt-5".to_string()),
|
||||
reasoning_effort: reasoning_effort.map(str::to_string),
|
||||
cwd: "/tmp/workspace".to_string(),
|
||||
cli_version: "0.0.0".to_string(),
|
||||
title: String::new(),
|
||||
name: None,
|
||||
preview: String::new(),
|
||||
sandbox_policy: "read-only".to_string(),
|
||||
approval_mode: "on-request".to_string(),
|
||||
tokens_used: 1,
|
||||
first_user_message: String::new(),
|
||||
archived_at: None,
|
||||
section: None,
|
||||
section_name: None,
|
||||
section_appearance: None,
|
||||
section_position: None,
|
||||
section_entered_at_ms: None,
|
||||
project_id: None,
|
||||
git_sha: None,
|
||||
git_branch: None,
|
||||
git_origin_url: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn expected_thread_metadata(reasoning_effort: Option<ReasoningEffort>) -> ThreadMetadata {
|
||||
ThreadMetadata {
|
||||
attached_thread_parent_id: None,
|
||||
originator: None,
|
||||
creator_user_id: None,
|
||||
creator_account_id: None,
|
||||
id: ThreadId::from_string("00000000-0000-0000-0000-000000000123")
|
||||
.expect("valid thread id"),
|
||||
rollout_path: PathBuf::from("/tmp/rollout-123.jsonl"),
|
||||
created_at: DateTime::<Utc>::from_timestamp(1_700_000_000, 0).expect("timestamp"),
|
||||
updated_at: DateTime::<Utc>::from_timestamp(1_700_000_100, 0).expect("timestamp"),
|
||||
recency_at: DateTime::<Utc>::from_timestamp(1_700_000_100, 0).expect("timestamp"),
|
||||
source: "cli".to_string(),
|
||||
history_mode: ThreadHistoryMode::Legacy,
|
||||
thread_source: None,
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
agent_path: None,
|
||||
model_provider: "openai".to_string(),
|
||||
model: Some("gpt-5".to_string()),
|
||||
reasoning_effort,
|
||||
cwd: PathBuf::from("/tmp/workspace"),
|
||||
cli_version: "0.0.0".to_string(),
|
||||
title: String::new(),
|
||||
name: None,
|
||||
preview: None,
|
||||
sandbox_policy: "read-only".to_string(),
|
||||
approval_mode: "on-request".to_string(),
|
||||
tokens_used: 1,
|
||||
first_user_message: None,
|
||||
archived_at: None,
|
||||
section: None,
|
||||
section_position: None,
|
||||
section_entered_at: None,
|
||||
project_id: None,
|
||||
git_sha: None,
|
||||
git_branch: None,
|
||||
git_origin_url: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_row_parses_reasoning_effort() {
|
||||
let metadata = ThreadMetadata::try_from(thread_row(Some("high")))
|
||||
.expect("thread metadata should parse");
|
||||
|
||||
assert_eq!(
|
||||
metadata,
|
||||
expected_thread_metadata(Some(ReasoningEffort::High))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_row_preserves_model_defined_reasoning_effort_values() {
|
||||
let metadata = ThreadMetadata::try_from(thread_row(Some("future")))
|
||||
.expect("thread metadata should parse");
|
||||
|
||||
assert_eq!(
|
||||
metadata,
|
||||
expected_thread_metadata(Some(ReasoningEffort::Custom("future".to_string())))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_row_rejects_unknown_history_mode() {
|
||||
let mut row = thread_row(/*reasoning_effort*/ None);
|
||||
row.history_mode = "future".to_string();
|
||||
|
||||
assert!(ThreadMetadata::try_from(row).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paginated_rollout_git_info_keeps_rollout_values_until_sqlite_mode_is_paginated() {
|
||||
let mut reconciled = expected_thread_metadata(/*reasoning_effort*/ None);
|
||||
reconciled.history_mode = ThreadHistoryMode::Paginated;
|
||||
reconciled.git_sha = Some("rollout-sha".to_string());
|
||||
reconciled.git_branch = Some("rollout-branch".to_string());
|
||||
reconciled.git_origin_url = Some(
|
||||
SanitizedGitUrl::try_from("https://example.com/rollout-origin")
|
||||
.expect("valid git remote URL"),
|
||||
);
|
||||
let existing = expected_thread_metadata(/*reasoning_effort*/ None);
|
||||
let expected = reconciled.clone();
|
||||
|
||||
reconciled.prefer_existing_git_info(&existing);
|
||||
|
||||
assert_eq!(reconciled, expected);
|
||||
}
|
||||
}
|
||||
363
akode-rs/state/src/nfs_migration.rs
Normal file
363
akode-rs/state/src/nfs_migration.rs
Normal file
@@ -0,0 +1,363 @@
|
||||
//! Converts WAL databases to DELETE mode while preserving recoverable WAL backups.
|
||||
//! Callers serialize startup and migration with the directory lock. Other SQLite clients
|
||||
//! must remain stopped during replacement; NFS must enforce cross-client POSIX locks.
|
||||
//! Migration requires write access to the directory and its persistent migration lock.
|
||||
//! Relaxed file permissions do not establish cross-user database sharing.
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::ensure;
|
||||
use sqlx::ConnectOptions;
|
||||
use sqlx::Connection;
|
||||
use sqlx::SqliteConnection;
|
||||
use sqlx::sqlite::SqliteConnectOptions;
|
||||
use sqlx::sqlite::SqliteJournalMode;
|
||||
use sqlx::sqlite::SqliteLockingMode;
|
||||
use sqlx::sqlite::SqliteSynchronous;
|
||||
use std::fs::File;
|
||||
use std::io::ErrorKind;
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
mod replacement;
|
||||
|
||||
use replacement::Recovery;
|
||||
use replacement::Replacement;
|
||||
use replacement::regular_file_exists;
|
||||
|
||||
/// Holds the directory lock shared by automatic startup and the migration command.
|
||||
pub struct NfsDbMigration {
|
||||
_lock: File,
|
||||
}
|
||||
|
||||
/// Result of checking or converting a database, for caller-owned reporting.
|
||||
pub enum NfsDbMigrationOutcome {
|
||||
Missing,
|
||||
AlreadyDelete,
|
||||
Migrated { backup_directory: PathBuf },
|
||||
}
|
||||
|
||||
impl NfsDbMigration {
|
||||
/// Inspect the on-disk journal mode without accessing WAL shared memory.
|
||||
/// Use SQLite's descriptor so closing it cannot release another connection's locks.
|
||||
#[expect(
|
||||
clippy::disallowed_methods,
|
||||
reason = "NFS inspection needs an immutable connection without shared memory"
|
||||
)]
|
||||
pub async fn needs_migration(source: &Path) -> anyhow::Result<bool> {
|
||||
if !regular_file_exists(source)? {
|
||||
let replacement = Replacement::new(source)?;
|
||||
return Ok(regular_file_exists(&replacement.backup_database)?
|
||||
|| regular_file_exists(&replacement.replacement_path())?);
|
||||
}
|
||||
let mut connection = SqliteConnection::connect_with(
|
||||
&SqliteConnectOptions::new()
|
||||
.filename(source)
|
||||
.read_only(true)
|
||||
.immutable(true)
|
||||
.disable_statement_logging(),
|
||||
)
|
||||
.await?;
|
||||
let inspected: anyhow::Result<bool> = async {
|
||||
let mut handle = connection.lock_handle().await?;
|
||||
let mut file: *mut libsqlite3_sys::sqlite3_file = std::ptr::null_mut();
|
||||
// SAFETY: SQLx's guard excludes its worker. FILE_POINTER writes a borrowed
|
||||
// sqlite3_file pointer, valid while this connection and guard remain alive.
|
||||
let status = unsafe {
|
||||
libsqlite3_sys::sqlite3_file_control(
|
||||
handle.as_raw_handle().as_ptr(),
|
||||
c"main".as_ptr(),
|
||||
libsqlite3_sys::SQLITE_FCNTL_FILE_POINTER,
|
||||
(&raw mut file).cast(),
|
||||
)
|
||||
};
|
||||
ensure!(
|
||||
status == libsqlite3_sys::SQLITE_OK && !file.is_null(),
|
||||
"cannot inspect database header"
|
||||
);
|
||||
// SAFETY: FILE_POINTER returned a live file owned by the guarded connection.
|
||||
let methods = unsafe { (*file).pMethods };
|
||||
ensure!(!methods.is_null(), "database VFS has no file methods");
|
||||
let mut header = [0u8; 20];
|
||||
// SAFETY: the built-in file VFS supplies xRead; the guarded file is live,
|
||||
// and the buffer has space for exactly the requested 20 bytes.
|
||||
let status = unsafe {
|
||||
let read = (*methods).xRead.context("database VFS cannot read")?;
|
||||
read(
|
||||
file,
|
||||
header.as_mut_ptr().cast(),
|
||||
/*iAmt*/ 20,
|
||||
/*iOfst*/ 0,
|
||||
)
|
||||
};
|
||||
ensure!(
|
||||
status == libsqlite3_sys::SQLITE_OK,
|
||||
"cannot read database header: {status}"
|
||||
);
|
||||
ensure!(
|
||||
&header[..16] == b"SQLite format 3\0",
|
||||
"invalid database header"
|
||||
);
|
||||
// SQLite file-format read/write versions are 1 for rollback and 2 for WAL.
|
||||
Ok(header[18] == 2 || header[19] == 2)
|
||||
}
|
||||
.await;
|
||||
let closed = connection.close().await;
|
||||
let needed = inspected?;
|
||||
closed?;
|
||||
Ok(needed)
|
||||
}
|
||||
|
||||
pub fn lock(sqlite_home: &Path) -> anyhow::Result<Self> {
|
||||
ensure!(
|
||||
cfg!(unix),
|
||||
"NFS database migration requires Unix filesystem locking and directory fsync"
|
||||
);
|
||||
// Never remove the lock: concurrent openers must lock the same inode.
|
||||
let lock = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.open(sqlite_home.join(".codex-nfs-migration.lock"))?;
|
||||
lock.try_lock()
|
||||
.context("another database migration is running")?;
|
||||
Ok(Self { _lock: lock })
|
||||
}
|
||||
|
||||
/// Whether source or recovery files have permission bits other than 0600.
|
||||
/// Only inspect metadata: opening WAL databases can create shared-memory files.
|
||||
pub fn needs_permission_confirmation(source: &Path) -> anyhow::Result<bool> {
|
||||
let replacement = Replacement::new(source)?;
|
||||
for path in [
|
||||
source.to_path_buf(),
|
||||
replacement.backup_database.clone(),
|
||||
replacement.replacement_path(),
|
||||
] {
|
||||
if !regular_file_exists(&path)? {
|
||||
continue;
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
if std::fs::metadata(path)?.permissions().mode() & 0o777 != 0o600 {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Convert an existing WAL database or resume an interrupted replacement.
|
||||
/// All other clients must remain stopped until this returns successfully.
|
||||
/// Callers must obtain consent or require unsafe migration through managed policy.
|
||||
/// The replacement preserves mode bits, but belongs to the current user and does not
|
||||
/// copy the original owner, group, or extended ACLs.
|
||||
#[expect(
|
||||
clippy::disallowed_methods,
|
||||
reason = "Migration needs a dedicated exclusive connection, not a runtime pool"
|
||||
)]
|
||||
pub async fn migrate(
|
||||
&mut self,
|
||||
source: &Path,
|
||||
staging_dir: &Path,
|
||||
) -> anyhow::Result<NfsDbMigrationOutcome> {
|
||||
let replacement = Replacement::new(source)?;
|
||||
if let Recovery::Installed = replacement.resume().await? {
|
||||
return Ok(NfsDbMigrationOutcome::Migrated {
|
||||
backup_directory: replacement.backup_directory,
|
||||
});
|
||||
}
|
||||
let exists = regular_file_exists(source)?;
|
||||
for suffix in ["-wal", "-shm", "-journal"] {
|
||||
let mut path = source.as_os_str().to_owned();
|
||||
path.push(suffix);
|
||||
let sidecar_exists = regular_file_exists(Path::new(&path))?;
|
||||
ensure!(
|
||||
exists || !sidecar_exists,
|
||||
"database is missing but a SQLite sidecar exists"
|
||||
);
|
||||
}
|
||||
if !exists {
|
||||
return Ok(NfsDbMigrationOutcome::Missing);
|
||||
}
|
||||
let options = SqliteConnectOptions::new()
|
||||
.filename(source)
|
||||
// Set this mode before SQLite first accesses the WAL.
|
||||
// SQLite then locks the database file without shared memory across NFS client kernels.
|
||||
.locking_mode(SqliteLockingMode::Exclusive)
|
||||
.synchronous(SqliteSynchronous::Full)
|
||||
.busy_timeout(Duration::from_secs(/*secs*/ 5))
|
||||
.disable_statement_logging();
|
||||
let mut connection = SqliteConnection::connect_with(&options).await.context(
|
||||
"cannot open source database exclusively; close its SQLite clients on all hosts",
|
||||
)?;
|
||||
|
||||
// Closing any descriptor for an inode can release this process's POSIX record locks
|
||||
// for that inode.
|
||||
// Keep both source files open until SQLite closes its connection, including after an error.
|
||||
let mut source_files = Vec::new();
|
||||
let result: anyhow::Result<bool> = async {
|
||||
{
|
||||
let mut handle = connection.lock_handle().await?;
|
||||
// SAFETY: SQLx's guard prevents its worker from accessing this open connection.
|
||||
// This db_config option accepts an int and an optional output pointer to an int.
|
||||
let status = unsafe {
|
||||
libsqlite3_sys::sqlite3_db_config(
|
||||
handle.as_raw_handle().as_ptr(),
|
||||
libsqlite3_sys::SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE,
|
||||
/*onoff*/ 1,
|
||||
std::ptr::null_mut::<i32>(),
|
||||
)
|
||||
};
|
||||
ensure!(
|
||||
status == libsqlite3_sys::SQLITE_OK,
|
||||
"cannot disable source checkpoint on close: {status}"
|
||||
);
|
||||
}
|
||||
let mode: String = sqlx::query_scalar("PRAGMA journal_mode")
|
||||
.fetch_one(&mut connection)
|
||||
.await
|
||||
.context(
|
||||
"cannot access source database exclusively; close its SQLite clients on all hosts",
|
||||
)?;
|
||||
if mode == "delete" {
|
||||
ensure!(
|
||||
!regular_file_exists(&replacement.replacement_path())?,
|
||||
"unfinished backup exists"
|
||||
);
|
||||
return Ok(false);
|
||||
}
|
||||
ensure!(
|
||||
mode == "wal",
|
||||
"source database must be in WAL mode (found {mode})"
|
||||
);
|
||||
// BEGIN EXCLUSIVE alone blocks only WAL writers. EXCLUSIVE locking_mode also blocks readers.
|
||||
// The mode keeps the database lock after ROLLBACK.
|
||||
sqlx::raw_sql("BEGIN EXCLUSIVE; ROLLBACK;")
|
||||
.execute(&mut connection)
|
||||
.await
|
||||
.context(
|
||||
"cannot lock source database exclusively; close its SQLite clients on all hosts",
|
||||
)?;
|
||||
|
||||
// A DELETE no-op must not open raw descriptors: closing them could release
|
||||
// POSIX locks held by another pool in this process.
|
||||
source_files.push(File::open(source)?);
|
||||
let source_permissions = source_files[0].metadata()?.permissions();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
ensure!(
|
||||
source_permissions.mode() & 0o600 == 0o600,
|
||||
"database owner permissions must include read and write so the replacement remains accessible to its new owner"
|
||||
);
|
||||
}
|
||||
// The private directory protects WAL contents even on a shared /tmp.
|
||||
let staging = tempfile::Builder::new()
|
||||
.prefix("codex-nfs-migration-")
|
||||
.tempdir_in(staging_dir)
|
||||
.context("cannot create local staging directory")?;
|
||||
let staged_database = staging.path().join("database.sqlite");
|
||||
|
||||
let mut wal_path = source.as_os_str().to_owned();
|
||||
wal_path.push("-wal");
|
||||
match File::open(wal_path) {
|
||||
Ok(file) => source_files.push(file),
|
||||
Err(error) if error.kind() == ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error).context("cannot open source WAL"),
|
||||
}
|
||||
for (file, name) in source_files
|
||||
.iter_mut()
|
||||
.zip(["database.sqlite", "database.sqlite-wal"])
|
||||
{
|
||||
let mut target = File::create(staging.path().join(name))?;
|
||||
copy_buffered(file, &mut target).context("cannot stage source database and WAL")?;
|
||||
}
|
||||
let mut copy = SqliteConnection::connect_with(
|
||||
&SqliteConnectOptions::new()
|
||||
.filename(&staged_database)
|
||||
.locking_mode(SqliteLockingMode::Exclusive)
|
||||
.journal_mode(SqliteJournalMode::Delete)
|
||||
.synchronous(SqliteSynchronous::Full)
|
||||
.disable_statement_logging(),
|
||||
)
|
||||
.await
|
||||
.context("cannot convert staged database to DELETE")?;
|
||||
let validated = validate_delete_database(&mut copy)
|
||||
.await
|
||||
.context("staged database failed validation");
|
||||
let closed = copy.close().await;
|
||||
validated?;
|
||||
closed?;
|
||||
|
||||
replacement.prepare_backup_directory()?;
|
||||
let mut temporary = tempfile::NamedTempFile::new_in(&replacement.backup_directory)?;
|
||||
copy_buffered(&mut File::open(&staged_database)?, temporary.as_file_mut())
|
||||
.context("cannot write replacement copy")?;
|
||||
// Use the open handle. Closing another source descriptor can release SQLite's locks.
|
||||
temporary
|
||||
.as_file()
|
||||
.set_permissions(source_permissions)?;
|
||||
temporary.as_file().sync_all()?;
|
||||
temporary
|
||||
.into_temp_path()
|
||||
.persist_noclobber(replacement.replacement_path())
|
||||
.context("cannot save replacement copy")?;
|
||||
File::open(&replacement.backup_directory)?.sync_all()?;
|
||||
for file in &source_files {
|
||||
file.sync_all()?;
|
||||
}
|
||||
replacement.move_original_to_backup()?;
|
||||
Ok(true)
|
||||
}
|
||||
.await;
|
||||
let closed = connection.close().await;
|
||||
drop(source_files);
|
||||
let changed = result?;
|
||||
closed.context("cannot close source database. Keep clients stopped")?;
|
||||
if changed {
|
||||
replacement.install()?;
|
||||
return Ok(NfsDbMigrationOutcome::Migrated {
|
||||
backup_directory: replacement.backup_directory,
|
||||
});
|
||||
}
|
||||
Ok(NfsDbMigrationOutcome::AlreadyDelete)
|
||||
}
|
||||
}
|
||||
|
||||
async fn validate_delete_database(connection: &mut SqliteConnection) -> anyhow::Result<()> {
|
||||
let mode: String = sqlx::query_scalar("PRAGMA journal_mode")
|
||||
.fetch_one(&mut *connection)
|
||||
.await?;
|
||||
ensure!(
|
||||
mode == "delete",
|
||||
"database did not enter DELETE journal mode"
|
||||
);
|
||||
let integrity: String = sqlx::query_scalar("PRAGMA integrity_check(1)")
|
||||
.fetch_one(connection)
|
||||
.await
|
||||
.context("database failed integrity check")?;
|
||||
ensure!(
|
||||
integrity == "ok",
|
||||
"database failed integrity check: {integrity}"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn copy_buffered(source: &mut File, destination: &mut File) -> std::io::Result<()> {
|
||||
// Use large reads to avoid the fallback to small reads for copy_file_range on NFSv4.1.
|
||||
let mut buffer = vec![0; 1024 * 1024];
|
||||
loop {
|
||||
let bytes = match source.read(&mut buffer) {
|
||||
Err(error) if error.kind() == ErrorKind::Interrupted => continue,
|
||||
result => result?,
|
||||
};
|
||||
if bytes == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
destination.write_all(&buffer[..bytes])?;
|
||||
}
|
||||
}
|
||||
244
akode-rs/state/src/nfs_migration/replacement.rs
Normal file
244
akode-rs/state/src/nfs_migration/replacement.rs
Normal file
@@ -0,0 +1,244 @@
|
||||
//! Move the WAL files into a backup directory, then install the validated DELETE copy.
|
||||
//! Resume an interrupted replacement from the files that remain on disk.
|
||||
//! All clients must remain stopped. The caller must hold the migration lock.
|
||||
//! Sync both directories after each step before changing more files.
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::ensure;
|
||||
use sqlx::ConnectOptions;
|
||||
use sqlx::Connection;
|
||||
use sqlx::SqliteConnection;
|
||||
use sqlx::sqlite::SqliteConnectOptions;
|
||||
use std::fs;
|
||||
use std::fs::File;
|
||||
use std::io::ErrorKind;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
const MARKER: &[u8] = b"codex-nfs-migration-v1\n";
|
||||
const SIDECARS: [&str; 3] = ["-wal", "-shm", "-journal"];
|
||||
|
||||
pub(super) enum Recovery {
|
||||
// The caller must check and lock the source before starting a new replacement.
|
||||
InspectSource,
|
||||
// Recovery installed the saved copy. No new replacement is necessary.
|
||||
Installed,
|
||||
}
|
||||
|
||||
pub(super) struct Replacement {
|
||||
source: PathBuf,
|
||||
pub(super) backup_directory: PathBuf,
|
||||
pub(super) backup_database: PathBuf,
|
||||
}
|
||||
|
||||
impl Replacement {
|
||||
pub(super) fn new(source: &Path) -> anyhow::Result<Self> {
|
||||
let name = source.file_name().context("database needs a file name")?;
|
||||
let mut directory = source.as_os_str().to_owned();
|
||||
directory.push("_wal_migration_backup");
|
||||
let directory = PathBuf::from(directory);
|
||||
Ok(Self {
|
||||
source: source.to_path_buf(),
|
||||
backup_database: directory.join(name),
|
||||
backup_directory: directory,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn replacement_path(&self) -> PathBuf {
|
||||
self.backup_directory.join("delete.sqlite")
|
||||
}
|
||||
|
||||
// Call only while the original database is locked. Rebuild an unused copy on every attempt.
|
||||
pub(super) fn prepare_backup_directory(&self) -> anyhow::Result<()> {
|
||||
if self.backup_directory.try_exists()? {
|
||||
ensure!(
|
||||
!regular_file_exists(&self.backup_database)?,
|
||||
"WAL backup already exists"
|
||||
);
|
||||
if regular_file_exists(&self.replacement_path())? {
|
||||
fs::remove_file(self.replacement_path())?;
|
||||
}
|
||||
} else {
|
||||
let builder = fs::DirBuilder::new();
|
||||
#[cfg(unix)]
|
||||
let builder = {
|
||||
use std::os::unix::fs::DirBuilderExt;
|
||||
let mut builder = builder;
|
||||
builder.mode(0o700);
|
||||
builder
|
||||
};
|
||||
builder.create(&self.backup_directory)?;
|
||||
let mut marker = File::create_new(self.backup_directory.join("migration-v1"))?;
|
||||
marker.write_all(MARKER)?;
|
||||
marker.sync_all()?;
|
||||
}
|
||||
self.sync_directories()
|
||||
}
|
||||
|
||||
pub(super) fn move_original_to_backup(&self) -> anyhow::Result<()> {
|
||||
ensure!(
|
||||
!regular_file_exists(&self.backup_database)?,
|
||||
"WAL backup already exists"
|
||||
);
|
||||
// Move the main file first. An incomplete switch must not look like an intact source.
|
||||
fs::rename(&self.source, &self.backup_database)?;
|
||||
self.sync_directories()?;
|
||||
self.move_sidecars_to_backup()
|
||||
}
|
||||
|
||||
fn move_sidecars_to_backup(&self) -> anyhow::Result<()> {
|
||||
for suffix in SIDECARS {
|
||||
let source = with_suffix(&self.source, suffix);
|
||||
let destination = with_suffix(&self.backup_database, suffix);
|
||||
if regular_file_exists(&source)? {
|
||||
ensure!(
|
||||
!regular_file_exists(&destination)?,
|
||||
"backup sidecar already exists: {}",
|
||||
destination.display()
|
||||
);
|
||||
fs::rename(source, destination)?;
|
||||
}
|
||||
}
|
||||
self.sync_directories()
|
||||
}
|
||||
|
||||
pub(super) fn install(&self) -> anyhow::Result<()> {
|
||||
for suffix in ["", "-wal", "-shm", "-journal"] {
|
||||
ensure!(
|
||||
!regular_file_exists(&with_suffix(&self.source, suffix))?,
|
||||
"database or sidecar already exists at the installation path"
|
||||
);
|
||||
}
|
||||
// A hard link installs the file atomically without replacing an unexpected database.
|
||||
fs::hard_link(self.replacement_path(), &self.source)?;
|
||||
self.finish_installation()
|
||||
}
|
||||
|
||||
fn finish_installation(&self) -> anyhow::Result<()> {
|
||||
self.sync_directories()?;
|
||||
fs::remove_file(self.replacement_path())?;
|
||||
self.sync_directories()
|
||||
}
|
||||
|
||||
fn sync_directories(&self) -> anyhow::Result<()> {
|
||||
File::open(&self.backup_directory)?.sync_all()?;
|
||||
File::open(
|
||||
self.source
|
||||
.parent()
|
||||
.context("database needs a parent directory")?,
|
||||
)?
|
||||
.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::disallowed_methods,
|
||||
reason = "Inspect the prepared copy without runtime initialization"
|
||||
)]
|
||||
pub(super) async fn resume(&self) -> anyhow::Result<Recovery> {
|
||||
match fs::symlink_metadata(&self.backup_directory) {
|
||||
Err(error) if error.kind() == ErrorKind::NotFound => {
|
||||
return Ok(Recovery::InspectSource);
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
Ok(metadata) => ensure!(
|
||||
metadata.is_dir(),
|
||||
"backup path already exists and is not a directory"
|
||||
),
|
||||
}
|
||||
let marker = self.backup_directory.join("migration-v1");
|
||||
ensure!(
|
||||
regular_file_exists(&marker)? && fs::read(&marker)? == MARKER,
|
||||
"backup directory already exists without a valid migration marker: {}",
|
||||
self.backup_directory.display()
|
||||
);
|
||||
let backup_exists = regular_file_exists(&self.backup_database)?;
|
||||
let replacement_exists = regular_file_exists(&self.replacement_path())?;
|
||||
let source_exists = regular_file_exists(&self.source)?;
|
||||
// No original files moved yet. The caller must lock the source and rebuild the copy.
|
||||
if !backup_exists {
|
||||
for suffix in SIDECARS {
|
||||
ensure!(
|
||||
!regular_file_exists(&with_suffix(&self.backup_database, suffix))?,
|
||||
"backup has a SQLite sidecar without its original database"
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
source_exists,
|
||||
"original database is missing from both source and backup"
|
||||
);
|
||||
return Ok(Recovery::InspectSource);
|
||||
}
|
||||
// Installation finished, or the replacement is missing. The caller must check the source.
|
||||
if !replacement_exists {
|
||||
ensure!(
|
||||
source_exists,
|
||||
"replacement is missing. Preserve the WAL backup and restore it before retrying"
|
||||
);
|
||||
return Ok(Recovery::InspectSource);
|
||||
}
|
||||
// An existing source must be the link installed before the interruption.
|
||||
if source_exists {
|
||||
let same_file = {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let source = fs::metadata(&self.source)?;
|
||||
let prepared = fs::metadata(self.replacement_path())?;
|
||||
(source.dev(), source.ino()) == (prepared.dev(), prepared.ino())
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
false
|
||||
}
|
||||
};
|
||||
ensure!(
|
||||
same_file,
|
||||
"another database already exists at the installation path"
|
||||
);
|
||||
self.finish_installation()?;
|
||||
return Ok(Recovery::Installed);
|
||||
}
|
||||
|
||||
// The original is in the backup. Check the replacement before installing it.
|
||||
let mut copy = SqliteConnection::connect_with(
|
||||
&SqliteConnectOptions::new()
|
||||
.filename(self.replacement_path())
|
||||
.read_only(true)
|
||||
.immutable(true)
|
||||
.disable_statement_logging(),
|
||||
)
|
||||
.await?;
|
||||
let checked = super::validate_delete_database(&mut copy)
|
||||
.await
|
||||
.context("saved replacement failed validation");
|
||||
let closed = copy.close().await;
|
||||
checked?;
|
||||
closed?;
|
||||
self.move_sidecars_to_backup()?;
|
||||
self.install()?;
|
||||
Ok(Recovery::Installed)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn regular_file_exists(path: &Path) -> anyhow::Result<bool> {
|
||||
match fs::symlink_metadata(path) {
|
||||
Err(error) if error.kind() == ErrorKind::NotFound => Ok(false),
|
||||
Err(error) => Err(error.into()),
|
||||
Ok(metadata) => {
|
||||
ensure!(
|
||||
metadata.is_file(),
|
||||
"path already exists and is not a regular file: {}",
|
||||
path.display()
|
||||
);
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn with_suffix(path: &Path, suffix: &str) -> PathBuf {
|
||||
let mut value = path.as_os_str().to_owned();
|
||||
value.push(suffix);
|
||||
value.into()
|
||||
}
|
||||
9
akode-rs/state/src/paths.rs
Normal file
9
akode-rs/state/src/paths.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use std::path::Path;
|
||||
|
||||
pub(crate) async fn file_modified_time_utc(path: &Path) -> Option<DateTime<Utc>> {
|
||||
let modified = tokio::fs::metadata(path).await.ok()?.modified().ok()?;
|
||||
let updated_at: DateTime<Utc> = modified.into();
|
||||
Some(updated_at)
|
||||
}
|
||||
773
akode-rs/state/src/runtime.rs
Normal file
773
akode-rs/state/src/runtime.rs
Normal file
@@ -0,0 +1,773 @@
|
||||
use crate::LogEntry;
|
||||
use crate::LogQuery;
|
||||
use crate::LogRow;
|
||||
use crate::SortKey;
|
||||
use crate::SqliteConfig;
|
||||
use crate::ThreadMetadata;
|
||||
use crate::ThreadMetadataBuilder;
|
||||
use crate::ThreadsPage;
|
||||
use crate::apply_rollout_item;
|
||||
use crate::migrations::runtime_goals_migrator;
|
||||
use crate::migrations::runtime_logs_migrator;
|
||||
use crate::migrations::runtime_memories_migrator;
|
||||
use crate::migrations::runtime_queue_migrator;
|
||||
use crate::migrations::runtime_state_migrator;
|
||||
use crate::migrations::runtime_thread_history_migrator;
|
||||
use crate::model::ThreadRow;
|
||||
use crate::model::anchor_from_item;
|
||||
use crate::model::datetime_to_epoch_millis;
|
||||
use crate::model::datetime_to_epoch_seconds;
|
||||
use crate::model::epoch_millis_to_datetime;
|
||||
use crate::paths::file_modified_time_utc;
|
||||
use crate::sqlite::SqliteWriteQueryExt;
|
||||
use crate::telemetry::DbKind;
|
||||
use crate::telemetry::DbTelemetry;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use akode_history::RolloutItem;
|
||||
use akode_protocol::ThreadId;
|
||||
use serde_json::Value;
|
||||
use sqlx::QueryBuilder;
|
||||
use sqlx::Row;
|
||||
use sqlx::Sqlite;
|
||||
use sqlx::SqliteConnection;
|
||||
use sqlx::SqlitePool;
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicI64;
|
||||
use std::time::Instant;
|
||||
use tracing::warn;
|
||||
|
||||
mod backfill;
|
||||
mod external_agent_config_imports;
|
||||
mod goals;
|
||||
mod guardian_feedback;
|
||||
mod logs;
|
||||
mod logs_maintenance;
|
||||
mod memories;
|
||||
mod memory_versions;
|
||||
mod projects;
|
||||
mod queued_items;
|
||||
pub(crate) mod reclamation;
|
||||
pub(crate) mod recovery;
|
||||
mod remote_control;
|
||||
mod rollout_migration;
|
||||
#[cfg(test)]
|
||||
pub(crate) mod test_support;
|
||||
mod thread_attachments;
|
||||
mod thread_metadata;
|
||||
mod thread_read_state;
|
||||
mod thread_section_order;
|
||||
mod thread_sections;
|
||||
mod threads;
|
||||
|
||||
pub use external_agent_config_imports::ExternalAgentConfigImportDetailsRecord;
|
||||
pub use external_agent_config_imports::ExternalAgentConfigImportFailureRecord;
|
||||
pub use external_agent_config_imports::ExternalAgentConfigImportHistoryRecord;
|
||||
pub use external_agent_config_imports::ExternalAgentConfigImportSuccessRecord;
|
||||
pub use goals::GoalAccountingMode;
|
||||
pub use goals::GoalAccountingOutcome;
|
||||
pub use goals::GoalStore;
|
||||
pub use goals::GoalUpdate;
|
||||
pub use guardian_feedback::GuardianReviewRecord;
|
||||
pub use guardian_feedback::MAX_GUARDIAN_REVIEW_BYTES;
|
||||
pub use guardian_feedback::MAX_GUARDIAN_REVIEW_RECORDS;
|
||||
pub use guardian_feedback::MAX_GUARDIAN_REVIEW_RECORDS_PER_THREAD;
|
||||
pub use memories::MemoryStore;
|
||||
pub use queued_items::SqliteQueueStore;
|
||||
pub use recovery::backup_runtime_db_for_fresh_start;
|
||||
pub use recovery::collect_runtime_db_backups;
|
||||
pub use recovery::is_sqlite_corruption_error;
|
||||
pub use recovery::runtime_db_path_for_corruption_error;
|
||||
pub use recovery::sqlite_error_detail_is_lock;
|
||||
pub use remote_control::RemoteControlEnrollmentRecord;
|
||||
pub use thread_read_state::ReadStateOperation;
|
||||
pub use thread_read_state::ReadStateUpdate;
|
||||
pub use thread_read_state::ThreadReadState;
|
||||
pub use threads::ThreadFilterOptions;
|
||||
|
||||
// "Partition" is the retained-log-content bucket we cap at 10 MiB:
|
||||
// - one bucket per non-null thread_id
|
||||
// - one bucket per threadless (thread_id IS NULL) non-null process_uuid
|
||||
// - one bucket for threadless rows with process_uuid IS NULL
|
||||
// This budget tracks each row's persisted rendered log body plus non-body
|
||||
// metadata, rather than the exact sum of all persisted SQLite column bytes.
|
||||
const LOG_PARTITION_SIZE_LIMIT_BYTES: i64 = 10 * 1024 * 1024;
|
||||
const LOG_PARTITION_ROW_LIMIT: i64 = 1_000;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct StateRuntime {
|
||||
sqlite: SqliteConfig,
|
||||
default_provider: String,
|
||||
pool: Arc<sqlx::SqlitePool>,
|
||||
logs_pool: Arc<sqlx::SqlitePool>,
|
||||
thread_goals: GoalStore,
|
||||
memories: MemoryStore,
|
||||
memories_v2: Arc<tokio::sync::OnceCell<MemoryStore>>,
|
||||
thread_queue: SqliteQueueStore,
|
||||
thread_updated_at_millis: Arc<AtomicI64>,
|
||||
thread_recency_at_millis: Arc<AtomicI64>,
|
||||
reclamation: Arc<reclamation::SqliteReclamationWorker>,
|
||||
}
|
||||
|
||||
impl StateRuntime {
|
||||
/// Initialize the state runtime using the provided SQLite configuration and default provider.
|
||||
///
|
||||
/// This opens (and migrates) the SQLite databases under the configured
|
||||
/// `sqlite_home`.
|
||||
/// Logs and paginated thread history live in dedicated files to reduce
|
||||
/// lock contention with the rest of the state store.
|
||||
pub async fn init(sqlite: SqliteConfig, default_provider: String) -> anyhow::Result<Arc<Self>> {
|
||||
Self::init_inner(sqlite, default_provider, /*telemetry_override*/ None).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn init_with_telemetry_for_tests(
|
||||
sqlite: SqliteConfig,
|
||||
default_provider: String,
|
||||
telemetry_override: &dyn DbTelemetry,
|
||||
) -> anyhow::Result<Arc<Self>> {
|
||||
Self::init_inner(sqlite, default_provider, Some(telemetry_override)).await
|
||||
}
|
||||
|
||||
async fn init_inner(
|
||||
sqlite: SqliteConfig,
|
||||
default_provider: String,
|
||||
telemetry_override: Option<&dyn DbTelemetry>,
|
||||
) -> anyhow::Result<Arc<Self>> {
|
||||
tokio::fs::create_dir_all(sqlite.home()).await?;
|
||||
let state_migrator = runtime_state_migrator();
|
||||
let logs_migrator = runtime_logs_migrator();
|
||||
let goals_migrator = runtime_goals_migrator();
|
||||
let memories_migrator = runtime_memories_migrator();
|
||||
let queue_migrator = runtime_queue_migrator();
|
||||
let state_path = sqlite.state_db_path();
|
||||
let logs_path = sqlite.logs_db_path();
|
||||
let goals_path = sqlite.goals_db_path();
|
||||
let memories_path = sqlite.memories_db_path();
|
||||
let queue_path = sqlite.queue_db_path();
|
||||
let pool = match sqlite
|
||||
.open_state_db(&state_migrator, telemetry_override)
|
||||
.await
|
||||
{
|
||||
Ok(db) => Arc::new(db),
|
||||
Err(err) => {
|
||||
warn!("failed to open state db at {}: {err}", state_path.display());
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
let has_memories_v2 = tokio::fs::try_exists(sqlite.memories_v2_db_path()).await?;
|
||||
let logs_pool = match sqlite
|
||||
.open_logs_db(&logs_migrator, telemetry_override)
|
||||
.await
|
||||
{
|
||||
Ok(db) => Arc::new(db),
|
||||
Err(err) => {
|
||||
warn!("failed to open logs db at {}: {err}", logs_path.display());
|
||||
close_sqlite_pools(&[pool.as_ref()]).await;
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
let goals_pool = match sqlite
|
||||
.open_goals_db(&goals_migrator, telemetry_override)
|
||||
.await
|
||||
{
|
||||
Ok(db) => Arc::new(db),
|
||||
Err(err) => {
|
||||
warn!("failed to open goals db at {}: {err}", goals_path.display());
|
||||
close_sqlite_pools(&[pool.as_ref(), logs_pool.as_ref()]).await;
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
let memories_pool = match sqlite
|
||||
.open_memories_db(&memories_migrator, telemetry_override)
|
||||
.await
|
||||
{
|
||||
Ok(db) => Arc::new(db),
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"failed to open memories db at {}: {err}",
|
||||
memories_path.display()
|
||||
);
|
||||
close_sqlite_pools(&[pool.as_ref(), logs_pool.as_ref(), goals_pool.as_ref()]).await;
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
let queue_pool = match sqlite
|
||||
.open_queue_db(&queue_migrator, telemetry_override)
|
||||
.await
|
||||
{
|
||||
Ok(db) => Arc::new(db),
|
||||
Err(err) => {
|
||||
warn!("failed to open queue db at {}: {err}", queue_path.display());
|
||||
close_sqlite_pools(&[
|
||||
pool.as_ref(),
|
||||
logs_pool.as_ref(),
|
||||
goals_pool.as_ref(),
|
||||
memories_pool.as_ref(),
|
||||
])
|
||||
.await;
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
let started = Instant::now();
|
||||
let backfill_state_result = ensure_backfill_state_row_in_pool(pool.as_ref()).await;
|
||||
crate::telemetry::record_init_result(
|
||||
telemetry_override,
|
||||
DbKind::State,
|
||||
"ensure_backfill_state",
|
||||
started.elapsed(),
|
||||
&backfill_state_result,
|
||||
);
|
||||
if let Err(err) = backfill_state_result {
|
||||
close_sqlite_pools(&[
|
||||
pool.as_ref(),
|
||||
logs_pool.as_ref(),
|
||||
goals_pool.as_ref(),
|
||||
memories_pool.as_ref(),
|
||||
queue_pool.as_ref(),
|
||||
])
|
||||
.await;
|
||||
return Err(err);
|
||||
}
|
||||
let started = Instant::now();
|
||||
let thread_timestamp_millis_result: anyhow::Result<(Option<i64>, Option<i64>)> =
|
||||
sqlx::query_as(
|
||||
"SELECT (SELECT MAX(updated_at_ms) FROM threads), (SELECT MAX(recency_at_ms) FROM threads)",
|
||||
)
|
||||
.fetch_one(pool.as_ref())
|
||||
.await
|
||||
.map_err(anyhow::Error::from);
|
||||
crate::telemetry::record_init_result(
|
||||
telemetry_override,
|
||||
DbKind::State,
|
||||
"post_init_query",
|
||||
started.elapsed(),
|
||||
&thread_timestamp_millis_result,
|
||||
);
|
||||
let (thread_updated_at_millis, thread_recency_at_millis) =
|
||||
match thread_timestamp_millis_result {
|
||||
Ok(value) => value,
|
||||
Err(err) => {
|
||||
close_sqlite_pools(&[
|
||||
pool.as_ref(),
|
||||
logs_pool.as_ref(),
|
||||
goals_pool.as_ref(),
|
||||
memories_pool.as_ref(),
|
||||
queue_pool.as_ref(),
|
||||
])
|
||||
.await;
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
let thread_updated_at_millis = thread_updated_at_millis.unwrap_or(0);
|
||||
let thread_recency_at_millis = thread_recency_at_millis.unwrap_or(0);
|
||||
let runtime = Arc::new(Self {
|
||||
reclamation: reclamation::SqliteReclamationWorker::spawn(sqlite.clone()),
|
||||
thread_goals: GoalStore::new(Arc::clone(&goals_pool)),
|
||||
memories: MemoryStore::new(Arc::clone(&memories_pool), Arc::clone(&pool)),
|
||||
memories_v2: Arc::new(tokio::sync::OnceCell::new()),
|
||||
thread_queue: SqliteQueueStore::new(queue_pool),
|
||||
pool,
|
||||
logs_pool,
|
||||
sqlite,
|
||||
default_provider,
|
||||
thread_updated_at_millis: Arc::new(AtomicI64::new(thread_updated_at_millis)),
|
||||
thread_recency_at_millis: Arc::new(AtomicI64::new(thread_recency_at_millis)),
|
||||
});
|
||||
// Existing v2 state must participate in startup corruption recovery.
|
||||
// Keep creation lazy for users who have never used v2.
|
||||
if has_memories_v2
|
||||
&& let Err(err) = runtime
|
||||
.memories_for_version(akode_protocol::MemoryVersion::V2)
|
||||
.await
|
||||
{
|
||||
runtime.close().await;
|
||||
return Err(err);
|
||||
}
|
||||
runtime.start_periodic_logs_maintenance(std::time::Duration::from_secs(30 * 60));
|
||||
Ok(runtime)
|
||||
}
|
||||
|
||||
/// Return the SQLite configuration for this runtime.
|
||||
pub fn sqlite(&self) -> &SqliteConfig {
|
||||
&self.sqlite
|
||||
}
|
||||
|
||||
pub fn thread_goals(&self) -> &GoalStore {
|
||||
&self.thread_goals
|
||||
}
|
||||
|
||||
pub fn memories(&self) -> &MemoryStore {
|
||||
&self.memories
|
||||
}
|
||||
|
||||
/// Return the durable, SQLite-backed user-message queue.
|
||||
pub fn thread_queue(&self) -> &SqliteQueueStore {
|
||||
&self.thread_queue
|
||||
}
|
||||
|
||||
/// Close all SQLite pools and wait for outstanding pool workers to exit.
|
||||
pub async fn close(&self) {
|
||||
self.reclamation.close().await;
|
||||
self.thread_queue.close().await;
|
||||
self.memories.close().await;
|
||||
if let Some(memories) = self.memories_v2.get() {
|
||||
memories.close().await;
|
||||
}
|
||||
self.thread_goals.close().await;
|
||||
self.logs_pool.close().await;
|
||||
self.pool.close().await;
|
||||
}
|
||||
|
||||
pub async fn clear_memory_data_in_sqlite_home(sqlite: &SqliteConfig) -> anyhow::Result<bool> {
|
||||
let mut cleared = false;
|
||||
for version in [
|
||||
akode_protocol::MemoryVersion::V1,
|
||||
akode_protocol::MemoryVersion::V2,
|
||||
] {
|
||||
let path = match version {
|
||||
akode_protocol::MemoryVersion::V1 => sqlite.memories_db_path(),
|
||||
akode_protocol::MemoryVersion::V2 => sqlite.memories_v2_db_path(),
|
||||
};
|
||||
if !tokio::fs::try_exists(path).await? {
|
||||
continue;
|
||||
}
|
||||
let pool = match version {
|
||||
akode_protocol::MemoryVersion::V1 => {
|
||||
sqlite
|
||||
.open_memories_db(
|
||||
&runtime_memories_migrator(),
|
||||
/*telemetry_override*/ None,
|
||||
)
|
||||
.await?
|
||||
}
|
||||
akode_protocol::MemoryVersion::V2 => sqlite.open_memories_v2_db().await?,
|
||||
};
|
||||
let result = memories::clear_memory_data_in_pool(&pool).await;
|
||||
pool.close().await;
|
||||
result?;
|
||||
cleared = true;
|
||||
}
|
||||
Ok(cleared)
|
||||
}
|
||||
}
|
||||
|
||||
async fn close_sqlite_pools(pools: &[&SqlitePool]) {
|
||||
for pool in pools {
|
||||
pool.close().await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Open and migrate the rebuildable paginated thread-history database.
|
||||
pub async fn open_thread_history_db(sqlite: &SqliteConfig) -> anyhow::Result<SqlitePool> {
|
||||
let migrator = runtime_thread_history_migrator();
|
||||
sqlite
|
||||
.open_thread_history_db(&migrator, /*telemetry_override*/ None)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn ensure_backfill_state_row_in_pool(
|
||||
pool: &sqlx::SqlitePool,
|
||||
) -> anyhow::Result<()> {
|
||||
// Eagerly check if the operation would have no effect to avoid blocking waiting for a SQLite
|
||||
// writer for no reason in the hot startup path.
|
||||
if sqlx::query_scalar::<_, i64>("SELECT 1 FROM backfill_state WHERE id = 1")
|
||||
.fetch_optional(pool)
|
||||
.await?
|
||||
.is_some()
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
sqlx::query(
|
||||
r#"
|
||||
INSERT INTO backfill_state (id, status, last_watermark, last_success_at, updated_at)
|
||||
VALUES (?, ?, NULL, NULL, ?)
|
||||
ON CONFLICT(id) DO NOTHING
|
||||
"#,
|
||||
)
|
||||
.bind(1_i64)
|
||||
.bind(crate::BackfillStatus::Pending.as_str())
|
||||
.bind(Utc::now().timestamp())
|
||||
.execute_with_busy_retry(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Integrity-check rows, including those emitted before interruption.
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
pub enum SqliteIntegrityCheck {
|
||||
Complete(Vec<String>),
|
||||
TimedOut(Vec<String>),
|
||||
}
|
||||
|
||||
/// Run SQLite's built-in integrity check against an existing database file.
|
||||
pub async fn sqlite_integrity_check(
|
||||
sqlite: &SqliteConfig,
|
||||
path: &Path,
|
||||
deadline: Option<Instant>,
|
||||
) -> anyhow::Result<SqliteIntegrityCheck> {
|
||||
let pool = sqlite
|
||||
.open_read_only_pool(
|
||||
path,
|
||||
deadline.map(|deadline| deadline.saturating_duration_since(Instant::now())),
|
||||
)
|
||||
.await?;
|
||||
let mut connection = pool.acquire().await?;
|
||||
if let Some(deadline) = deadline {
|
||||
// Lock waits do not invoke the progress handler; share the remaining budget.
|
||||
QueryBuilder::<Sqlite>::new("PRAGMA busy_timeout = ")
|
||||
.push(
|
||||
deadline
|
||||
.saturating_duration_since(Instant::now())
|
||||
.as_millis(),
|
||||
)
|
||||
.build()
|
||||
.execute(&mut *connection)
|
||||
.await?;
|
||||
// Interrupt SQLite itself: dropping a timed-out future leaves its worker scanning.
|
||||
connection
|
||||
.lock_handle()
|
||||
.await?
|
||||
.set_progress_handler(/*num_ops*/ 1_000, move || Instant::now() < deadline);
|
||||
}
|
||||
let mut rows = Vec::<String>::new();
|
||||
// Keep corruption rows even when a later step interrupts the scan.
|
||||
let result = sqlx::query::<Sqlite>("PRAGMA integrity_check")
|
||||
.try_map(|row| {
|
||||
rows.push(row.try_get(/*index*/ 0)?);
|
||||
Ok(())
|
||||
})
|
||||
.fetch_all(&mut *connection)
|
||||
.await;
|
||||
drop(connection);
|
||||
pool.close().await;
|
||||
match result {
|
||||
Ok(_) => Ok(SqliteIntegrityCheck::Complete(rows)),
|
||||
Err(sqlx::Error::Database(error))
|
||||
if deadline.is_some()
|
||||
&& error.code().is_some_and(|code| {
|
||||
matches!(
|
||||
code.parse::<i32>().ok().map(|code| code & 0xff),
|
||||
Some(libsqlite3_sys::SQLITE_INTERRUPT | libsqlite3_sys::SQLITE_BUSY)
|
||||
)
|
||||
}) =>
|
||||
{
|
||||
Ok(SqliteIntegrityCheck::TimedOut(rows))
|
||||
}
|
||||
Err(error) => Err(error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::SqliteIntegrityCheck;
|
||||
use super::StateRuntime;
|
||||
use super::runtime_state_migrator;
|
||||
use super::sqlite_integrity_check;
|
||||
use super::test_support::test_thread_metadata;
|
||||
use super::test_support::unique_temp_dir;
|
||||
use crate::DB_INIT_METRIC;
|
||||
use crate::DbTelemetry;
|
||||
use crate::migrations::STATE_MIGRATOR;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_utils_absolute_path::test_support::PathExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use sqlx::SqlitePool;
|
||||
use sqlx::migrate::MigrateError;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
#[derive(Default)]
|
||||
struct TestTelemetry {
|
||||
counters: Mutex<Vec<MetricEvent>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
struct MetricEvent {
|
||||
name: String,
|
||||
tags: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl TestTelemetry {
|
||||
fn counters(&self) -> Vec<MetricEvent> {
|
||||
self.counters
|
||||
.lock()
|
||||
.expect("telemetry lock")
|
||||
.iter()
|
||||
.map(|event| MetricEvent {
|
||||
name: event.name.clone(),
|
||||
tags: event.tags.clone(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl DbTelemetry for TestTelemetry {
|
||||
fn counter(&self, name: &str, _inc: i64, tags: &[(&str, &str)]) {
|
||||
self.counters
|
||||
.lock()
|
||||
.expect("telemetry lock")
|
||||
.push(MetricEvent {
|
||||
name: name.to_string(),
|
||||
tags: tags_to_map(tags),
|
||||
});
|
||||
}
|
||||
|
||||
fn record_duration(
|
||||
&self,
|
||||
_name: &str,
|
||||
_duration: std::time::Duration,
|
||||
_tags: &[(&str, &str)],
|
||||
) {
|
||||
}
|
||||
|
||||
fn histogram(&self, _name: &str, _value: i64, _tags: &[(&str, &str)]) {}
|
||||
}
|
||||
|
||||
fn tags_to_map(tags: &[(&str, &str)]) -> BTreeMap<String, String> {
|
||||
tags.iter()
|
||||
.map(|(key, value)| ((*key).to_string(), (*value).to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn open_db_pool(path: &Path) -> SqlitePool {
|
||||
crate::SqliteConfig::new_for_testing(path.parent().unwrap_or(path).abs())
|
||||
.open_read_write_pool(path)
|
||||
.await
|
||||
.expect("open sqlite pool")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sqlite_integrity_check_can_be_interrupted_and_retried() {
|
||||
let codex_home = unique_temp_dir();
|
||||
tokio::fs::create_dir_all(&codex_home)
|
||||
.await
|
||||
.expect("create codex home");
|
||||
let sqlite = crate::SqliteConfig::new_for_testing(codex_home.as_path().abs());
|
||||
let path = sqlite.state_db_path();
|
||||
let pool = sqlite
|
||||
.open_read_write_pool(&path)
|
||||
.await
|
||||
.expect("open sqlite db");
|
||||
sqlx::query("CREATE TABLE sample (id INTEGER PRIMARY KEY, value INTEGER, other INTEGER)")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("create sample table");
|
||||
sqlx::query("CREATE UNIQUE INDEX sample_value ON sample(value)")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("create sample index");
|
||||
sqlx::query(
|
||||
"WITH RECURSIVE rows(id) AS (SELECT 1 UNION ALL SELECT id + 1 FROM rows WHERE id < 2048) INSERT INTO sample SELECT id, id, CASE WHEN id = 1 THEN 0 ELSE id END FROM rows",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("populate enough rows to invoke the progress handler");
|
||||
pool.close().await;
|
||||
|
||||
assert_eq!(
|
||||
sqlite_integrity_check(&sqlite, &path, Some(Instant::now()))
|
||||
.await
|
||||
.expect("interrupt integrity check"),
|
||||
SqliteIntegrityCheck::TimedOut(Vec::new()),
|
||||
);
|
||||
|
||||
let result = sqlite_integrity_check(&sqlite, &path, /*deadline*/ None)
|
||||
.await
|
||||
.expect("integrity check should run");
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
SqliteIntegrityCheck::Complete(vec!["ok".to_string()])
|
||||
);
|
||||
|
||||
let pool = sqlite
|
||||
.open_read_write_pool(&path)
|
||||
.await
|
||||
.expect("reopen sqlite db");
|
||||
let mut connection = pool.acquire().await.expect("acquire writer");
|
||||
// WAL readers do not wait on this writer, so use a rollback journal.
|
||||
sqlx::query("PRAGMA journal_mode=DELETE; BEGIN EXCLUSIVE")
|
||||
.execute(&mut *connection)
|
||||
.await
|
||||
.expect("hold an exclusive lock");
|
||||
let started = Instant::now();
|
||||
let result =
|
||||
sqlite_integrity_check(&sqlite, &path, Some(started + Duration::from_millis(50)))
|
||||
.await
|
||||
.expect("interrupt lock wait");
|
||||
let elapsed = started.elapsed();
|
||||
sqlx::query("ROLLBACK")
|
||||
.execute(&mut *connection)
|
||||
.await
|
||||
.expect("release lock");
|
||||
assert_eq!(result, SqliteIntegrityCheck::TimedOut(Vec::new()));
|
||||
assert!(elapsed < Duration::from_secs(1), "lock wait: {elapsed:?}");
|
||||
|
||||
// Misdescribe one index entry so SQLite emits an error before its first progress callback.
|
||||
sqlx::query(
|
||||
"PRAGMA writable_schema=ON; UPDATE sqlite_schema SET sql='CREATE UNIQUE INDEX sample_value ON sample(other)' WHERE name='sample_value'; PRAGMA writable_schema=OFF",
|
||||
)
|
||||
.execute(&mut *connection)
|
||||
.await
|
||||
.expect("introduce an index mismatch");
|
||||
drop(connection);
|
||||
pool.close().await;
|
||||
assert_eq!(
|
||||
sqlite_integrity_check(&sqlite, &path, Some(Instant::now()))
|
||||
.await
|
||||
.expect("retain corruption before interruption"),
|
||||
SqliteIntegrityCheck::TimedOut(vec![
|
||||
"row 1 missing from index sample_value".to_string()
|
||||
]),
|
||||
);
|
||||
let _ = tokio::fs::remove_dir_all(codex_home).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn open_state_sqlite_tolerates_newer_applied_migrations() {
|
||||
let codex_home = unique_temp_dir();
|
||||
tokio::fs::create_dir_all(&codex_home)
|
||||
.await
|
||||
.expect("create codex home");
|
||||
let sqlite = crate::SqliteConfig::new_for_testing(codex_home.as_path().abs());
|
||||
let state_path = sqlite.state_db_path();
|
||||
let pool = sqlite
|
||||
.open_read_write_pool(&state_path)
|
||||
.await
|
||||
.expect("open state db");
|
||||
STATE_MIGRATOR
|
||||
.run(&pool)
|
||||
.await
|
||||
.expect("apply current state schema");
|
||||
sqlx::query(
|
||||
"INSERT INTO _sqlx_migrations (version, description, success, checksum, execution_time) VALUES (?, ?, ?, ?, ?)",
|
||||
)
|
||||
.bind(9_999_i64)
|
||||
.bind("future migration")
|
||||
.bind(true)
|
||||
.bind(vec![1_u8, 2, 3, 4])
|
||||
.bind(1_i64)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("insert future migration record");
|
||||
pool.close().await;
|
||||
|
||||
let strict_pool = open_db_pool(state_path.as_path()).await;
|
||||
let strict_err = STATE_MIGRATOR
|
||||
.run(&strict_pool)
|
||||
.await
|
||||
.expect_err("strict migrator should reject newer applied migrations");
|
||||
assert!(matches!(strict_err, MigrateError::VersionMissing(9_999)));
|
||||
strict_pool.close().await;
|
||||
|
||||
let tolerant_migrator = runtime_state_migrator();
|
||||
let tolerant_pool = sqlite
|
||||
.open_state_db(&tolerant_migrator, /*telemetry_override*/ None)
|
||||
.await
|
||||
.expect("runtime migrator should tolerate newer applied migrations");
|
||||
tolerant_pool.close().await;
|
||||
|
||||
let _ = tokio::fs::remove_dir_all(codex_home).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn init_records_successful_sqlite_init_phases_to_explicit_telemetry() {
|
||||
let codex_home = unique_temp_dir();
|
||||
let telemetry = TestTelemetry::default();
|
||||
|
||||
let runtime = StateRuntime::init_with_telemetry_for_tests(
|
||||
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
|
||||
"test-provider".to_string(),
|
||||
&telemetry,
|
||||
)
|
||||
.await
|
||||
.expect("state runtime should initialize");
|
||||
|
||||
let phases = telemetry
|
||||
.counters()
|
||||
.into_iter()
|
||||
.filter(|event| event.name == DB_INIT_METRIC)
|
||||
.filter(|event| event.tags.get("status").map(String::as_str) == Some("success"))
|
||||
.filter_map(|event| event.tags.get("phase").cloned())
|
||||
.collect::<BTreeSet<_>>();
|
||||
let expected = [
|
||||
"open_state",
|
||||
"migrate_state",
|
||||
"open_logs",
|
||||
"migrate_logs",
|
||||
"open_goals",
|
||||
"migrate_goals",
|
||||
"open_memories",
|
||||
"migrate_memories",
|
||||
"open_queue",
|
||||
"migrate_queue",
|
||||
"ensure_backfill_state",
|
||||
"post_init_query",
|
||||
]
|
||||
.into_iter()
|
||||
.map(str::to_string)
|
||||
.collect::<BTreeSet<_>>();
|
||||
assert_eq!(phases, expected);
|
||||
|
||||
runtime.close().await;
|
||||
let _ = tokio::fs::remove_dir_all(codex_home).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn init_restores_independent_thread_timestamp_maxima() {
|
||||
let codex_home = unique_temp_dir();
|
||||
let sqlite = crate::SqliteConfig::new_for_testing(codex_home.as_path().abs());
|
||||
let runtime = StateRuntime::init(sqlite.clone(), "test-provider".to_string())
|
||||
.await
|
||||
.expect("state runtime should initialize");
|
||||
|
||||
for (thread_id, updated_at_ms, recency_at_ms) in [
|
||||
("00000000-0000-0000-0000-000000000101", 3_000, 1_000),
|
||||
("00000000-0000-0000-0000-000000000102", 1_000, 4_000),
|
||||
] {
|
||||
let thread_id = ThreadId::from_string(thread_id).expect("valid thread id");
|
||||
runtime
|
||||
.upsert_thread(&test_thread_metadata(
|
||||
&codex_home,
|
||||
thread_id,
|
||||
codex_home.clone(),
|
||||
))
|
||||
.await
|
||||
.expect("thread should be stored");
|
||||
sqlx::query("UPDATE threads SET updated_at_ms = ?, recency_at_ms = ? WHERE id = ?")
|
||||
.bind(updated_at_ms)
|
||||
.bind(recency_at_ms)
|
||||
.bind(thread_id.to_string())
|
||||
.execute(runtime.pool.as_ref())
|
||||
.await
|
||||
.expect("thread timestamps should be updated");
|
||||
}
|
||||
|
||||
runtime.close().await;
|
||||
drop(runtime);
|
||||
|
||||
let runtime = StateRuntime::init(sqlite, "test-provider".to_string())
|
||||
.await
|
||||
.expect("state runtime should restore thread timestamps");
|
||||
assert_eq!(
|
||||
(
|
||||
runtime.thread_updated_at_millis.load(Ordering::Relaxed),
|
||||
runtime.thread_recency_at_millis.load(Ordering::Relaxed),
|
||||
),
|
||||
(3_000, 4_000)
|
||||
);
|
||||
|
||||
runtime.close().await;
|
||||
let _ = tokio::fs::remove_dir_all(codex_home).await;
|
||||
}
|
||||
}
|
||||
289
akode-rs/state/src/runtime/backfill.rs
Normal file
289
akode-rs/state/src/runtime/backfill.rs
Normal file
@@ -0,0 +1,289 @@
|
||||
use super::*;
|
||||
use crate::sqlite::SqliteWriteQueryExt;
|
||||
|
||||
impl StateRuntime {
|
||||
pub async fn get_backfill_state(&self) -> anyhow::Result<crate::BackfillState> {
|
||||
self.ensure_backfill_state_row().await?;
|
||||
let row = sqlx::query(
|
||||
r#"
|
||||
SELECT status, last_watermark, last_success_at
|
||||
FROM backfill_state
|
||||
WHERE id = 1
|
||||
"#,
|
||||
)
|
||||
.fetch_one(self.pool.as_ref())
|
||||
.await?;
|
||||
crate::BackfillState::try_from_row(&row)
|
||||
}
|
||||
|
||||
/// Attempt to claim ownership of rollout metadata backfill.
|
||||
///
|
||||
/// Returns `true` when this runtime claimed the backfill worker slot.
|
||||
/// Returns `false` if backfill is already complete or currently owned by a
|
||||
/// non-expired worker.
|
||||
pub async fn try_claim_backfill(&self, lease_seconds: i64) -> anyhow::Result<bool> {
|
||||
self.ensure_backfill_state_row().await?;
|
||||
let now = Utc::now().timestamp();
|
||||
let lease_cutoff = now.saturating_sub(lease_seconds.max(0));
|
||||
let result = sqlx::query(
|
||||
r#"
|
||||
UPDATE backfill_state
|
||||
SET status = ?, updated_at = ?
|
||||
WHERE id = 1
|
||||
AND status != ?
|
||||
AND (status != ? OR updated_at <= ?)
|
||||
"#,
|
||||
)
|
||||
.bind(crate::BackfillStatus::Running.as_str())
|
||||
.bind(now)
|
||||
.bind(crate::BackfillStatus::Complete.as_str())
|
||||
.bind(crate::BackfillStatus::Running.as_str())
|
||||
.bind(lease_cutoff)
|
||||
.execute_with_busy_retry(self.pool.as_ref())
|
||||
.await?;
|
||||
Ok(result.rows_affected() == 1)
|
||||
}
|
||||
|
||||
/// Mark rollout metadata backfill as running.
|
||||
pub async fn mark_backfill_running(&self) -> anyhow::Result<()> {
|
||||
self.ensure_backfill_state_row().await?;
|
||||
sqlx::query(
|
||||
r#"
|
||||
UPDATE backfill_state
|
||||
SET status = ?, updated_at = ?
|
||||
WHERE id = 1
|
||||
"#,
|
||||
)
|
||||
.bind(crate::BackfillStatus::Running.as_str())
|
||||
.bind(Utc::now().timestamp())
|
||||
.execute_with_busy_retry(self.pool.as_ref())
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persist rollout metadata backfill progress.
|
||||
pub async fn checkpoint_backfill(&self, watermark: &str) -> anyhow::Result<()> {
|
||||
self.ensure_backfill_state_row().await?;
|
||||
sqlx::query(
|
||||
r#"
|
||||
UPDATE backfill_state
|
||||
SET status = ?, last_watermark = ?, updated_at = ?
|
||||
WHERE id = 1
|
||||
"#,
|
||||
)
|
||||
.bind(crate::BackfillStatus::Running.as_str())
|
||||
.bind(watermark)
|
||||
.bind(Utc::now().timestamp())
|
||||
.execute_with_busy_retry(self.pool.as_ref())
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Mark rollout metadata backfill as complete.
|
||||
pub async fn mark_backfill_complete(&self, last_watermark: Option<&str>) -> anyhow::Result<()> {
|
||||
self.ensure_backfill_state_row().await?;
|
||||
let now = Utc::now().timestamp();
|
||||
sqlx::query(
|
||||
r#"
|
||||
UPDATE backfill_state
|
||||
SET
|
||||
status = ?,
|
||||
last_watermark = COALESCE(?, last_watermark),
|
||||
last_success_at = ?,
|
||||
updated_at = ?
|
||||
WHERE id = 1
|
||||
"#,
|
||||
)
|
||||
.bind(crate::BackfillStatus::Complete.as_str())
|
||||
.bind(last_watermark)
|
||||
.bind(now)
|
||||
.bind(now)
|
||||
.execute_with_busy_retry(self.pool.as_ref())
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn ensure_backfill_state_row(&self) -> anyhow::Result<()> {
|
||||
ensure_backfill_state_row_in_pool(self.pool.as_ref()).await
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::StateRuntime;
|
||||
use super::test_support::unique_temp_dir;
|
||||
use chrono::Utc;
|
||||
use akode_utils_absolute_path::test_support::PathExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use sqlx::Connection;
|
||||
|
||||
#[tokio::test]
|
||||
async fn backfill_state_persists_progress_and_completion() {
|
||||
let codex_home = unique_temp_dir();
|
||||
let runtime = StateRuntime::init(
|
||||
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
|
||||
"test-provider".to_string(),
|
||||
)
|
||||
.await
|
||||
.expect("initialize runtime");
|
||||
|
||||
let initial = runtime
|
||||
.get_backfill_state()
|
||||
.await
|
||||
.expect("get initial backfill state");
|
||||
assert_eq!(initial.status, crate::BackfillStatus::Pending);
|
||||
assert_eq!(initial.last_watermark, None);
|
||||
assert_eq!(initial.last_success_at, None);
|
||||
|
||||
runtime
|
||||
.mark_backfill_running()
|
||||
.await
|
||||
.expect("mark backfill running");
|
||||
runtime
|
||||
.checkpoint_backfill("sessions/2026/01/27/rollout-a.jsonl")
|
||||
.await
|
||||
.expect("checkpoint backfill");
|
||||
|
||||
let running = runtime
|
||||
.get_backfill_state()
|
||||
.await
|
||||
.expect("get running backfill state");
|
||||
assert_eq!(running.status, crate::BackfillStatus::Running);
|
||||
assert_eq!(
|
||||
running.last_watermark,
|
||||
Some("sessions/2026/01/27/rollout-a.jsonl".to_string())
|
||||
);
|
||||
assert_eq!(running.last_success_at, None);
|
||||
|
||||
runtime
|
||||
.mark_backfill_complete(Some("sessions/2026/01/28/rollout-b.jsonl"))
|
||||
.await
|
||||
.expect("mark backfill complete");
|
||||
let completed = runtime
|
||||
.get_backfill_state()
|
||||
.await
|
||||
.expect("get completed backfill state");
|
||||
assert_eq!(completed.status, crate::BackfillStatus::Complete);
|
||||
assert_eq!(
|
||||
completed.last_watermark,
|
||||
Some("sessions/2026/01/28/rollout-b.jsonl".to_string())
|
||||
);
|
||||
assert!(completed.last_success_at.is_some());
|
||||
|
||||
let _ = tokio::fs::remove_dir_all(codex_home).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_backfill_state_succeeds_while_another_connection_holds_writer_slot() {
|
||||
let codex_home = unique_temp_dir();
|
||||
let sqlite = crate::SqliteConfig::new_for_testing(codex_home.as_path().abs());
|
||||
let runtime = StateRuntime::init(sqlite.clone(), "test-provider".to_string())
|
||||
.await
|
||||
.expect("initialize runtime");
|
||||
let write_pool = sqlite
|
||||
.open_read_write_pool(&sqlite.state_db_path())
|
||||
.await
|
||||
.expect("open write pool");
|
||||
let mut write_connection = write_pool.acquire().await.expect("open write connection");
|
||||
let write_transaction = write_connection
|
||||
.begin_with("BEGIN IMMEDIATE")
|
||||
.await
|
||||
.expect("acquire write lock");
|
||||
|
||||
let state = runtime
|
||||
.get_backfill_state()
|
||||
.await
|
||||
.expect("get backfill state");
|
||||
assert_eq!(state, crate::BackfillState::default());
|
||||
|
||||
write_transaction
|
||||
.rollback()
|
||||
.await
|
||||
.expect("release write lock");
|
||||
let _ = tokio::fs::remove_dir_all(codex_home).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_backfill_state_repairs_a_missing_singleton_row() {
|
||||
let codex_home = unique_temp_dir();
|
||||
let runtime = StateRuntime::init(
|
||||
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
|
||||
"test-provider".to_string(),
|
||||
)
|
||||
.await
|
||||
.expect("initialize runtime");
|
||||
sqlx::query("DELETE FROM backfill_state WHERE id = 1")
|
||||
.execute(runtime.pool.as_ref())
|
||||
.await
|
||||
.expect("delete backfill state row");
|
||||
|
||||
let state = runtime
|
||||
.get_backfill_state()
|
||||
.await
|
||||
.expect("get repaired backfill state");
|
||||
assert_eq!(state, crate::BackfillState::default());
|
||||
let row_count =
|
||||
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM backfill_state WHERE id = 1")
|
||||
.fetch_one(runtime.pool.as_ref())
|
||||
.await
|
||||
.expect("count repaired backfill state rows");
|
||||
assert_eq!(row_count, 1);
|
||||
|
||||
let _ = tokio::fs::remove_dir_all(codex_home).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn backfill_claim_is_singleton_until_stale_and_blocked_when_complete() {
|
||||
let codex_home = unique_temp_dir();
|
||||
let runtime = StateRuntime::init(
|
||||
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
|
||||
"test-provider".to_string(),
|
||||
)
|
||||
.await
|
||||
.expect("initialize runtime");
|
||||
|
||||
let claimed = runtime
|
||||
.try_claim_backfill(/*lease_seconds*/ 3600)
|
||||
.await
|
||||
.expect("initial backfill claim");
|
||||
assert_eq!(claimed, true);
|
||||
|
||||
let duplicate_claim = runtime
|
||||
.try_claim_backfill(/*lease_seconds*/ 3600)
|
||||
.await
|
||||
.expect("duplicate backfill claim");
|
||||
assert_eq!(duplicate_claim, false);
|
||||
|
||||
let stale_updated_at = Utc::now().timestamp().saturating_sub(10_000);
|
||||
sqlx::query(
|
||||
r#"
|
||||
UPDATE backfill_state
|
||||
SET status = ?, updated_at = ?
|
||||
WHERE id = 1
|
||||
"#,
|
||||
)
|
||||
.bind(crate::BackfillStatus::Running.as_str())
|
||||
.bind(stale_updated_at)
|
||||
.execute(runtime.pool.as_ref())
|
||||
.await
|
||||
.expect("force stale backfill lease");
|
||||
|
||||
let stale_claim = runtime
|
||||
.try_claim_backfill(/*lease_seconds*/ 10)
|
||||
.await
|
||||
.expect("stale backfill claim");
|
||||
assert_eq!(stale_claim, true);
|
||||
|
||||
runtime
|
||||
.mark_backfill_complete(/*last_watermark*/ None)
|
||||
.await
|
||||
.expect("mark complete");
|
||||
let claim_after_complete = runtime
|
||||
.try_claim_backfill(/*lease_seconds*/ 3600)
|
||||
.await
|
||||
.expect("claim after complete");
|
||||
assert_eq!(claim_after_complete, false);
|
||||
|
||||
let _ = tokio::fs::remove_dir_all(codex_home).await;
|
||||
}
|
||||
}
|
||||
149
akode-rs/state/src/runtime/external_agent_config_imports.rs
Normal file
149
akode-rs/state/src/runtime/external_agent_config_imports.rs
Normal file
@@ -0,0 +1,149 @@
|
||||
use super::StateRuntime;
|
||||
use crate::model::datetime_to_epoch_millis;
|
||||
use crate::sqlite::SqliteWriteQueryExt;
|
||||
use chrono::Utc;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use sqlx::Row;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ExternalAgentConfigImportSuccessRecord {
|
||||
pub item_type: String,
|
||||
pub cwd: Option<PathBuf>,
|
||||
pub source: Option<String>,
|
||||
pub target: Option<String>,
|
||||
#[serde(default)]
|
||||
pub title: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ExternalAgentConfigImportFailureRecord {
|
||||
pub item_type: String,
|
||||
pub error_type: Option<String>,
|
||||
#[serde(default)]
|
||||
pub sub_error_type: Option<String>,
|
||||
pub failure_stage: String,
|
||||
pub message: String,
|
||||
pub cwd: Option<PathBuf>,
|
||||
pub source: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ExternalAgentConfigImportDetailsRecord {
|
||||
pub successes: Vec<ExternalAgentConfigImportSuccessRecord>,
|
||||
pub failures: Vec<ExternalAgentConfigImportFailureRecord>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ExternalAgentConfigImportHistoryRecord {
|
||||
pub import_id: String,
|
||||
pub provider_id: Option<String>,
|
||||
pub completed_at_ms: i64,
|
||||
pub successes: Vec<ExternalAgentConfigImportSuccessRecord>,
|
||||
pub failures: Vec<ExternalAgentConfigImportFailureRecord>,
|
||||
}
|
||||
|
||||
impl StateRuntime {
|
||||
pub async fn record_external_agent_config_import_completed(
|
||||
&self,
|
||||
import_id: &str,
|
||||
provider_id: Option<&str>,
|
||||
successes: &[ExternalAgentConfigImportSuccessRecord],
|
||||
failures: &[ExternalAgentConfigImportFailureRecord],
|
||||
) -> anyhow::Result<()> {
|
||||
sqlx::query(
|
||||
r#"
|
||||
INSERT INTO external_agent_config_imports (
|
||||
import_id,
|
||||
provider_id,
|
||||
completed_at_ms,
|
||||
successes,
|
||||
failures
|
||||
) VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(import_id) DO UPDATE SET
|
||||
provider_id = excluded.provider_id,
|
||||
completed_at_ms = excluded.completed_at_ms,
|
||||
successes = excluded.successes,
|
||||
failures = excluded.failures
|
||||
"#,
|
||||
)
|
||||
.bind(import_id)
|
||||
.bind(provider_id)
|
||||
.bind(datetime_to_epoch_millis(Utc::now()))
|
||||
.bind(serde_json::to_string(successes)?)
|
||||
.bind(serde_json::to_string(failures)?)
|
||||
.execute_with_busy_retry(self.pool.as_ref())
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn external_agent_config_import_details_record(
|
||||
&self,
|
||||
import_id: &str,
|
||||
) -> anyhow::Result<Option<ExternalAgentConfigImportDetailsRecord>> {
|
||||
let row = sqlx::query(
|
||||
r#"
|
||||
SELECT
|
||||
successes,
|
||||
failures
|
||||
FROM external_agent_config_imports
|
||||
WHERE import_id = ?
|
||||
"#,
|
||||
)
|
||||
.bind(import_id)
|
||||
.fetch_optional(self.pool.as_ref())
|
||||
.await?;
|
||||
|
||||
row.map(|row| {
|
||||
let successes: String = row.try_get("successes")?;
|
||||
let failures: String = row.try_get("failures")?;
|
||||
Ok(ExternalAgentConfigImportDetailsRecord {
|
||||
successes: serde_json::from_str(&successes)?,
|
||||
failures: serde_json::from_str(&failures)?,
|
||||
})
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub async fn external_agent_config_import_history_records(
|
||||
&self,
|
||||
) -> anyhow::Result<Vec<ExternalAgentConfigImportHistoryRecord>> {
|
||||
let rows = sqlx::query(
|
||||
r#"
|
||||
SELECT
|
||||
import_id,
|
||||
provider_id,
|
||||
completed_at_ms,
|
||||
successes,
|
||||
failures
|
||||
FROM external_agent_config_imports
|
||||
ORDER BY completed_at_ms DESC, import_id ASC
|
||||
"#,
|
||||
)
|
||||
.fetch_all(self.pool.as_ref())
|
||||
.await?;
|
||||
|
||||
rows.into_iter()
|
||||
.map(|row| {
|
||||
let import_id: String = row.try_get("import_id")?;
|
||||
let provider_id: Option<String> = row.try_get("provider_id")?;
|
||||
let completed_at_ms: i64 = row.try_get("completed_at_ms")?;
|
||||
let successes: String = row.try_get("successes")?;
|
||||
let failures: String = row.try_get("failures")?;
|
||||
Ok(ExternalAgentConfigImportHistoryRecord {
|
||||
import_id,
|
||||
provider_id,
|
||||
completed_at_ms,
|
||||
successes: serde_json::from_str(&successes)?,
|
||||
failures: serde_json::from_str(&failures)?,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "external_agent_config_imports_tests.rs"]
|
||||
mod tests;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user