Skip to main content

artifactize_core/store/
requests.rs

1use std::{
2    collections::HashMap,
3    path::{Path, PathBuf},
4    sync::Arc,
5};
6
7use serde::Serialize;
8
9use rusqlite::OptionalExtension;
10use tokio_rusqlite::Connection;
11
12use super::{
13    DATABASE, Execution, HumanClaim, Request,
14    definitions::Graph,
15    receipts::{Error, check_files, schema_initialized},
16};
17use crate::workspace::{canonical_target, outside_workspace};
18
19/// A request with what it shows. Its decoded records are shared: a copy of the view, and the
20/// Run's view of the same read, keep the one request and execution, so a snapshot that is
21/// read again copies only the requests that changed.
22#[derive(Debug, Clone, Serialize)]
23pub struct RequestView {
24    #[serde(flatten)]
25    pub request: Arc<Request>,
26    pub claim: Option<HumanClaim>,
27    pub execution: Option<Arc<Execution>>,
28    pub definition: Option<RequestDefinition>,
29}
30
31/// The saved definitions of a request's eval and Artifact.
32#[derive(Clone)]
33pub struct RequestDefinition(Place);
34#[derive(Clone)]
35enum Place {
36    /// A place in the Run's one decoded graph, which every view of an opened Run shares.
37    Graph {
38        graph: Arc<Graph>,
39        /// The eval's position in the graph's evals.
40        eval: usize,
41        artifact: crate::types::ArtifactName,
42    },
43    /// Copies of its own eval and Artifact, for a view read apart from its Run, such as a
44    /// waiting review's, which may be kept long after the rest of the Run is gone.
45    Own {
46        eval: Arc<super::definitions::Eval>,
47        artifact: Arc<super::definitions::Artifact>,
48    },
49}
50impl RequestDefinition {
51    pub fn eval(&self) -> &super::definitions::Eval {
52        match &self.0 {
53            Place::Graph { graph, eval, .. } => &graph.evals()[*eval],
54            Place::Own { eval, .. } => eval,
55        }
56    }
57    pub fn artifact(&self) -> &super::definitions::Artifact {
58        match &self.0 {
59            Place::Graph {
60                graph, artifact, ..
61            } => graph
62                .artifact(artifact)
63                .expect("an indexed request's Artifact is in its graph"),
64            Place::Own { artifact, .. } => artifact,
65        }
66    }
67}
68impl Serialize for RequestDefinition {
69    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
70        use serde::ser::SerializeStruct;
71        let mut definition = serializer.serialize_struct("RequestDefinition", 2)?;
72        definition.serialize_field("eval", self.eval())?;
73        definition.serialize_field("artifact", self.artifact())?;
74        definition.end()
75    }
76}
77impl std::fmt::Debug for RequestDefinition {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        f.debug_struct("RequestDefinition")
80            .field("eval", self.eval())
81            .field("artifact", self.artifact())
82            .finish()
83    }
84}
85
86#[derive(Default)]
87struct Filter<'a> {
88    run: Option<crate::types::RunId>,
89    id: Option<crate::types::RequestId>,
90    repo: Option<&'a Path>,
91    waiting: bool,
92    session: Option<crate::types::SessionId>,
93    statuses: &'a [crate::types::RequestStatus],
94    /// A bounded slice of the ordered requests: where it starts and how many it reads.
95    slice: Option<(Start, u32)>,
96    shown: Shown,
97    newest_waiting: bool,
98    list_limit: Option<u32>,
99}
100
101/// Where a batch of the ordered requests starts.
102#[derive(Debug, Clone)]
103pub enum Start {
104    /// At a position from the first request.
105    Position(u64),
106    /// Just after a request the previous batch read, without stepping past the ones before it.
107    After(Mark),
108}
109
110/// A request's place in the order a batch reads in.
111#[derive(Debug, Clone)]
112pub struct Mark {
113    listed: String,
114    /// The Run's rowid, which orders Runs newest first.
115    run: i64,
116    run_id: String,
117    ordinal: i64,
118}
119
120/// One batch of the ordered requests.
121#[derive(Debug, Default)]
122pub struct Batch {
123    /// The requests that read, each at its offset in the batch, with its Run's repository.
124    pub requests: Vec<(u32, RequestView, PathBuf)>,
125    /// How many requests the batch read, including those that did not read.
126    pub read: u32,
127    /// Where the next batch starts, when the batch read any request.
128    pub next: Option<Start>,
129}
130
131/// What the views of a read show besides their requests.
132#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
133pub enum Shown {
134    /// The definitions their Runs saved, which hold the Runs' whole graphs: each Run read is
135    /// decoded whole.
136    #[default]
137    Definitions,
138    /// No definitions: only the Runs' repositories are read, never their records.
139    Requests,
140}
141
142pub async fn read_requests(state: &Path, run: Option<&str>) -> Result<Vec<RequestView>, String> {
143    read_requests_in(state, run, None).await
144}
145
146pub async fn read_requests_in(
147    state: &Path,
148    run: Option<&str>,
149    repo: Option<&Path>,
150) -> Result<Vec<RequestView>, String> {
151    read(
152        state,
153        Filter {
154            run: run.map(str::parse).transpose()?,
155            repo,
156            ..Filter::default()
157        },
158    )
159    .await
160}
161
162pub(crate) async fn read_request_list(
163    state: &Path,
164    run: Option<crate::types::RunId>,
165    repo: Option<&Path>,
166    limit: u32,
167) -> Result<Vec<RequestView>, String> {
168    if limit == 0 {
169        return Ok(Vec::new());
170    }
171    read(
172        state,
173        Filter {
174            run,
175            repo,
176            shown: Shown::Requests,
177            list_limit: Some(limit),
178            ..Filter::default()
179        },
180    )
181    .await
182}
183
184pub async fn read_request(state: &Path, id: &str) -> Result<RequestView, String> {
185    read_request_id(state, &id.parse()?).await
186}
187
188pub async fn read_request_id(
189    state: &Path,
190    id: &crate::types::RequestId,
191) -> Result<RequestView, String> {
192    read_request_by_id(state, id, Shown::Definitions).await
193}
194
195/// Request `id` with what `shown` names besides it.
196pub async fn read_request_as(state: &Path, id: &str, shown: Shown) -> Result<RequestView, String> {
197    read_request_by_id(state, &id.parse()?, shown).await
198}
199
200/// Read an already validated request ID, with what `shown` names besides it.
201pub async fn read_request_by_id(
202    state: &Path,
203    id: &crate::types::RequestId,
204    shown: Shown,
205) -> Result<RequestView, String> {
206    read_optional_request(state, id, shown)
207        .await?
208        .ok_or_else(|| "Review request not found.".into())
209}
210
211/// Read an exact request if it still exists, distinguishing absence from a store error.
212pub async fn read_optional_request(
213    state: &Path,
214    id: &crate::types::RequestId,
215    shown: Shown,
216) -> Result<Option<RequestView>, String> {
217    Ok(read(
218        state,
219        Filter {
220            id: Some(id.clone()),
221            shown,
222            ..Filter::default()
223        },
224    )
225    .await?
226    .pop())
227}
228
229/// The request whose Agent review ran as session `id`, if this state has it.
230pub async fn read_session_request(state: &Path, id: &str) -> Result<Option<RequestView>, String> {
231    read_request_by_session(state, id.parse()?).await
232}
233
234pub(crate) async fn read_request_by_session(
235    state: &Path,
236    session: crate::types::SessionId,
237) -> Result<Option<RequestView>, String> {
238    Ok(read(
239        state,
240        Filter {
241            session: Some(session),
242            ..Filter::default()
243        },
244    )
245    .await?
246    .pop())
247}
248
249/// The request that owns `view`'s shared execution: a follower of another Run joins the
250/// original waiting request, which alone records the Human definition (tools and owner
251/// schemas), the claim and the result. `view` itself when it is the original.
252pub async fn read_original(state: &Path, view: &RequestView) -> Result<RequestView, String> {
253    read_original_as(state, view, Shown::Definitions).await
254}
255
256/// The request that owns `view`'s shared execution, read with what `shown` names besides it.
257pub async fn read_original_as(
258    state: &Path,
259    view: &RequestView,
260    shown: Shown,
261) -> Result<RequestView, String> {
262    match original_id(view) {
263        Some(id) => read_request_by_id(state, id, shown).await,
264        None => Ok(view.clone()),
265    }
266}
267
268/// The recorded owner of a live review, or its exact receipt if that owner is gone.
269/// An operational read failure still propagates.
270pub async fn read_review_owner(state: &Path, view: &RequestView) -> Result<RequestView, String> {
271    let Some(id) = original_id(view).filter(|_| view.request.status().is_human_wait()) else {
272        return Ok(view.clone());
273    };
274    let found = read(
275        state,
276        Filter {
277            id: Some(id.clone()),
278            shown: Shown::Requests,
279            ..Filter::default()
280        },
281    )
282    .await?;
283    Ok(found.into_iter().next().unwrap_or_else(|| view.clone()))
284}
285
286fn original_id(view: &RequestView) -> Option<&crate::types::RequestId> {
287    view.execution
288        .as_ref()
289        .map(|execution| &execution.provenance.request_id)
290        .or_else(|| {
291            view.request
292                .provenance
293                .as_ref()
294                .map(|source| &source.request_id)
295        })
296        .filter(|id| *id != &view.request.id)
297}
298
299/// One entry per waiting Human sign-off: followers collapse onto the original request that
300/// owns their shared execution, at the position of the first entry that names it.
301pub async fn read_waiting_originals(
302    state: &Path,
303    repo: Option<&Path>,
304) -> Result<Vec<RequestView>, String> {
305    let waiting = read_waiting(state, repo).await?;
306    let by_id: std::collections::BTreeMap<_, _> = waiting
307        .iter()
308        .map(|view| (&view.request.id, view))
309        .collect();
310    let mut seen = std::collections::BTreeSet::new();
311    let mut originals: Vec<RequestView> = Vec::with_capacity(waiting.len());
312    for view in &waiting {
313        let source = view
314            .execution
315            .as_ref()
316            .map_or(&view.request.id, |execution| {
317                &execution.provenance.request_id
318            });
319        if seen.contains(source) {
320            continue;
321        }
322        let original = match by_id.get(source) {
323            Some(original) => Some((*original).clone()),
324            None => read_original(state, view).await.ok(),
325        };
326        // A follower whose original is gone or no longer waits stays listed as itself.
327        let original = original
328            .filter(|original| original.request.status().is_human_wait())
329            .unwrap_or_else(|| view.clone());
330        if seen.insert(original.request.id.clone()) {
331            originals.push(original);
332        }
333    }
334    Ok(originals)
335}
336
337/// Up to `limit` requests with one of `statuses` (any status when empty) from position
338/// `offset` of every Run's requests, newest Run first, each with its Run's repository and what
339/// `shown` names besides it.
340pub async fn read_request_batch(
341    state: &Path,
342    statuses: &[crate::types::RequestStatus],
343    start: Start,
344    limit: u32,
345    shown: Shown,
346) -> Result<Batch, String> {
347    read_batch(
348        state,
349        Filter {
350            statuses,
351            slice: Some((start, limit)),
352            shown,
353            ..Filter::default()
354        },
355    )
356    .await
357}
358
359/// Desktop review pages start with the requests that began waiting most recently.
360pub(crate) async fn read_review_batch(
361    state: &Path,
362    statuses: &[crate::types::RequestStatus],
363    start: Start,
364    limit: u32,
365    shown: Shown,
366) -> Result<Batch, String> {
367    read_batch(
368        state,
369        Filter {
370            statuses,
371            slice: Some((start, limit)),
372            shown,
373            newest_waiting: true,
374            ..Filter::default()
375        },
376    )
377    .await
378}
379
380/// WAITING_HUMAN requests, newest Run first, from the canonical `repo`'s Runs or every Run.
381/// Their views have no definitions: what waits, not what it reviews, so the read does not grow
382/// with the waiting Runs' workspaces.
383pub async fn read_waiting(state: &Path, repo: Option<&Path>) -> Result<Vec<RequestView>, String> {
384    read(
385        state,
386        Filter {
387            repo,
388            waiting: true,
389            shown: Shown::Requests,
390            ..Filter::default()
391        },
392    )
393    .await
394}
395
396async fn read(state: &Path, filter: Filter<'_>) -> Result<Vec<RequestView>, String> {
397    Ok(read_with_repo(state, filter)
398        .await?
399        .into_iter()
400        .map(|(view, _)| view)
401        .collect())
402}
403
404/// The repository of the Run that request `id` belongs to, where its Human actions are
405/// recorded. Only the request's Run row is read, never the Run's record or definitions, so a
406/// Human action finds its receipts at once however large the Run's workspace is.
407pub async fn read_request_repo(state: &Path, id: &str) -> Result<std::path::PathBuf, String> {
408    read_request_repo_by_id(state, id.parse()?).await
409}
410
411pub(crate) async fn read_request_repo_by_id(
412    state: &Path,
413    id: crate::types::RequestId,
414) -> Result<std::path::PathBuf, String> {
415    let not_found = || "Review request not found.".to_owned();
416    let state = canonical_target(state).map_err(|e| e.to_string())?;
417    let Some(connection) = open_read(&state).await? else {
418        return Err(not_found());
419    };
420    let result = connection
421        .call(move |db| -> Result<_, Error> {
422            super::wait_when_busy(db)?;
423            let transaction = db.transaction()?;
424            if !schema_initialized(&transaction)? {
425                return Ok(None);
426            }
427            let repo = transaction
428                .query_row(
429                    "SELECT r.repo FROM requests q JOIN runs r ON r.id=q.run_id WHERE q.id=?",
430                    [&id],
431                    |row| super::path_column(row, 0),
432                )
433                .optional()?;
434            transaction.commit()?;
435            if let Some(repo) = &repo {
436                crate::workspace::outside_workspaces(std::iter::once(repo.as_path()), &state)
437                    .map_err(|error| Error::Invalid(error.to_string()))?;
438            }
439            Ok(repo)
440        })
441        .await
442        .map_err(|e| e.to_string());
443    super::connection::finish(connection, result)
444        .await?
445        .ok_or_else(not_found)
446}
447
448/// A read-only connection to the database of the canonical `state`, or none before it has one.
449pub(super) async fn open_read(state: &Path) -> Result<Option<Connection>, String> {
450    check_files(state)?;
451    if !state
452        .join(DATABASE)
453        .try_exists()
454        .map_err(|e| e.to_string())?
455    {
456        return Ok(None);
457    }
458    Connection::open_with_flags(
459        state.join(DATABASE),
460        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
461    )
462    .await
463    .map(Some)
464    .map_err(|e| e.to_string())
465}
466
467async fn read_with_repo(
468    state: &Path,
469    filter: Filter<'_>,
470) -> Result<Vec<(RequestView, std::path::PathBuf)>, String> {
471    Ok(read_batch(state, filter)
472        .await?
473        .requests
474        .into_iter()
475        .map(|(_, view, repo)| (view, repo))
476        .collect())
477}
478
479async fn read_batch(state: &Path, filter: Filter<'_>) -> Result<Batch, String> {
480    let state = canonical_target(state).map_err(|e| e.to_string())?;
481    let repo = filter
482        .repo
483        .map(canonical_target)
484        .transpose()
485        .map_err(|e| e.to_string())?;
486    if let Some(repo) = &repo {
487        outside_workspace(repo, &state).map_err(|e| e.to_string())?;
488    }
489    let Filter {
490        run,
491        id,
492        waiting,
493        statuses,
494        slice,
495        session,
496        newest_waiting,
497        list_limit,
498        ..
499    } = filter;
500    let statuses = statuses.to_vec();
501    let shown = filter.shown;
502    let Some(connection) = open_read(&state).await? else {
503        return Ok(Batch::default());
504    };
505    let result = connection
506        .call(move |db| -> Result<_, Error> {
507            super::wait_when_busy(db)?;
508            if list_limit.is_some() && run.is_none() && repo.is_some() {
509                super::migrations::ensure_request_list_index(db, &state)?;
510            }
511            let transaction = db.transaction()?;
512            if !schema_initialized(&transaction)? {
513                return Ok(Batch::default());
514            }
515            let filter = Query {
516                run,
517                id,
518                repo,
519                waiting,
520                session,
521                statuses,
522                slice,
523                ids: None,
524                newest_waiting,
525                list_limit,
526            };
527            let rows = rows(&transaction, &filter)?;
528            let ids: std::collections::BTreeSet<_> = rows.iter().map(|row| &row.run).collect();
529            let mut statement = transaction.prepare(match shown {
530                Shown::Definitions => "SELECT r.id,r.repo,r.data,d.data,d.body FROM runs r LEFT JOIN run_definitions d ON d.run_id=r.id WHERE r.id IN (SELECT value FROM json_each(?))",
531                Shown::Requests => "SELECT r.id,r.repo,NULL,NULL,NULL FROM runs r WHERE r.id IN (SELECT value FROM json_each(?))",
532            })?;
533            let runs = statement
534                .query_map([serde_json::to_string(&ids)?], |row| {
535                    Ok((
536                        row.get::<_, crate::types::RunId>(0)?,
537                        row.get::<_, String>(1)?,
538                        row.get::<_, Option<String>>(2)?,
539                        row.get::<_, Option<String>>(3)?,
540                        row.get::<_, Option<String>>(4)?,
541                    ))
542                })?
543                .collect::<Result<Vec<_>, _>>()?;
544            let mut indexes = std::collections::BTreeMap::new();
545            let mut repos = Vec::new();
546            for (id, repo, state, definitions, body) in runs {
547                let index = match state {
548                    None => DefinitionIndex::none(),
549                    Some(state) => {
550                        let read = definitions
551                            .map(|data| super::run_record::text(&transaction, &id, data, body))
552                            .transpose()?
553                            .transpose()
554                            .and_then(|definitions| {
555                                super::run_record::whole(&id, &state, definitions.as_deref())
556                            });
557                        match read {
558                            Ok(run) => DefinitionIndex::apart(&run),
559                            Err(unreadable) => {
560                                super::unreadable::skipped(&unreadable);
561                                continue;
562                            }
563                        }
564                    }
565                };
566                let repo = artifactize_tools::files::path_from_text(&repo)
567                    .map_err(|error| Error::Invalid(error.to_string()))?;
568                repos.push(repo.clone());
569                indexes.insert(id, (index, repo));
570            }
571            crate::workspace::outside_workspaces(repos.iter().map(|repo| repo.as_path()), &state)
572                .map_err(|error| Error::Invalid(error.to_string()))?;
573            let batch = Batch {
574                read: u32::try_from(rows.len()).expect("a batch reads at most its u32 limit"),
575                next: rows.last().map(|row| Start::After(row.mark.clone())),
576                requests: rows
577                    .into_iter()
578                    .enumerate()
579                    .filter_map(|(offset, row)| {
580                        let (index, repo) = indexes.get_mut(&row.run)?;
581                        let view = row.view(index)?;
582                        Some((offset as u32, view, repo.clone()))
583                    })
584                    .collect(),
585            };
586            drop(statement);
587            transaction.commit()?;
588            Ok(batch)
589        })
590        .await
591        .map_err(|e| e.to_string());
592    super::connection::finish(connection, result).await
593}
594
595/// Only present predicates are emitted, so Run and request lookups use their existing indexes.
596#[derive(Default)]
597pub(super) struct Query {
598    pub run: Option<crate::types::RunId>,
599    pub id: Option<crate::types::RequestId>,
600    pub repo: Option<std::path::PathBuf>,
601    pub waiting: bool,
602    pub session: Option<crate::types::SessionId>,
603    pub statuses: Vec<crate::types::RequestStatus>,
604    pub slice: Option<(Start, u32)>,
605    pub newest_waiting: bool,
606    /// The CLI's bounded list in newest Run order, never a Review page.
607    pub list_limit: Option<u32>,
608    /// Only these requests.
609    pub ids: Option<Vec<crate::types::RequestId>>,
610}
611
612#[derive(Debug, Clone)]
613pub(super) struct Row {
614    pub id: crate::types::RequestId,
615    pub run: crate::types::RunId,
616    pub eval: crate::types::EvalId,
617    pub data: String,
618    pub execution: Option<String>,
619    pub execution_id: Option<crate::types::ExecutionId>,
620    pub claim: Option<(
621        crate::types::RequestId,
622        crate::types::ReviewerId,
623        crate::types::Timestamp,
624    )>,
625    /// Its place in the order it was read in.
626    pub mark: Mark,
627}
628
629pub(super) fn rows(db: &rusqlite::Connection, filter: &Query) -> Result<Vec<Row>, Error> {
630    // The repository is saved as its path text; it becomes text only for the parameter.
631    let (mut predicates, mut values): (Vec<String>, Vec<rusqlite::types::Value>) = [
632        ("q.run_id", filter.run.as_ref().map(ToString::to_string)),
633        ("q.id", filter.id.as_ref().map(ToString::to_string)),
634        (
635            "r.repo",
636            filter.repo.as_deref().map(crate::platform::path_text),
637        ),
638        (
639            "json_extract(q.data,'$.sessionId')",
640            filter.session.as_ref().map(ToString::to_string),
641        ),
642    ]
643    .into_iter()
644    .filter_map(|(column, value)| Some((format!("{column}=?"), value?.into())))
645    .unzip();
646    if filter.waiting {
647        predicates.push("q.status IN ('WAITING_HUMAN','DEFERRED')".into());
648    }
649    if let Some(ids) = &filter.ids {
650        predicates.push("q.id IN (SELECT value FROM json_each(?))".into());
651        values.push(serde_json::to_string(ids)?.into());
652    }
653    if !filter.statuses.is_empty() {
654        let marks = vec!["?"; filter.statuses.len()].join(",");
655        predicates.push(format!("q.status IN ({marks})"));
656        values.extend(
657            filter
658                .statuses
659                .iter()
660                .map(|status| rusqlite::types::Value::from(status.as_str().to_owned())),
661        );
662    }
663    // Each order is an index's, so a batch steps through only the requests it reads: Review
664    // order is `request_listed`, newest Run first is the Runs' rowid and a Run's requests by
665    // ordinal (`request_marks`). Requests of Runs listed at the same moment, which only
666    // fixtures make, list by Run ID so the order stays one index. `after` selects what
667    // follows a [`Mark`] in that order, with the values it binds.
668    type After = fn(&Mark) -> (&'static str, Vec<rusqlite::types::Value>);
669    let (order, after): (_, After) = if filter.run.is_some() {
670        ("q.ordinal", |mark| {
671            ("q.ordinal>?", vec![mark.ordinal.into()])
672        })
673    } else if filter.newest_waiting {
674        ("q.listed DESC,q.run_id DESC,q.ordinal", |mark| {
675            (
676                "q.listed<=? AND (q.listed<? OR q.run_id<? OR (q.run_id=? AND q.ordinal>?))",
677                vec![
678                    mark.listed.clone().into(),
679                    mark.listed.clone().into(),
680                    mark.run_id.clone().into(),
681                    mark.run_id.clone().into(),
682                    mark.ordinal.into(),
683                ],
684            )
685        })
686    } else {
687        ("r.rowid DESC,q.ordinal", |mark| {
688            (
689                "r.rowid<=? AND (r.rowid<? OR q.ordinal>?)",
690                vec![mark.run.into(), mark.run.into(), mark.ordinal.into()],
691            )
692        })
693    };
694    let mut limit = "";
695    if let Some(count) = filter.list_limit.filter(|_| filter.run.is_none()) {
696        // Pick just the Runs that could have requests in this page. Every nonempty Run's
697        // requests are admitted together. The last Run in the page may be partial; the
698        // outer query preserves ordinal order and takes only as many as the limit permits.
699        // This also skips arbitrarily many Runs with no requests.
700        let scope = if let Some(repo) = &filter.repo {
701            values.push(crate::platform::path_text(repo).into());
702            "WHERE repo=?"
703        } else {
704            ""
705        };
706        predicates.push(format!(
707            "r.rowid IN (
708                SELECT rr.rowid FROM (
709                    SELECT request_id FROM request_attempts {scope} ORDER BY sequence DESC LIMIT ?
710                ) recent
711                CROSS JOIN requests qq ON qq.id=recent.request_id
712                CROSS JOIN runs rr ON rr.id=qq.run_id
713            )"
714        ));
715        values.push(i64::from(count).into());
716    }
717    // Drive the bounded list by Run, then by request ordinal. Starting with requests
718    // can make SQLite sort the entire newest Run for a short page.
719    let from = if filter.list_limit.is_some() {
720        "runs r CROSS JOIN requests q ON q.run_id=r.id"
721    } else {
722        "requests q JOIN runs r ON r.id=q.run_id"
723    };
724    if let Some(count) = filter.list_limit {
725        values.push(i64::from(count).into());
726        limit = " LIMIT ?";
727    } else if let Some((start, count)) = &filter.slice {
728        let offset = match start {
729            Start::Position(offset) => *offset,
730            Start::After(mark) => {
731                let (predicate, bound) = after(mark);
732                predicates.push(predicate.into());
733                values.extend(bound);
734                0
735            }
736        };
737        values.push(i64::from(*count).into());
738        values.push(i64::try_from(offset).unwrap_or(i64::MAX).into());
739        limit = " LIMIT ? OFFSET ?";
740    }
741    let predicate = if predicates.is_empty() {
742        String::new()
743    } else {
744        format!("WHERE {}", predicates.join(" AND "))
745    };
746    let mut statement = db.prepare_cached(&format!(
747        "SELECT q.id,q.run_id,q.data,e.data,h.id,h.claimed_by,h.claimed_at,q.eval_id,e.id,q.listed,r.rowid,q.ordinal
748        FROM {from}
749        LEFT JOIN executions e ON e.id=q.execution_id
750        LEFT JOIN requests h ON h.id=json_extract(e.data,'$.provenance.requestId') AND h.claimed_by IS NOT NULL
751        {predicate} ORDER BY {order}{limit}"
752    ))?;
753    #[cfg(test)]
754    statement.reset_status(rusqlite::StatementStatus::VmStep);
755    let rows = statement
756        .query_map(rusqlite::params_from_iter(values), |row| {
757            let id = row.get::<_, Option<crate::types::RequestId>>(4)?;
758            let reviewer = row.get::<_, Option<crate::types::ReviewerId>>(5)?;
759            let at = row.get::<_, Option<crate::types::Timestamp>>(6)?;
760            Ok(Row {
761                id: row.get(0)?,
762                run: row.get(1)?,
763                eval: row.get(7)?,
764                data: row.get(2)?,
765                execution: row.get(3)?,
766                execution_id: row.get(8)?,
767                claim: id
768                    .zip(reviewer)
769                    .zip(at)
770                    .map(|((id, reviewer), at)| (id, reviewer, at)),
771                mark: Mark {
772                    listed: row.get(9)?,
773                    run: row.get(10)?,
774                    run_id: row.get(1)?,
775                    ordinal: row.get(11)?,
776                },
777            })
778        })?
779        .collect::<Result<_, _>>()?;
780    #[cfg(test)]
781    crate::performance::sql_steps(statement.reset_status(rusqlite::StatementStatus::VmStep));
782    Ok(rows)
783}
784
785/// Saved definitions are decoded once per Run and indexed by position, never copied whole.
786/// First duplicate Eval wins, matching SQLite's former json_each lookup; missing/null
787/// definitions remain absent.
788pub(super) struct DefinitionIndex {
789    graph: Option<Arc<Graph>>,
790    evals: HashMap<crate::types::EvalId, usize>,
791    /// The copies handed out so far, when each view keeps its own ([`Place::Own`]).
792    copies: Option<Copies>,
793}
794#[derive(Default)]
795struct Copies {
796    evals: HashMap<usize, Arc<super::definitions::Eval>>,
797    artifacts: HashMap<crate::types::ArtifactName, Arc<super::definitions::Artifact>>,
798}
799impl DefinitionIndex {
800    /// The views share the Run's graph: an opened Run's, read as one.
801    pub fn new(run: &super::Run) -> Self {
802        let graph = run.definitions.share();
803        let mut evals = HashMap::new();
804        for (position, eval) in graph.iter().flat_map(|graph| graph.evals()).enumerate() {
805            evals.entry(eval.id.clone()).or_insert(position);
806        }
807        Self {
808            graph,
809            evals,
810            copies: None,
811        }
812    }
813    /// Each view keeps copies of its own eval and Artifact, shared only by the views of this
814    /// read: requests read apart from their Runs.
815    fn apart(run: &super::Run) -> Self {
816        Self {
817            copies: Some(Copies::default()),
818            ..Self::new(run)
819        }
820    }
821    /// No definitions: the views show their requests alone.
822    fn none() -> Self {
823        Self {
824            graph: None,
825            evals: HashMap::new(),
826            copies: None,
827        }
828    }
829    fn definition(
830        &mut self,
831        eval: &crate::types::EvalId,
832        artifact: &crate::types::ArtifactName,
833    ) -> Option<RequestDefinition> {
834        let graph = self.graph.as_ref()?;
835        let saved = graph.artifact(artifact)?;
836        let position = *self.evals.get(eval)?;
837        Some(RequestDefinition(match &mut self.copies {
838            None => Place::Graph {
839                graph: graph.clone(),
840                eval: position,
841                artifact: artifact.clone(),
842            },
843            Some(copies) => Place::Own {
844                eval: copies
845                    .evals
846                    .entry(position)
847                    .or_insert_with(|| Arc::new(graph.evals()[position].clone()))
848                    .clone(),
849                artifact: copies
850                    .artifacts
851                    .entry(artifact.clone())
852                    .or_insert_with(|| Arc::new(saved.clone()))
853                    .clone(),
854            },
855        }))
856    }
857}
858impl Row {
859    pub fn view(&self, index: &mut DefinitionIndex) -> Option<RequestView> {
860        let request = super::unreadable::evidence::<Request>("request", &self.data)?;
861        let execution = self
862            .execution
863            .as_deref()
864            .and_then(|data| super::unreadable::evidence("execution", data));
865        Some(self.with_evidence(index, request, execution))
866    }
867    /// The request's view and why any of its records do not read. A request that does not read
868    /// has no view; an execution that does not read leaves the view without it.
869    pub fn read(
870        &self,
871        index: &mut DefinitionIndex,
872    ) -> (Option<RequestView>, Vec<super::Unreadable>) {
873        let mut unreadable = Vec::new();
874        let execution = self
875            .execution
876            .as_deref()
877            .zip(self.execution_id.as_ref())
878            .and_then(|(data, id)| {
879                super::unreadable::decode("execution", id, data)
880                    .map_err(|record| unreadable.push(record))
881                    .ok()
882            });
883        let view = super::unreadable::decode::<Request>("request", &self.id, &self.data)
884            .map_err(|record| unreadable.push(record))
885            .ok()
886            .map(|request| self.with_evidence(index, request, execution));
887        (view, unreadable)
888    }
889    fn with_evidence(
890        &self,
891        index: &mut DefinitionIndex,
892        request: Request,
893        execution: Option<Execution>,
894    ) -> RequestView {
895        let definition = index.definition(&self.eval, &request.target);
896        RequestView {
897            request: Arc::new(request),
898            definition,
899            execution: execution.map(Arc::new),
900            claim: self.claim.as_ref().map(|(id, reviewer, at)| HumanClaim {
901                request_id: id.clone(),
902                reviewer: reviewer.clone(),
903                claimed_at: *at,
904            }),
905        }
906    }
907}
908
909/// Both selected-Run view shapes from the same short read transaction and decoded rows.
910pub async fn read_run_requests(
911    state: &Path,
912    id: &str,
913) -> Result<(super::RunView, Vec<RequestView>), String> {
914    read_run_requests_by_id(state, &id.parse()?).await
915}
916
917/// Both selected-Run view shapes for an already validated Run ID.
918pub async fn read_run_requests_by_id(
919    state: &Path,
920    id: &crate::types::RunId,
921) -> Result<(super::RunView, Vec<RequestView>), String> {
922    let state = state.to_path_buf();
923    let id = id.clone();
924    crate::task::joined(
925        tokio::task::spawn_blocking(move || {
926            let mut reader = super::reader::Reader::default();
927            reader
928                .snapshot(&state, |db, cache, state| {
929                    cache.selected(db, state, &id, true)
930                })?
931                .ok_or_else(|| "Run not found.".into())
932        })
933        .await,
934    )
935    .map_err(|error| error.to_string())?
936}