Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

requirements.authoring.cache_warmup

Requirements index · View definition

evidence Valid

Requirement

So that concurrent assessments find their system prompt cached under cite requirements.authoring.cache_checkpoints, a batch MUST start one assessment of each kind it contains before any other of that kind, and start the others only once that assessment’s first provider request has finished, whether or not it succeeded.

Rationale

I found no gaps. The two obligations are implemented and tested.

Obligations

  1. Start one assessment of each kind before any other of that kind.
  2. Start the others of a kind only once that assessment’s first provider request has finished, whether or not it succeeded.

Implementation

  • src/authoring/batch.rs#fn[run_batch] carries the {impl}. It tags each subject with its kind through assessment_kind. It then picks the next subject to launch with CacheWarmup::next.
  • src/authoring/batch.rs#impl[CacheWarmup]/fn[next] returns the first queued subject whose kind is not currently warming. If its kind has not yet warmed, that subject becomes the kind’s warming assessment and its kind is marked as warming. Every other subject of that kind is skipped until the kind is released. This covers obligation 1.
  • A warming assessment gets a first_request_finished callback. prepare_assessment in src/authoring/mod.rs registers it on the usage log with on_first_request.
  • src/authoring/usage.rs#impl[UsageLog]/fn[end_request] fires the callback once. It does so on both the completed and failed branches, because the call does not depend on usage or failure. This covers “whether or not it succeeded”.
  • src/authoring/adaptive.rs#fn[attempt] calls handoff_first_request, so the callback survives follow-up logs.
  • run_batch receives the callback’s message on a channel. It calls warmup.warmed(kind), which releases the kind. It also drains the channel after a task joins. If an assessment finishes without making a request, warmup.finished(kind) frees the slot so another of that kind warms instead.

Tests

  • src/authoring/batch.rs#mod[tests]/fn[each_kind_starts_one_assessment_until_its_first_request_finishes] tests the scheduler directly. It checks that one of each kind starts, the rest wait, a finish without a request lets the next one warm, and warmed releases the others.
  • src/authoring/usage.rs#mod[tests]/fn[the_first_finished_request_is_reported_once_whatever_its_outcome] checks the callback fires once after the first request ends, including when the request failed.
  • tests/authoring_batch.rs#fn[a_batch_warms_each_kind_with_one_assessment_before_starting_the_others] is an end-to-end test against a mock server. assert_warmed_first checks that no other request of a kind arrives before the first request has been answered. The test also checks that the other assessments of a kind then run concurrently.
  • tests/authoring_batch.rs#fn[a_failed_first_request_still_releases_its_kind] throttles the first request. It checks that the others start without waiting for the retry.

I found no unspecified behavior in the implementation.

Inputs

Implementation

Input 3: outline src/authoring/batch.rs fn[run_batch]
/// Runs a batch over every subject, or, with `sites_of`, over the site
/// reviews of one distributed requirement.
// {impl}`requirements.authoring.github_reads`
// {impl}`requirements.authoring.policy`
// {impl}`requirements.authoring.cache_warmup`
// {impl}`requirements.authoring.read_denial.mandatory`
async fn run_batch(
    root: &Path,
    selection: Option<&str>,
    options: AuthoringOptions,
    sites_of: Option<&str>,
) -> io::Result<BatchOutcome> {
    let root = fs::canonicalize(root)?;
    let mut progress = BatchProgress::new(options.verbose);
    let mut inspection =
        inspect_repository_with_progress(&root, |update| progress.inspect(update))?;
    if !inspection.discovery_errors.is_empty() {
        return Err(io::Error::other(inspection.discovery_errors.join("\n")));
    }
    // A FIXME record whose acknowledging issue closed is stale.
    // {impl}`requirements.authoring.github_reads`
    crate::github::add_issue_findings(
        &mut inspection,
        &crate::github::GithubIssues::from_env(&root),
    );
    if let Some(requirement) = sites_of
        && !inspection.sites.contains_key(requirement)
    {
        return Err(io::Error::other(format!(
            "sites:{requirement}: no distributed requirement named {requirement}"
        )));
    }
    // Orphaned reviews are deleted before, and independently of, any model
    // configuration.
    let deleted = if sites_of.is_none() {
        delete_orphaned_reviews(&root, &inspection)?
    } else {
        Vec::new()
    };
    for path in &deleted {
        progress.println(&format!("Deleted orphaned review {path}"));
    }
    let (subjects, unchanged) =
        select_subjects(&root, &inspection, sites_of, options.force, &mut |update| {
            progress.inspect(update)
        });
    let mut outcome = BatchOutcome {
        completed: Vec::new(),
        failures: Vec::new(),
        unchanged,
        deleted,
        policy: None,
        cancelled: false,
    };
    // With nothing to assess, no configuration or credentials are resolved.
    // {impl}`requirements.authoring.configuration`
    if subjects.is_empty() {
        return Ok(outcome);
    }
    let config = config::resolve_authoring(&root, selection)?;
    let concurrency = config.effective_concurrency();
    let policy = config.effective_policy(options.policy);
    outcome.policy = Some(policy);
    progress.println(&format!(
        "Authoring {} assessments under the {policy} policy with concurrency {concurrency}; {unchanged} current records skipped",
        subjects.len()
    ));
    progress.start(subjects.len());
    let mut subjects = subjects
        .into_iter()
        .map(|subject| (assessment_kind(&inspection, &subject), subject))
        .collect::<Vec<_>>();
    let mut warmup = CacheWarmup::default();
    let (warmed, mut warmed_kinds) = tokio::sync::mpsc::unbounded_channel();
    let mut tasks = JoinSet::new();
    let (cancel, cancellation) = watch::channel(None::<&'static str>);
    // The batch listens for interruption itself, so a signal arriving while no
    // assessment is waiting (between tasks, or while a record is written)
    // still stops the batch. Poll once now to register the listener before
    // any assessment starts; registered signals are kept until polled again.
    let interrupt = tokio::signal::ctrl_c();
    tokio::pin!(interrupt);
    let mut listening = true;
    observe_interrupt(interrupt.as_mut(), &mut listening, &cancel).await;
    loop {
        // A signal received while the batch was busy stops further launches.
        observe_interrupt(interrupt.as_mut(), &mut listening, &cancel).await;
        while cancellation.borrow().is_none() && tasks.len() < concurrency {
            let Some((kind, subject, warms)) = warmup.next(&mut subjects) else {
                break;
            };
            let root = root.clone();
            let config = config.clone();
            let cancellation = cancellation.clone();
            let cancel = cancel.clone();
            let first_request_finished = warms.then(|| {
                let warmed = warmed.clone();
                Box::new(move || {
                    let _ = warmed.send(kind);
                }) as Box<dyn FnOnce() + Send>
            });
            tasks.spawn(async move {
                let result = prepare_assessment(
                    &root,
                    &subject,
                    &config,
                    policy,
                    cancellation,
                    first_request_finished,
                )
                .await;
                if let Err(error) = &result {
                    cancel_on_error(&cancel, error);
                }
                (kind, subject.label(), result)
            });
        }
        progress.refresh(tasks.len(), subjects.len());
        let joined = tokio::select! {
            biased;
            signal = &mut interrupt, if listening => {
                listening = false;
                if signal.is_ok() {
                    stop(&cancel);
                }
                continue;
            }
            Some(kind) = warmed_kinds.recv() => {
                warmup.warmed(kind);
                continue;
            }
            joined = tasks.join_next() => joined,
        };
        let Some(result) = joined else {
            break;
        };
        // A warming assessment signals before it finishes.
        while let Ok(kind) = warmed_kinds.try_recv() {
            warmup.warmed(kind);
        }
        let (label, result) = match result {
            Ok((kind, label, result)) => {
                warmup.finished(kind);
                (label, result)
            }
            Err(error) => {
                progress.failed("authoring task", &error);
                outcome
                    .failures
                    .push(("authoring task".into(), error.to_string()));
                continue;
            }
        };
        // ...and discards a judgment not yet written when it arrived.
        observe_interrupt(interrupt.as_mut(), &mut listening, &cancel).await;
        let result = match result {
            Ok(pending) => match stage_record(&root, &pending) {
                Ok((file, path)) => {
                    // Preparation may involve slow filesystem writes. Observe
                    // cancellation again before committing the atomic replacement.
                    tokio::task::yield_now().await;
                    observe_interrupt(interrupt.as_mut(), &mut listening, &cancel).await;
                    match persist_record(file, path, &cancellation) {
                        Ok(path) => pending.persisted(path),
                        Err(error) => Err(pending.failed(error)),
                    }
                }
                Err(error) => Err(pending.failed(error)),
            },
            Err(error) => Err(error),
        };
        match result {
            Ok(assessment) => {
                progress.completed(&assessment);
                outcome.completed.push(assessment);
            }
            Err(error) => {
                cancel_on_error(&cancel, &error);
                progress.failed(&label, &error);
                outcome.failures.push((label, error.to_string()));
            }
        }
    }
    if let Some(reason) = *cancellation.borrow() {
        let remaining = subjects.len();
        if remaining > 0 {
            let message = format!("{reason}; {remaining} assessments not started");
            progress.println(&format!("batch: {message}"));
            outcome.failures.push(("batch".into(), message));
        }
    }
    outcome.cancelled = cancellation.borrow().is_some();
    progress.finish(outcome.cancelled, subjects.len());
    Ok(outcome)
}

Tests

Input 4: outline src/authoring/batch.rs mod[tests]/fn[each_kind_starts_one_assessment_until_its_first_request_finishes]
  • File: src/authoring/batch.rs
  • Selector: mod[tests]/fn[each_kind_starts_one_assessment_until_its_first_request_finishes]
  • Kind: fn
  • src/authoring/batch.rs:647–692
    // {test}`requirements.authoring.cache_warmup`
    #[test]
    fn each_kind_starts_one_assessment_until_its_first_request_finishes() {
        let subject = |name: &str| AuthoringSubject::Definition(name.into());
        let mut queue = vec![
            ("requirement", subject("a")),
            ("requirement", subject("b")),
            ("example", subject("c")),
            ("requirement", subject("d")),
            ("example", subject("e")),
        ];
        let mut warmup = CacheWarmup::default();
        let label = |next: Option<(&str, AuthoringSubject, bool)>| {
            next.map(|(kind, subject, warms)| (kind.to_owned(), subject.label(), warms))
        };
        let started =
            |kind: &str, name: &str, warms| Some((kind.to_owned(), name.to_owned(), warms));
        // One of each kind starts; the rest wait for their kind.
        assert_eq!(
            label(warmup.next(&mut queue)),
            started("requirement", "a", true)
        );
        assert_eq!(
            label(warmup.next(&mut queue)),
            started("example", "c", true)
        );
        assert_eq!(label(warmup.next(&mut queue)), None);
        // An assessment that finished without a request warmed nothing, so
        // the next of its kind warms it instead.
        warmup.finished("example");
        assert_eq!(
            label(warmup.next(&mut queue)),
            started("example", "e", true)
        );
        // Once a kind's first request finishes, the others of it start.
        warmup.warmed("requirement");
        assert_eq!(
            label(warmup.next(&mut queue)),
            started("requirement", "b", false)
        );
        assert_eq!(
            label(warmup.next(&mut queue)),
            started("requirement", "d", false)
        );
        assert!(queue.is_empty());
    }
Input 5: outline src/authoring/usage.rs mod[tests]/fn[the_first_finished_request_is_reported_once_whatever_its_outcome]
  • File: src/authoring/usage.rs
  • Selector: mod[tests]/fn[the_first_finished_request_is_reported_once_whatever_its_outcome]
  • Kind: fn
  • src/authoring/usage.rs:434–453
    // {test}`requirements.authoring.cache_warmup`
    #[test]
    fn the_first_finished_request_is_reported_once_whatever_its_outcome() {
        let state = tempfile::tempdir().unwrap();
        let mut log =
            UsageLog::start(state.path(), Path::new("/project"), "requirements.case").unwrap();
        let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let counted = calls.clone();
        log.on_first_request(move || {
            counted.fetch_add(1, Ordering::Relaxed);
        });
        let first = log.begin_request().unwrap();
        assert_eq!(calls.load(Ordering::Relaxed), 0);
        log.end_request(first, 1, None, Some((None, None))).unwrap();
        assert_eq!(calls.load(Ordering::Relaxed), 1);
        let second = log.begin_request().unwrap();
        log.end_request(second, 1, Some(&Usage::new()), None)
            .unwrap();
        assert_eq!(calls.load(Ordering::Relaxed), 1);
    }
Input 6: outline tests/authoring_batch.rs fn[a_batch_warms_each_kind_with_one_assessment_before_starting_the_others]
// {test}`requirements.authoring.cache_warmup`
#[test]
fn a_batch_warms_each_kind_with_one_assessment_before_starting_the_others() {
    mock_server_waits_for_remaining_request_headers();
    let server = Server::start_with(false, Behavior::WarmupBarrier);
    let fixture = Fixture::new(&server.endpoint, Some(8));
    let output = fixture.run(&["author", "--all"]);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let kinds = assert_warmed_first(&server);
    assert_eq!(kinds[0].len(), 4, "{:?}", kinds[0]);
    assert_eq!(kinds[1].len(), 2, "{:?}", kinds[1]);
    // The others of a kind then run together.
    let state = server.requests.0.lock().unwrap();
    assert!(state.peak >= 3, "peak {}", state.peak);
}
Input 7: outline tests/authoring_batch.rs fn[a_failed_first_request_still_releases_its_kind]
// {test}`requirements.authoring.cache_warmup`
#[test]
fn a_failed_first_request_still_releases_its_kind() {
    let server = Server::start_with(
        false,
        Behavior::ThrottledOnce {
            subject: "requirement requirements.alpha",
        },
    );
    let fixture = Fixture::new(&server.endpoint, Some(8));
    let output = fixture.run(&["author", "--all"]);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let kinds = assert_warmed_first(&server);
    let requirements = &kinds[0];
    assert_eq!(requirements[0].0, "requirement requirements.alpha");
    // The other requirements start after the throttled request, without
    // waiting for the retry, which backs off for at least half a second.
    let retry = requirements[1..]
        .iter()
        .find(|(subject, ..)| subject == "requirement requirements.alpha")
        .expect("the throttled request is retried");
    let others = requirements
        .iter()
        .filter(|(subject, ..)| subject != "requirement requirements.alpha")
        .collect::<Vec<_>>();
    assert_eq!(others.len(), 3);
    assert!(others.iter().all(|(_, arrived, _)| *arrived < retry.1));
}

Referenced definitions

Input 2: requirements selection requirements.authoring.cache_checkpoints
:::{req} cache_checkpoints
For backends that accept explicit cache checkpoints, when the backend and model
support prompt caching, every provider request MUST place one cache checkpoint
after the system prompt of {cite}`requirements.authoring.prompt_parts` and
another at the end of its last message, so each request reuses the tool
definitions and system prompt that earlier assessments of its kind sent, and
the conversation its own earlier requests sent. Cache checkpoints MUST NOT
change the content of a request.

For OpenAI, which caches matching prompt prefixes automatically, the harness
MUST keep the system prompt and tool definitions unchanged across requests in
one conversation and replay prior conversation content in its original order.
It MUST NOT insert checkpoint blocks.
:::

Other sources

Input 1: requirements selection requirements.authoring.cache_warmup
:::{req} cache_warmup
So that concurrent assessments find their system prompt cached under
{cite}`requirements.authoring.cache_checkpoints`, a batch MUST start one
assessment of each kind it contains before any other of that kind, and start the
others only once that assessment's first provider request has finished, whether
or not it succeeded.
:::
Input 8: outline src/authoring/batch.rs impl[CacheWarmup]
impl CacheWarmup {
    /// Takes the first queued subject that may start now, and whether it
    /// warms its kind: a subject of a warm kind, or the first of a kind
    /// with none warming.
    fn next(
        &mut self,
        queue: &mut Vec<(&'static str, AuthoringSubject)>,
    ) -> Option<(&'static str, AuthoringSubject, bool)> {
        let index = queue
            .iter()
            .position(|(kind, _)| !self.warming.contains(kind))?;
        let (kind, subject) = queue.remove(index);
        let warms = !self.warm.contains(kind);
        if warms {
            self.warming.insert(kind);
        }
        Some((kind, subject, warms))
    }

    /// Records that a kind's first provider request has finished.
    fn warmed(&mut self, kind: &'static str) {
        self.warming.remove(kind);
        self.warm.insert(kind);
    }

    /// Records that an assessment of a kind finished. One that finished
    /// without a provider request warmed nothing, so another of its kind
    /// takes its place.
    fn finished(&mut self, kind: &'static str) {
        self.warming.remove(kind);
    }
}
Input 9: outline src/authoring/batch.rs struct[CacheWarmup]
/// Which assessment kinds have warmed their prompt cache: a kind's first
/// assessment starts alone, and the others of its kind wait until its first
/// provider request has finished, while other kinds proceed.
#[derive(Default)]
struct CacheWarmup {
    /// Kinds whose first assessment is running but has not yet finished its
    /// first provider request.
    warming: std::collections::BTreeSet<&'static str>,
    /// Kinds whose cache an earlier provider request has written.
    warm: std::collections::BTreeSet<&'static str>,
}
Input 10: outline src/authoring/usage.rs impl[UsageLog]/fn[end_request]
    pub(super) fn end_request(
        &mut self,
        index: usize,
        elapsed: u128,
        usage: Option<&Usage>,
        failure: Option<(Option<u16>, Option<String>)>,
    ) -> io::Result<()> {
        let tokens = usage.map(TokenCounts::from_usage).unwrap_or_default();
        if usage.is_some() {
            for input in &mut self.record.inputs {
                if input.sent_in_request.is_none() && input.submitted_in_request.is_some() {
                    input.sent_in_request = Some(index);
                }
            }
        }
        self.record.requests[index] = RequestUsage {
            outcome: if usage.is_some() {
                "completed"
            } else {
                "failed"
            }
            .into(),
            elapsed_ms: elapsed,
            tokens,
            failure: failure.map(|(http_status, error_code)| RequestFailure {
                http_status,
                error_code,
                retried: false,
            }),
        };
        self.record.tokens = TokenCounts::sum(&self.record.requests);
        self.active_request = None;
        self.record.elapsed_ms = self.started.elapsed().as_millis();
        if let Some(finished) = self.first_request_finished.take() {
            finished();
        }
        self.save()
    }