thirdshift 0.31.0

Turn a GitHub issue into a ready-for-review pull request, unattended
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
//! A resumable Experiment owns its fixed inputs and Trial artifacts. Command
//! recording stays in the ordinary logs; private Eval data stays here.

mod accounting;
mod coordination;
mod cost;
pub(crate) mod deciders;
mod difficulty;
mod efficiency;
mod evidence;
mod execution;
mod grading;
mod integrity;
mod leaks;
mod model_grader;
mod names;
mod options;
pub(crate) mod pairs;
pub(crate) mod pairwise;
mod panel;
mod reading;
mod rechecks;
mod release;
mod retention;
mod session_evidence;
mod store;
mod trace;
mod trial;
mod trial_results;
mod trial_sessions;
mod usage;
mod workers;

use std::collections::BTreeMap;
use std::path::Path;

use anyhow::{Context, Result, ensure};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use super::{arms, format, suite};
use crate::config::UserConfig;
use crate::git::Git;
use crate::harness::{Choice, ChosenBy, Harness};
use crate::issue::Repo;
use crate::trial::VoidCause;
use crate::verdict::{Levels, decimal};
use crate::{interrupt, logs, progress};

pub(crate) use evidence::RunningTrial;
pub(crate) use grading::{Conclusion, Flip, Pending};
pub(crate) use leaks::decide as decide_leak;
pub(crate) use names::setup_changes;
pub use options::{Options, parse};
pub(crate) use rechecks::record as recheck;
pub(crate) use session_evidence::{SessionLog, read as read_session};
pub(crate) use store::{State, View, read};
pub(crate) use trial_results::{Arm, TrialResult, trial_key};

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub(crate) struct Bar {
    #[serde(deserialize_with = "decimal")]
    pub margin: f64,
    #[serde(flatten)]
    pub levels: Levels,
    #[serde(deserialize_with = "decimal")]
    pub prior: f64,
    pub seed: u64,
    pub draws: usize,
    pub trials_per_task: BTreeMap<String, usize>,
    /// Absent in Experiments that judged every approved Eval task.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub discriminating_tasks: Option<BTreeMap<String, Vec<String>>>,
    /// Absent in saved Experiments from before Advisory suites.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_discriminating_tasks: Option<usize>,
    pub timeout_seconds: u64,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "efficiency::optional_decimal"
    )]
    pub cost_ceiling: Option<f64>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "efficiency::optional_decimal"
    )]
    pub time_ceiling: Option<f64>,
    pub void_rules: VoidRules,
    /// Absent when no Grader panel grades the pairs of Trials.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub panel: Option<panel::Panel>,
    /// Absent when anyone may read any pair, beside the Verdict.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub people: Option<deciders::PeopleSetting>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub(crate) struct VoidRules {
    pub retries: usize,
    pub causes: Vec<VoidCause>,
}

impl Default for Bar {
    fn default() -> Self {
        let statistics = crate::verdict::Bar::default();
        Self {
            margin: statistics.margin,
            levels: statistics.levels,
            prior: statistics.prior,
            seed: statistics.seed,
            draws: statistics.draws,
            trials_per_task: BTreeMap::new(),
            discriminating_tasks: None,
            min_discriminating_tasks: None,
            timeout_seconds: 1800,
            cost_ceiling: None,
            time_ceiling: None,
            void_rules: VoidRules {
                retries: 2,
                causes: [
                    VoidCause::SessionUnavailable,
                    VoidCause::UsageLimit,
                    VoidCause::RateLimit,
                    VoidCause::Interrupted,
                    VoidCause::RepositoryChanged,
                    VoidCause::SandboxUnavailable,
                    VoidCause::HostKilled,
                    VoidCause::MemoryCap,
                ]
                .into(),
            },
            panel: None,
            people: None,
        }
    }
}

impl Bar {
    fn advisory(&self, suite: &str) -> Option<bool> {
        self.min_discriminating_tasks.map(|minimum| {
            self.discriminating_tasks
                .as_ref()
                .and_then(|suites| suites.get(suite))
                .map_or(0, Vec::len)
                < minimum
        })
    }

    fn judges(&self, suite: &str, task: &str) -> bool {
        self.discriminating_tasks.as_ref().is_none_or(|suites| {
            suites
                .get(suite)
                .is_some_and(|tasks| tasks.iter().any(|name| name == task))
        })
    }
}

#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct Setup {
    pub commit: String,
    pub harness: String,
    pub model: Option<String>,
    pub effort: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub process: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub process_digest: Option<String>,
}

impl Setup {
    fn requested(&self) -> Result<arms::Requested> {
        Ok(
            arms::Requested::new(&self.commit, &self.harness)?.with_process(
                self.process.as_deref(),
                self.model.as_deref(),
                self.effort.as_deref(),
            ),
        )
    }

    fn choice(&self) -> Choice {
        Choice {
            harness: Harness::named(&self.harness).expect("validated Arm Harness"),
            model: self.model.clone(),
            effort: self.effort.clone(),
            chosen_by: ChosenBy::Command,
        }
    }
}

/// Only these public Experiment facts enter factory logs, never task inputs.
#[derive(Clone, Serialize, Deserialize)]
pub(crate) struct Description {
    pub id: String,
    pub baseline: Setup,
    pub candidate: Setup,
    pub suites: Vec<String>,
    pub bar: Bar,
    pub prepared: Option<arms::Prepared>,
}

impl Description {
    pub(crate) fn setup(&self, arm: Arm) -> &Setup {
        match arm {
            Arm::Baseline => &self.baseline,
            Arm::Candidate => &self.candidate,
        }
    }
}

#[derive(Serialize, Deserialize)]
struct Task {
    suite: String,
    name: String,
    directory: std::path::PathBuf,
    manifest: format::Task,
}

pub fn run(options: Options) -> Result<()> {
    interrupt::install()?;
    let repository = std::env::current_dir()?;
    let git = Git::new(&repository);
    let candidate = resolve(&git, &options.candidate)?;
    let baseline_reference = if options.release && options.baseline.is_none() {
        Some(git.run(&[
            "--no-replace-objects",
            "describe",
            "--tags",
            "--abbrev=0",
            "--match",
            "v[0-9]*",
            &candidate,
        ])?)
    } else {
        options.baseline.clone()
    };
    let baseline = match &baseline_reference {
        Some(reference) => resolve(&git, reference)?,
        None => git.run(&["--no-replace-objects", "merge-base", "main", &candidate])?,
    };
    let root = crate::config::home()?.join(".thirdshift/evals");
    let suites_root = root.join("suites");
    let suites = if options.suites.is_empty() {
        let paths = git.run(&[
            "--no-replace-objects",
            "diff",
            "--name-only",
            "--no-renames",
            &baseline,
            &candidate,
            "--",
        ])?;
        suite::touched(
            &suites_root,
            &paths.lines().map(String::from).collect::<Vec<_>>(),
        )?
    } else {
        options.suites.clone()
    };
    if suites.is_empty() && options.release {
        return release::skip(
            "no_suites",
            "no Eval suite touched; no release Experiment needed",
            options.json,
        );
    }
    ensure!(
        !suites.is_empty(),
        "no Eval suites selected; use --suite for a defaults-only Experiment"
    );
    let config = UserConfig::load()?;
    let mut baseline = options.baseline_setup.resolve(baseline, &config);
    let mut candidate = options.candidate_setup.resolve(candidate, &config);
    let mut bar = options.bar;
    // Keep the judged list and the retained manifest snapshots on one reading
    // of Difficulty, fenced against approval and Difficulty publication.
    let suite_locks = suites
        .iter()
        .map(|name| suite::lock(&suites_root.join(name)))
        .collect::<Result<Vec<_>>>()?;
    let mut discriminating = BTreeMap::new();
    for name in &suites {
        let manifest = suite::Manifest::load(&suites_root.join(name))?;
        bar.trials_per_task.insert(
            name.clone(),
            options
                .trials_per_task
                .unwrap_or(manifest.trials_per_arm.get()),
        );
        let mut listed = Vec::new();
        for (name, directory) in suite::directories(&suites_root.join(name).join("tasks"))? {
            let task = format::Task::load(&directory)?;
            if task.state == format::State::Approved && task.session == format::Session::Process {
                for setup in [&mut baseline, &mut candidate] {
                    setup.process.get_or_insert_with(|| "ticket-run".into());
                }
            }
            if task.state == format::State::Approved
                && task
                    .difficulty
                    .as_ref()
                    .is_some_and(format::Difficulty::discriminating)
            {
                listed.push(name);
            }
        }
        discriminating.insert(name.clone(), listed);
    }
    bar.discriminating_tasks = Some(discriminating);
    ensure!(
        bar.trials_per_task.values().all(|n| matches!(n, 1 | 3)),
        "Trials per Eval task must be one or three"
    );
    for setup in [&mut baseline, &mut candidate] {
        setup.process_digest = arms::Process::source_digest(&setup.requested()?)?;
    }
    let identity = serde_json::to_vec(&(&baseline, &candidate, &suites))?;
    let id = format!("{:x}", Sha256::digest(identity));
    let description = Description {
        id,
        baseline,
        candidate,
        suites,
        bar,
        prepared: None,
    };
    panel::check_stand_in(&description)?;
    let fresh = !root
        .join("experiments")
        .join(&description.id)
        .join("experiment.json")
        .exists();
    let Some(mut experiment) =
        store::Stored::open(&root.join("experiments"), description, |description| {
            // The release Baseline probe can build an Arm too. Check new
            // Experiments first; resumes keep the tasks already recorded.
            let tasks = tasks(&suites_root, &description.suites)?;
            deciders::check(&description.bar, &tasks)?;
            if options.release
                && !release::supports_trials(&repository, &root, &description.baseline.commit)?
            {
                return Ok(None);
            }
            Ok(Some(tasks))
        })?
    else {
        let tag = baseline_reference.as_deref().expect("release Baseline tag");
        return release::skip(
            "baseline_without_trial",
            &format!("last release {tag} has no Trial flag; carrying on without an Experiment"),
            options.json,
        );
    };
    drop(suite_locks);
    if let Some(path) = &options.prices {
        let prices = crate::trial::accounting::Prices::load(path)?;
        ensure!(
            !experiment.directory.join("started").exists()
                || experiment.pricing.as_ref() == Some(&prices),
            "price table cannot change after the first Trial"
        );
        experiment.pricing = Some(prices);
        experiment.save()?;
    }
    if let Some(name) = options.name {
        experiment.rename(Some(name))?;
    }
    if experiment.state == State::Completed {
        retention::repositories(&experiment);
        println!("{}", experiment.render(options.json)?);
        logs::start_notice::skipped(format!(
            "Experiment {} is already completed",
            experiment.description.id
        ));
        return Ok(());
    }
    if let Err(error) = cost::confirm(&experiment, options.yes) {
        // A declined new Experiment leaves no record to list as running.
        if fresh {
            experiment.discard()?;
        }
        return Err(error);
    }
    if experiment.details.candidate_ref.is_none() {
        experiment.details.baseline_ref =
            Some(baseline_reference.unwrap_or_else(|| "main (merge base)".into()));
        experiment.details.candidate_ref = Some(options.candidate.clone());
        experiment.details.title = Some(git.run(&[
            "log",
            "-1",
            "--format=%s",
            &experiment.description.candidate.commit,
        ])?);
    }
    experiment.details.release |= options.release;
    experiment.details.resume_command = Some(
        std::iter::once("thirdshift".to_owned())
            .chain(
                resume_args(std::env::args().skip(1))
                    .into_iter()
                    .map(|arg| format!("'{}'", arg.replace('\'', "'\\''"))),
            )
            .collect::<Vec<_>>()
            .join(" "),
    );
    logs::begin(logs::Begin::Experiment);
    logs::configured(&config);
    let repo = Repo {
        owner: "JacobStephens2".into(),
        name: "thirdshift".into(),
    };
    logs::started(
        logs::Work::Experiment(&repo),
        &experiment.description.candidate.choice(),
    );
    logs::experiment(&experiment.description);
    logs::resumable(experiment.details.resume_command.as_deref().unwrap());
    experiment.details.command_log = logs::command_log_path();
    experiment.details.ended_at = None;
    experiment.details.pause_reason = None;
    let result = (|| {
        experiment.state = State::Running;
        experiment.save()?;
        coordination::start(&mut experiment, options.no_wait)?;
        logs::stage(logs::Stage::ArmBuilds);
        if experiment.description.prepared.is_none() {
            let description = &experiment.description;
            let requested = [
                description.baseline.requested()?,
                description.candidate.requested()?,
            ];
            let record = experiment.directory.join("arms.json");
            if record.exists() {
                experiment.description.prepared =
                    Some(serde_json::from_slice(&std::fs::read(record)?)?);
            } else {
                experiment.description.prepared =
                    Some(arms::prepare(&repository, requested, &record)?);
            }
            let prepared = experiment
                .description
                .prepared
                .as_ref()
                .context("missing prepared Arms")?;
            for (setup, arm) in [
                (&experiment.description.baseline, &prepared.baseline),
                (&experiment.description.candidate, &prepared.candidate),
            ] {
                if let Some(expected) = &setup.process_digest {
                    ensure!(
                        arm.process
                            .as_ref()
                            .context("missing frozen Arm Process")?
                            .digest()?
                            == *expected,
                        "Custom process inputs changed during Arm preparation; start the Experiment again"
                    );
                }
            }
            experiment.save()?;
            logs::experiment(&experiment.description);
        }
        logs::stage(logs::Stage::EvalTasks);
        model_grader::prepare(&experiment, &config.harness)?;
        panel::prepare(&experiment)?;
        workers::run(&experiment)?;
        pairs::run(&experiment)?;
        // The panel grades last, so a pause in it holds back no model Score.
        model_grader::run(&experiment)?;
        panel::run(&experiment)?;
        experiment.refresh_verdict()?;
        experiment.state = State::Completed;
        Ok(())
    })();
    let cause = result
        .as_ref()
        .err()
        .map(|error: &anyhow::Error| format!("{error:#}"));
    coordination::publish_waiting_for(&mut experiment, &[]);
    if result.is_err() {
        experiment.state = if interrupt::requested() {
            State::Interrupted
        } else {
            State::Paused
        };
    }
    experiment.details.ended_at =
        (experiment.state == State::Completed).then(|| chrono::Local::now().to_rfc3339());
    experiment.details.pause_reason = cause.clone();
    let saved = experiment.save();
    if result.is_ok() && saved.is_ok() {
        retention::repositories(&experiment);
        // Results contain private Grader evidence, unlike the public Command
        // facts. Print them without copying them into the factory's logs.
        println!("{}", experiment.render(options.json)?);
    }
    let outcome = if interrupt::requested() {
        "interrupted"
    } else if saved.is_ok()
        && result
            .as_ref()
            .err()
            .is_some_and(|error| error.is::<crate::session::limits::Reached>())
    {
        let reached = result
            .as_ref()
            .unwrap_err()
            .downcast_ref::<crate::session::limits::Reached>()
            .unwrap();
        logs::paused(&reached.0);
        "paused"
    } else if result.is_err() || saved.is_err() {
        "failed"
    } else {
        experiment
            .verdict
            .as_ref()
            .context("completed Experiment has no Verdict")?
            .outcome()
    };
    logs::ended(outcome);
    logs::experiment_finished(outcome, cause.as_deref());
    progress::step(format!(
        "Experiment {} {outcome}",
        experiment.description.id
    ));
    result.and(saved)
}

pub fn show(args: &[String]) -> Result<String> {
    let json = args.iter().any(|arg| arg == "--json");
    let positional: Vec<_> = args.iter().filter(|arg| arg.as_str() != "--json").collect();
    let root = crate::config::home()?.join(".thirdshift/evals/experiments");
    if let [id, flag, hit, decision, reason_flag, reason] = positional.as_slice()
        && flag.as_str() == "--leak"
        && reason_flag.as_str() == "--reason"
    {
        return decide_leak(
            id,
            hit,
            decision,
            reason,
            logs::Actor::cli("a leak decision")?,
            json,
        );
    }
    if let [id, flag, pair, rest @ ..] = positional.as_slice()
        && flag.as_str() == "--pair"
    {
        let page = match rest {
            [] => pairwise::page(id, pair, &logs::Actor::cli("a blind pair")?)?,
            [flag, a, b] if flag.as_str() == "--merge" => {
                pairwise::merge(id, pair, a, b, logs::Actor::cli("merge calls")?)?
            }
            [flag, preference, rubric @ ..] if flag.as_str() == "--prefer" => {
                let mut graded = Vec::new();
                for chunk in rubric.chunks(2) {
                    let [flag, value] = chunk else {
                        anyhow::bail!("--rubric needs <criterion>=<a|b|tie|both-bad>");
                    };
                    let (criterion, value) = value
                        .split_once('=')
                        .filter(|_| flag.as_str() == "--rubric")
                        .context("--rubric needs <criterion>=<a|b|tie|both-bad>")?;
                    graded.push((criterion.to_owned(), value.to_owned()));
                }
                pairwise::prefer(
                    id,
                    pair,
                    preference,
                    &graded,
                    logs::Actor::cli("a preference")?,
                )?
            }
            _ => anyhow::bail!("{PAIR_USAGE}"),
        };
        return if json {
            Ok(serde_json::to_string_pretty(&page)?)
        } else {
            Ok(pairwise::text(&page))
        };
    }
    if let [id, flag] = positional.as_slice()
        && flag.as_str() == "--record-difficulty"
    {
        return difficulty::record(&root, id, json);
    }
    if let [id, flag, name] = positional.as_slice()
        && flag.as_str() == "--name"
    {
        return store::rename(&root, id, names::parse(name)?, json);
    }
    if let [id, flag, session] = positional.as_slice()
        && flag.as_str() == "--session"
    {
        let session = read_session(id, session)?;
        return Ok(if json {
            serde_json::to_string_pretty(&session)?
        } else {
            session.contents
        });
    }
    ensure!(
        positional.len() <= 1,
        "usage: thirdshift experiments [<id>] [--json], experiments <id> --record-difficulty [--json], experiments <id> --name <text> [--json], experiments <id> --session <session-id> [--json], experiments <id> --leak <hit-id> <confirm|dismiss> --reason <text> [--json] or {PAIR_USAGE}"
    );
    store::show(&root, positional.first().map(|id| id.as_str()), json)
}

const PAIR_USAGE: &str = "experiments <id> --pair <pair-id> [--merge <ready|not-ready> <ready|not-ready> | --prefer <a|b|tie|both-bad> [--rubric <criterion>=<a|b|tie|both-bad>]...] [--json]";

/// The shown resume command leaves out `--name`, so following it keeps a
/// later rename. Flags pair with values as `options::parse` reads them.
fn resume_args(mut args: impl Iterator<Item = String>) -> Vec<String> {
    let mut kept = Vec::new();
    while let Some(arg) = args.next() {
        if matches!(arg.as_str(), "--json" | "--release" | "--yes" | "--no-wait")
            || !arg.starts_with("--")
        {
            kept.push(arg);
        } else if arg == "--name" {
            args.next();
        } else {
            kept.push(arg);
            kept.extend(args.next());
        }
    }
    kept
}

fn resolve(git: &Git, reference: &str) -> Result<String> {
    git.run(&[
        "--no-replace-objects",
        "rev-parse",
        "--verify",
        "--end-of-options",
        &format!("{reference}^{{commit}}"),
    ])
}

fn tasks(root: &Path, suites: &[String]) -> Result<Vec<Task>> {
    let mut tasks = Vec::new();
    let mut missing = Vec::new();
    for name in suites {
        let suite = root.join(name);
        for (task_name, directory) in super::suite::directories(&suite.join("tasks"))? {
            let manifest = format::Task::load(&directory)?;
            if manifest.state == format::State::Proposed {
                continue;
            }
            let Some(inputs) = manifest.trial.as_ref() else {
                missing.push(format!("{name}/{task_name}"));
                continue;
            };
            crate::issue::IssueUrl::parse(&inputs.issue_url)?;
            ensure!(
                !inputs.base.is_empty() && !inputs.branch.is_empty() && !inputs.pr_url.is_empty(),
                "Trial inputs must be nonempty"
            );
            tasks.push(Task {
                suite: name.clone(),
                name: task_name,
                directory,
                manifest,
            });
        }
    }
    ensure!(
        missing.is_empty(),
        "Eval tasks need a [trial] table: {}; see docs/eval-tasks.md",
        missing.join(", ")
    );
    ensure!(
        !tasks.is_empty(),
        "selected suites have no approved Eval tasks"
    );
    Ok(tasks)
}