1use std::path::Path;
6
7use rusqlite::{OpenFlags, params};
8use serde::Serialize;
9use tokio_rusqlite::Connection;
10
11use super::{
12 DATABASE, Execution,
13 receipts::{Error, NotifyingConnection, schema_initialized},
14};
15
16pub const MAX_ENTRIES: i64 = 10_000;
19pub const MAX_BYTES: i64 = 1024 * 1024 * 1024;
21pub const MAX_ENTRY_BYTES: usize = 16 * 1024 * 1024;
23
24pub(super) const RECORD: &str =
26 "e.completed_at IS NOT NULL AND e.status IN ('GREEN','RED') AND e.key IS NOT NULL";
27
28pub(super) const LATEST: &str = "e.completed_at DESC, e.rowid DESC";
30
31#[derive(Debug, Serialize)]
33#[serde(rename_all = "camelCase")]
34pub struct Entry {
35 pub key: crate::types::ReuseKey,
36 pub eval_def_hash: crate::types::DefinitionHash,
37 pub execution_id: crate::types::ExecutionId,
38 pub verdict: crate::types::ExecutionStatus,
39 #[serde(with = "crate::platform::path_serde")]
40 pub repo_path: std::path::PathBuf,
41 pub eval_id: crate::types::EvalId,
42 pub fingerprint: Option<crate::types::Fingerprint>,
44 pub completed_at: Option<crate::types::Timestamp>,
45 pub producer: Option<crate::types::ProducerId>,
47 pub variant: Option<crate::config::ProfileName>,
50 pub origin: Option<crate::types::StoreUrl>,
52 pub records: i64,
54 pub bytes: i64,
55 pub last_used: crate::types::Timestamp,
56}
57
58async fn open(state: &Path, writable: bool) -> Result<Option<NotifyingConnection>, String> {
59 let state = crate::workspace::canonical_target(state).map_err(|e| e.to_string())?;
60 super::receipts::check_files(&state)?;
61 let path = state.join(DATABASE);
62 if !path.try_exists().map_err(|e| e.to_string())? {
63 return Ok(None);
64 }
65 let connection = Connection::open_with_flags(
66 path,
67 if writable {
68 OpenFlags::SQLITE_OPEN_READ_WRITE
69 } else {
70 OpenFlags::SQLITE_OPEN_READ_ONLY
71 },
72 )
73 .await
74 .map_err(|e| e.to_string())?;
75 let connection = NotifyingConnection::new(connection, &state);
76 let initialized = connection
77 .call(|db| -> Result<bool, Error> {
78 super::wait_when_busy(db)?;
79 let transaction = db.transaction()?;
80 schema_initialized(&transaction)
81 })
82 .await
83 .map_err(|e| e.to_string());
84 match initialized {
85 Ok(true) => Ok(Some(connection)),
86 result => connection.finish(result.map(|_| None)).await,
87 }
88}
89
90pub async fn list(state: &Path, history: bool) -> Result<Vec<Entry>, String> {
92 let Some(connection) = open(state, false).await? else {
93 return Ok(Vec::new());
94 };
95 let result = connection
96 .call(move |db| -> Result<_, Error> {
97 let mut statement = db.prepare(&format!(
98 "SELECT * FROM (SELECT e.key,e.eval_def_hash,e.id,e.status,json_extract(e.data,'$.provenance.repoPath'),json_extract(e.data,'$.provenance.evalId'),json_extract(e.data,'$.fingerprint'),json_extract(e.data,'$.completedAt'),json_extract(e.data,'$.origin.store'),count(*) OVER (PARTITION BY e.key),e.bytes,e.last_used,row_number() OVER (PARTITION BY e.key ORDER BY {LATEST}) AS rank,e.data FROM executions e WHERE {RECORD}) WHERE ?1 OR rank=1 ORDER BY 1,rank"
99 ))?;
100 Ok(statement
101 .query_map([history], |row| {
102 let id: crate::types::ExecutionId = row.get(2)?;
103 let data: String = row.get(13)?;
104 let Some(execution) =
105 super::unreadable::evidence::<Execution>("execution", &data)
106 else {
107 return Ok(None);
108 };
109 Ok(Some(Entry {
110 key: row.get(0)?,
111 eval_def_hash: row.get(1)?,
112 execution_id: id,
113 verdict: row.get(3)?,
114 repo_path: row.get::<_, String>(4)?.into(),
115 eval_id: row.get(5)?,
116 fingerprint: row.get(6)?,
117 completed_at: row.get(7)?,
118 producer: execution.producer.map(|producer| producer.name),
119 variant: execution.options.variant,
120 origin: row.get(8)?,
121 records: row.get(9)?,
122 bytes: row.get(10)?,
123 last_used: row.get(11)?,
124 }))
125 })?
126 .filter_map(|row| row.transpose())
127 .collect::<Result<_, _>>()?)
128 })
129 .await
130 .map_err(|e| e.to_string());
131 connection.finish(result).await
132}
133
134pub async fn show(state: &Path, key: &str, history: bool) -> Result<Vec<Execution>, String> {
136 let Some(connection) = open(state, false).await? else {
137 return Ok(Vec::new());
138 };
139 let Ok(key) = key.parse::<crate::types::ReuseKey>() else {
140 return connection.finish(Ok(Vec::new())).await;
141 };
142 let result = connection
143 .call(move |db| -> Result<_, Error> {
144 let mut statement = db.prepare(&format!(
145 "SELECT e.data FROM executions e WHERE e.key=? AND {RECORD} ORDER BY {LATEST} LIMIT ?"
146 ))?;
147 statement
148 .query_map(params![key, if history { -1 } else { 1 }], |row| {
149 row.get::<_, String>(0)
150 })?
151 .filter_map(|row| match row {
152 Ok(data) => super::unreadable::evidence("execution", &data).map(Ok),
153 Err(error) => Some(Err(Error::Sql(error))),
154 })
155 .collect()
156 })
157 .await
158 .map_err(|e| e.to_string());
159 connection.finish(result).await
160}
161
162pub(crate) async fn local(
164 state: &Path,
165 after: Option<crate::types::ReuseKey>,
166 limit: usize,
167) -> Result<Vec<(crate::types::ReuseKey, Execution)>, String> {
168 let Some(connection) = open(state, false).await? else {
169 return Ok(Vec::new());
170 };
171 let result = connection
172 .call(move |db| -> Result<_, Error> {
173 let mut statement = db.prepare(&format!(
174 "SELECT key,data FROM (SELECT e.key,e.data,row_number() OVER (PARTITION BY e.key ORDER BY {LATEST}) AS rank FROM executions e WHERE {RECORD} AND json_extract(e.data,'$.origin') IS NULL AND e.key>?) WHERE rank=1 ORDER BY key LIMIT ?"
175 ))?;
176 let mut rows = statement.query(params![
177 after.as_ref().map_or("", crate::types::ReuseKey::as_str),
178 limit as i64
179 ])?;
180 let mut page = Vec::new();
181 while let Some(row) = rows.next()? {
182 let key: crate::types::ReuseKey = row.get(0)?;
183 let data: String = row.get(1)?;
184 let execution: Execution = super::unreadable::decode("execution", key.as_str(), &data)
185 .map_err(Error::Unreadable)?;
186 if execution.key.as_ref() != Some(&key) {
187 return Err(Error::Invalid(format!("Cached execution {} does not have its indexed reuse key {key}.", execution.id)));
188 }
189 page.push((key, execution));
190 }
191 Ok(page)
192 })
193 .await
194 .map_err(|e| e.to_string());
195 connection.finish(result).await
196}
197
198pub async fn remove(state: &Path, key: &str) -> Result<bool, String> {
200 let Some(connection) = open(state, true).await? else {
201 return Ok(false);
202 };
203 let Ok(key) = key.parse::<crate::types::ReuseKey>() else {
204 return connection.finish(Ok(false)).await;
205 };
206 let result = connection
207 .call(move |db| -> Result<bool, Error> {
208 let transaction =
209 db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
210 let in_use: bool = transaction.query_row(
211 "SELECT EXISTS(SELECT 1 FROM executions WHERE key=?1 AND status IN ('RUNNING','WAITING_HUMAN')) OR EXISTS(SELECT 1 FROM requests q JOIN executions e ON e.id=q.execution_id WHERE e.key=?1 AND e.completed_at IS NOT NULL AND q.status IN ('QUEUED','RUNNING','WAITING_HUMAN'))",
212 [&key],
213 |row| row.get(0),
214 )?;
215 if in_use {
216 return Err(Error::Invalid(format!(
217 "Key {key} is in use by an active execution or waiter."
218 )));
219 }
220 let removed = transaction.execute(
221 "UPDATE executions SET completed_at=NULL,bytes=NULL,last_used=NULL WHERE key=? AND completed_at IS NOT NULL",
222 [&key],
223 )?;
224 transaction.commit()?;
225 Ok(removed != 0)
226 })
227 .await
228 .map_err(|e| e.to_string());
229 connection.finish(result).await
230}
231
232pub(super) fn columns(
236 execution: &Execution,
237 bytes: usize,
238) -> Result<Option<(crate::types::Timestamp, i64)>, Error> {
239 let (Some(_), Some(_), Some(completed_at)) = (
240 &execution.key,
241 execution.verdict(),
242 &execution.completed_at(),
243 ) else {
244 return Ok(None);
245 };
246 if bytes > MAX_ENTRY_BYTES {
247 return Ok(None);
248 }
249 Ok(Some((*completed_at, bytes as i64)))
250}
251
252pub(super) fn touch(
254 db: &rusqlite::Connection,
255 execution_id: &crate::types::ExecutionId,
256 at: crate::types::Timestamp,
257) -> Result<(), Error> {
258 db.execute(
259 "UPDATE executions SET last_used=? WHERE id=? AND completed_at IS NOT NULL",
260 params![at, execution_id],
261 )?;
262 Ok(())
263}
264
265#[derive(Debug, Clone, Copy)]
267struct Caps {
268 entries: i64,
269 bytes: i64,
270}
271
272const CAPS: Caps = Caps {
273 entries: MAX_ENTRIES,
274 bytes: MAX_BYTES,
275};
276
277pub(crate) async fn collect(state: &Path) -> Result<(), String> {
284 let Some(connection) = open(state, true).await? else {
285 return Ok(());
286 };
287 let result = connection
288 .call(|db| collect_within(db, CAPS))
289 .await
290 .map_err(|e| e.to_string());
291 connection.finish(result).await
292}
293
294struct Record {
296 id: crate::types::ExecutionId,
297 checkout: Option<std::path::PathBuf>,
298 eval: Option<crate::types::EvalId>,
300 human: bool,
301 bytes: i64,
302 last_used: crate::types::Timestamp,
303 held: bool,
304}
305
306fn collect_within(db: &mut rusqlite::Connection, caps: Caps) -> Result<(), Error> {
307 let transaction = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
308 let records = transaction
310 .prepare(&format!(
311 "SELECT e.id,json_extract(e.data,'$.provenance.repoPath'),json_extract(e.data,'$.provenance.evalId'),
312 coalesce(json_extract(e.data,'$.profile.kind')='human',0),e.bytes,e.last_used,
313 EXISTS(SELECT 1 FROM executions a WHERE a.key=e.key AND a.status IN ('RUNNING','WAITING_HUMAN'))
314 OR EXISTS(SELECT 1 FROM requests q WHERE q.execution_id=e.id AND q.status IN ('QUEUED','RUNNING','WAITING_HUMAN'))
315 FROM executions e WHERE {RECORD} ORDER BY {LATEST}"
316 ))?
317 .query_map([], |row| {
318 Ok(Record {
319 id: row.get(0)?,
320 checkout: row.get::<_, Option<String>>(1)?.map(Into::into),
321 eval: row
322 .get::<_, Option<String>>(2)?
323 .and_then(|eval| eval.parse().ok()),
324 human: row.get(3)?,
325 bytes: row.get(4)?,
326 last_used: row.get(5)?,
327 held: row.get(6)?,
328 })
329 })?
330 .collect::<Result<Vec<_>, _>>()?;
331 let present: std::collections::BTreeSet<_> = records
332 .iter()
333 .filter_map(|record| record.checkout.as_deref())
334 .collect::<std::collections::BTreeSet<_>>()
335 .into_iter()
336 .filter(|checkout| checkout.is_dir())
337 .collect();
338 {
339 let mut evict = transaction.prepare(
341 "UPDATE executions SET completed_at=NULL,bytes=NULL,last_used=NULL WHERE id=?",
342 )?;
343 for id in eviction_candidates(&records, &present, caps) {
344 evict.execute([id])?;
345 }
346 }
347 Ok(transaction.commit()?)
348}
349
350fn eviction_candidates<'a>(
351 records: &'a [Record],
352 present: &std::collections::BTreeSet<&Path>,
353 caps: Caps,
354) -> Vec<&'a crate::types::ExecutionId> {
355 let mut reused = std::collections::BTreeSet::new();
356 let mut history = Vec::new();
357 let mut evicted = Vec::new();
358 for record in records {
359 let newest = match (&record.checkout, &record.eval) {
360 (Some(checkout), Some(eval)) => {
361 reused.insert((checkout, eval)) && present.contains(checkout.as_path())
362 }
363 _ => false,
364 };
365 if record.held {
366 continue;
367 }
368 if record.bytes > MAX_ENTRY_BYTES as i64 {
369 evicted.push(&record.id);
370 } else if !newest {
371 history.push(record);
372 }
373 }
374 history.sort_by(|a, b| {
376 b.human
377 .cmp(&a.human)
378 .then_with(|| b.last_used.cmp(&a.last_used))
379 });
380 let (mut entries, mut bytes) = (0, 0);
381 for record in history {
382 if entries < caps.entries && bytes + record.bytes <= caps.bytes {
383 entries += 1;
384 bytes += record.bytes;
385 } else {
386 evicted.push(&record.id);
387 }
388 }
389 evicted
390}
391
392#[cfg(test)]
393mod tests;