artifactize-core 0.33.0

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! Run admission and cancellation share the Run row's write lock with scheduler saves.
use super::{Receipts, Request, Run, receipts::Error};
use crate::{
    runs::{Activity, Control, Worker},
    types::{FailureCode, RequestKey, RequestStatus, RunId, RunStatus},
};
use rusqlite::{OptionalExtension, TransactionBehavior, params};

use super::run_record::load;

/// The saved Run's status and control, which a save merges with.
fn saved_control(
    db: &rusqlite::Connection,
    id: &RunId,
) -> Result<(RunStatus, Option<Control>), Error> {
    let (status, control): (RunStatus, Option<String>) = db.query_row(
        "SELECT status,json_extract(data,'$.control') FROM runs WHERE id=?",
        [id],
        |row| Ok((row.get(0)?, row.get(1)?)),
    )?;
    Ok((
        status,
        control
            .map(|text| serde_json::from_str(&text))
            .transpose()?,
    ))
}

/// Never replace concurrent admission/cancellation with an older scheduler clone.
pub(super) fn save(db: &rusqlite::Connection, mut run: Run) -> Result<(), Error> {
    let (status, saved) = saved_control(db, &run.id)?;
    if !status.is_open() && saved.is_some() {
        return Ok(());
    }
    merge_scheduler_control(&mut run, saved, crate::broker::now());
    super::run_record::update(db, &run)
}

/// Preserve saved admission and cancellation state when the scheduler publishes its view.
fn merge_scheduler_control(run: &mut Run, saved: Option<Control>, at: crate::types::Timestamp) {
    let running = run.status().is_open();
    if let (Some(control), Some(saved)) = (&mut run.control, saved) {
        control.worker = saved.worker;
        if saved.is_cancelling() {
            control.activity = Activity::Cancelling;
        }
        if control.is_cancelling()
            && !running
            && control.failure_code != Some(crate::types::FailureCode::OwnerDied)
        {
            control.failure_code = Some(crate::types::FailureCode::Cancelled);
            run.state = super::RunState::Error {
                at,
                error: Some("Run was cancelled.".into()),
            };
            if let Some(validation) = &mut run.validation.0 {
                validation.satisfied = crate::config::Field::Value(false);
            }
        }
    }
}

impl Receipts {
    pub(crate) async fn keyed_run(
        &self,
        repo: &std::path::Path,
        key: &RequestKey,
        expected_args_hash: Option<&str>,
    ) -> Result<Option<RunId>, String> {
        let repo = crate::platform::path_text(repo);
        let key = key.clone();
        let expected_args_hash = expected_args_hash.map(str::to_owned);
        self.connection
            .call(move |db| -> Result<Option<RunId>, Error> {
                let row: Option<(RunId, Option<String>)> = db
                    .query_row(
                        "SELECT id, json_extract(data,'$.requestArgsHash') FROM runs WHERE repo=? AND request_key=?",
                        params![repo, key],
                        |row| Ok((row.get(0)?, row.get(1)?)),
                    )
                    .optional()?;
                if let Some((id, saved_hash)) = row {
                    if expected_args_hash.is_some() && saved_hash != expected_args_hash {
                        return Err(Error::Invalid(
                            "Conflicting verify arguments for the same request_key.".into(),
                        ));
                    }
                    return Ok(Some(id));
                }
                Ok(None)
            })
            .await
            .map_err(|error| error.to_string())
    }

    pub(crate) async fn reserve(&self, run: &Run, requests: &[Request]) -> Result<RunId, String> {
        let run = run.clone();
        let requests = requests.to_vec();
        self.connection.call(move |db| -> Result<RunId, Error> {
            let transaction = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
            let repo = crate::platform::path_text(&run.repo_path);
            if let Some(key) = &run.request_key
                && let Some((id, saved_hash)) = transaction
                    .query_row(
                        "SELECT id, json_extract(data,'$.requestArgsHash') FROM runs WHERE repo=? AND request_key=?",
                        params![repo, key],
                        |row| Ok((row.get::<_, RunId>(0)?, row.get::<_, Option<String>>(1)?)),
                    )
                    .optional()?
            {
                if run.request_args_hash.is_some() && saved_hash != run.request_args_hash {
                    return Err(Error::Invalid(
                        "Conflicting verify arguments for the same request_key.".into(),
                    ));
                }
                return Ok(id);
            }
            super::run_record::insert(&transaction, &run)?;
            for (ordinal, request) in requests.iter().enumerate() {
                transaction.execute("INSERT INTO requests(id,run_id,eval_id,ordinal,status,data) VALUES (?,?,?,?,?,?)", params![request.id,run.id,request.eval_id,ordinal as i64,request.status(),serde_json::to_string(request)?])?;
            }
            transaction.commit()?;
            Ok(run.id)
        }).await.map_err(|error| error.to_string())
    }

    /// Change the Run's control under the Run row's write lock. `change` sees the saved status
    /// and control, and only the control is written back: neither the Run's state nor its
    /// definitions are decoded, however large its catalog is.
    pub(crate) async fn control(
        &self,
        id: &RunId,
        change: impl FnOnce(RunStatus, &mut Option<Control>) -> Result<(), String> + Send + 'static,
    ) -> Result<(RunStatus, Option<Control>), String> {
        let id = id.clone();
        self.connection
            .call(move |db| -> Result<_, Error> {
                let transaction = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
                let (status, mut control) = saved_control(&transaction, &id)?;
                change(status, &mut control).map_err(Error::Invalid)?;
                let text = control.as_ref().map(serde_json::to_string).transpose()?;
                transaction.execute(
                    "UPDATE runs SET data=CASE WHEN ?1 IS NULL THEN json_remove(data,'$.control') ELSE json_set(data,'$.control',json(?1)) END WHERE id=?2",
                    params![text, id],
                )?;
                transaction.commit()?;
                Ok((status, control))
            })
            .await
            .map_err(|error| error.to_string())
    }

    pub(crate) async fn fail_run(
        &self,
        id: &RunId,
        code: crate::types::FailureCode,
        error: String,
    ) -> Result<(), String> {
        let id = id.clone();
        self.connection
            .call(move |db| -> Result<(), Error> {
                let transaction = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
                let mut run = load(&transaction, &id)?;
                if !run.status().is_open() {
                    return Ok(());
                }
                let requests = {
                    let mut statement = transaction.prepare(concat!(
                        "SELECT data FROM requests WHERE run_id=? ",
                        "AND status NOT IN ('GREEN','RED','ERROR')"
                    ))?;
                    statement
                        .query_map([&id], |row| row.get::<_, String>(0))?
                        .collect::<Result<Vec<_>, _>>()?
                };
                for data in requests {
                    let mut request: Request = serde_json::from_str(&data)?;
                    request.state = super::RequestState::failed(
                        error.clone(),
                        Some(code),
                        crate::broker::now(),
                    );
                    super::receipts::update_request(&transaction, &request)?;
                }
                run.state = super::RunState::Error {
                    at: crate::broker::now(),
                    error: Some(error),
                };
                if let Some(control) = &mut run.control {
                    control.failure_code = Some(code);
                }
                save(&transaction, run)?;
                transaction.commit()?;
                Ok(())
            })
            .await
            .map_err(|e| e.to_string())
    }

    /// Ask the Run to stop; the saved status and control after the request.
    pub(crate) async fn request_cancel(
        &self,
        id: &RunId,
    ) -> Result<(RunStatus, Option<Control>), String> {
        self.control(id, |status, control| {
            if status.is_open() {
                let control = control.get_or_insert_with(Control::legacy);
                control.activity = Activity::Cancelling;
            }
            Ok(())
        })
        .await
    }
    /// Retire only this Run's own active executions; other Runs sharing the same Verify engine
    /// process and joined executions belonging to another Run stay untouched. A sign-off still
    /// waiting on a retired execution, deferred or joined from another Run, could never be
    /// claimed again, so it ends with the execution.
    pub(crate) async fn retire_worker(
        &self,
        id: &RunId,
        code: crate::types::FailureCode,
    ) -> Result<(), String> {
        let id = id.clone();
        self.connection.call(move |db| -> Result<(), Error> {
            let transaction = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
            let (_, control) = saved_control(&transaction, &id)?;
            if let Some(Control { worker: Worker::Admitted { owner }, .. }) = control {
                let executions = {
                    let mut statement = transaction.prepare(
                        "SELECT id FROM executions WHERE owner_pid=?1 AND owner_start_time=?2 AND status IN ('RUNNING','WAITING_HUMAN') AND json_valid(data) AND json_extract(data,'$.provenance.runId')=?3",
                    )?;
                    statement.query_map(params![owner.pid.get(), owner.start_time as i64, id], |row| row.get(0))?.collect::<Result<Vec<crate::types::ExecutionId>, _>>()?
                };
                for id in executions {
                    retire_execution(&transaction, &id, code, "Run worker stopped.")?;
                }
            }
            transaction.commit()?;
            Ok(())
        }).await.map_err(|e| e.to_string())
    }
}

/// End an active execution and every Human request still waiting on it.
pub(super) fn retire_execution(
    db: &rusqlite::Connection,
    id: &crate::types::ExecutionId,
    code: crate::types::FailureCode,
    error: &str,
) -> Result<(), Error> {
    let at = crate::broker::now();
    let waiting = {
        let mut statement = db.prepare("SELECT q.data FROM requests q JOIN executions e ON e.id=q.execution_id WHERE e.id=? AND e.status='WAITING_HUMAN' AND q.status IN ('WAITING_HUMAN','DEFERRED')")?;
        statement
            .query_map([id], |row| row.get::<_, String>(0))?
            .collect::<Result<Vec<_>, _>>()?
    };
    db.execute("UPDATE executions SET status='ERROR',data=json_set(data,'$.status','ERROR','$.error',?1,'$.errorCode',?2,'$.result',NULL,'$.completedAt',?3) WHERE id=?4 AND status IN ('RUNNING','WAITING_HUMAN')", params![error,code,at,id])?;
    for data in waiting {
        retire_request(db, serde_json::from_str(&data)?, code, error, at)?;
    }
    Ok(())
}

pub(super) fn retire_request(
    db: &rusqlite::Connection,
    mut request: Request,
    code: crate::types::FailureCode,
    error: &str,
    at: crate::types::Timestamp,
) -> Result<(), Error> {
    request.state = super::RequestState::failed(error.into(), Some(code), at);
    super::receipts::update_request(db, &request)
}

/// Compact observations don't decode saved graphs, owner payloads or execution logs.
pub(crate) struct Observation {
    pub status: RunStatus,
    pub control: Option<Control>,
    pub repo: std::path::PathBuf,
    pub created_at: crate::types::Timestamp,
    pub completed_at: Option<crate::types::Timestamp>,
    pub counts: std::collections::BTreeMap<RequestStatus, u64>,
    pub error_codes: Vec<Option<FailureCode>>,
}

fn snapshot(state: &std::path::Path, id: &RunId, errors: bool) -> Result<Observation, Error> {
    let mut db = rusqlite::Connection::open_with_flags(
        state.join(super::DATABASE),
        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
    )?;
    super::wait_when_busy(&db)?;
    let transaction = db.transaction()?;
    if !super::receipts::schema_initialized(&transaction)? {
        return Err(Error::Invalid("Run not found.".into()));
    }
    let (mut saved, control): (Observation, Option<String>) = transaction.query_row(
        "SELECT repo,status,json_extract(data,'$.control'),json_extract(data,'$.createdAt'),json_extract(data,'$.completedAt') FROM runs WHERE id=?", [id],
        |row| Ok((Observation {
            repo: super::path_column(row, 0)?, status: row.get(1)?, control: None,
            created_at: row.get(3)?, completed_at: row.get(4)?, counts: Default::default(), error_codes: Vec::new(),
        }, row.get(2)?))).optional()?.ok_or_else(|| Error::Invalid("Run not found.".into()))?;
    crate::workspace::outside_workspace(&saved.repo, state)
        .map_err(|e| Error::Invalid(e.to_string()))?;
    saved.counts = {
        let mut statement = transaction
            .prepare("SELECT status,count(*) FROM requests WHERE run_id=? GROUP BY status")?;
        statement
            .query_map([id], |row| {
                Ok((
                    row.get(0)?,
                    u64::try_from(row.get::<_, i64>(1)?).expect("COUNT(*) is nonnegative"),
                ))
            })?
            .collect::<Result<_, _>>()?
    };
    if errors && saved.counts.contains_key(&RequestStatus::Error) {
        let mut statement = transaction.prepare(
            "SELECT DISTINCT json_extract(data,'$.errorCode') FROM requests WHERE run_id=? AND status=?",
        )?;
        saved.error_codes = statement
            .query_map(params![id, RequestStatus::Error], |row| row.get(0))?
            .collect::<Result<_, _>>()?;
    }
    saved.status = saved
        .status
        .with_signoffs(saved.counts.keys().any(|status| status.is_human_wait()));
    saved.control = control
        .map(|text| serde_json::from_str(&text))
        .transpose()?;
    transaction.commit()?;
    Ok(saved)
}

pub(crate) async fn observe(state: &std::path::Path, id: &RunId) -> Result<Observation, String> {
    observe_with_errors(state, id, false).await
}

pub(crate) async fn observe_with_errors(
    state: &std::path::Path,
    id: &RunId,
    errors: bool,
) -> Result<Observation, String> {
    let state = state.to_path_buf();
    let id = id.clone();
    crate::task::joined(
        tokio::task::spawn_blocking(move || {
            super::receipts::check_files(&state)?;
            snapshot(&state, &id, errors).map_err(|e| e.to_string())
        })
        .await,
    )
    .map_err(|e| e.to_string())?
}

/// The repository a saved Run belongs to, read from its columns alone.
pub async fn read_run_repo(
    state: &std::path::Path,
    id: &RunId,
) -> Result<std::path::PathBuf, String> {
    let state = crate::workspace::canonical_target(state).map_err(|e| e.to_string())?;
    Ok(observe(&state, id).await?.repo)
}

/// Read-only fast-path check for an existing Run registered under `(repo, request_key)`.
/// Returns `Ok(None)` when the state database does not yet exist or has no matching key.
pub(crate) async fn read_keyed_run(
    state: &std::path::Path,
    repo: &std::path::Path,
    key: &RequestKey,
    expected_args_hash: Option<&str>,
) -> Result<Option<RunId>, String> {
    let state = state.to_path_buf();
    let repo = crate::platform::path_text(repo);
    let key = key.clone();
    let expected_args_hash = expected_args_hash.map(str::to_owned);
    crate::task::joined(
        tokio::task::spawn_blocking(move || -> Result<Option<RunId>, String> {
            super::receipts::regular_files(&state)?;
            let path = state.join(super::DATABASE);
            if !crate::platform::paths::target_exists(&path).map_err(|error| error.to_string())? {
                return Ok(None);
            }
            super::receipts::check_files(&state)?;
            let mut db = rusqlite::Connection::open_with_flags(
                path,
                rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
            )
            .map_err(|error| error.to_string())?;
            super::wait_when_busy(&db).map_err(|error| error.to_string())?;
            let transaction = db.transaction().map_err(|error| error.to_string())?;
            if !super::receipts::schema_initialized(&transaction)
                .map_err(|error| error.to_string())?
            {
                return Ok(None);
            }
            let row: Option<(RunId, Option<String>)> = transaction
                .query_row(
                    "SELECT id, json_extract(data,'$.requestArgsHash') FROM runs WHERE repo=? AND request_key=?",
                    params![repo, key],
                    |row| Ok((row.get(0)?, row.get(1)?)),
                )
                .optional()
                .map_err(|error| error.to_string())?;
            if let Some((id, saved_hash)) = row {
                if expected_args_hash.is_some() && saved_hash != expected_args_hash {
                    return Err("Conflicting verify arguments for the same request_key.".into());
                }
                return Ok(Some(id));
            }
            Ok(None)
        })
        .await,
    )
    .map_err(|error| error.to_string())?
}