perf(cron): add composite index on cron_runs(job_id, started_at)

Problem:
The pruning query in record_run uses WHERE job_id = ?1 with
ORDER BY started_at DESC, but only single-column indexes exist
for job_id and started_at separately. SQLite must scan one index
and then sort or scan the other, which is suboptimal for the
combined filter + sort pattern used during pruning.

Fix:
Add a composite index CREATE INDEX IF NOT EXISTS
idx_cron_runs_job_started ON cron_runs(job_id, started_at).
This lets SQLite satisfy the WHERE job_id = ?1 ORDER BY
started_at DESC subquery in a single index scan without a
separate sort step. The existing single-column indexes are
retained for other queries that filter on only one column.

Ref: zeroclaw-labs/zeroclaw#710 (Item 7)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Alex Gorevski 2026-02-17 19:51:14 -08:00 committed by Chummy
parent 151bc6a600
commit 9967eeb954

View file

@ -538,7 +538,8 @@ fn with_connection<T>(config: &Config, f: impl FnOnce(&Connection) -> Result<T>)
FOREIGN KEY (job_id) REFERENCES cron_jobs(id) ON DELETE CASCADE FOREIGN KEY (job_id) REFERENCES cron_jobs(id) ON DELETE CASCADE
); );
CREATE INDEX IF NOT EXISTS idx_cron_runs_job_id ON cron_runs(job_id); CREATE INDEX IF NOT EXISTS idx_cron_runs_job_id ON cron_runs(job_id);
CREATE INDEX IF NOT EXISTS idx_cron_runs_started_at ON cron_runs(started_at);", CREATE INDEX IF NOT EXISTS idx_cron_runs_started_at ON cron_runs(started_at);
CREATE INDEX IF NOT EXISTS idx_cron_runs_job_started ON cron_runs(job_id, started_at);",
) )
.context("Failed to initialize cron schema")?; .context("Failed to initialize cron schema")?;