use std::{
alloc::{GlobalAlloc, Layout, System},
collections::{BTreeMap, BTreeSet},
fs,
path::{Path, PathBuf},
sync::{
Arc, Mutex,
atomic::{AtomicBool, AtomicU64, Ordering::Relaxed},
},
time::Duration,
};
use tokio_util::sync::CancellationToken;
use crate::{
config,
human::{self, Submission},
monitor::live,
project::{self, VerifyOptions, selection::Selection, verify::reserve},
review::ArtifactDeclarations,
runs::Origin,
runtime::Verdict,
store::{self, Receipts},
types::{ArtifactName, RunId, Timestamp},
};
const WORKSPACE_SIZES: [usize; 4] = [1_000, 2_000, 4_000, 8_000];
const ACTION_COUNTS: [usize; 4] = [1, 2, 4, 8];
static COUNTING: AtomicBool = AtomicBool::new(false);
static DECLARATIONS: AtomicU64 = AtomicU64::new(0);
static UNRELATED: AtomicU64 = AtomicU64::new(0);
static DECLARATION_SCOPE: Mutex<Option<BTreeSet<PathBuf>>> = Mutex::new(None);
static WORKSPACES: AtomicU64 = AtomicU64::new(0);
static CONTENT: AtomicU64 = AtomicU64::new(0);
static SQL_STEPS: AtomicU64 = AtomicU64::new(0);
static FILE_READS: Mutex<Option<BTreeMap<PathBuf, u64>>> = Mutex::new(None);
static ALLOCATED: AtomicU64 = AtomicU64::new(0);
static LIVE: AtomicU64 = AtomicU64::new(0);
fn count(counter: &AtomicU64, amount: u64) {
if COUNTING.load(Relaxed) {
counter.fetch_add(amount, Relaxed);
}
}
pub(crate) fn declaration_read(path: &Path) {
if COUNTING.load(Relaxed) {
DECLARATIONS.fetch_add(1, Relaxed);
if DECLARATION_SCOPE
.lock()
.unwrap()
.as_ref()
.is_some_and(|files| !files.contains(path))
{
UNRELATED.fetch_add(1, Relaxed);
}
}
}
pub(crate) fn workspace_read() {
count(&WORKSPACES, 1);
}
pub(crate) fn sql_steps(steps: i32) {
count(&SQL_STEPS, u64::try_from(steps).unwrap_or_default());
}
pub(crate) fn content_read(path: &Path) {
if COUNTING.load(Relaxed) {
CONTENT.fetch_add(1, Relaxed);
if let Some(reads) = FILE_READS.lock().unwrap().as_mut() {
*reads.entry(path.to_owned()).or_default() += 1;
}
}
}
struct Allocations;
#[global_allocator]
static ALLOCATOR: Allocations = Allocations;
unsafe impl GlobalAlloc for Allocations {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let ptr = unsafe { System.alloc(layout) };
if !ptr.is_null() {
let size = layout.size() as u64;
count(&ALLOCATED, size);
LIVE.fetch_add(size, Relaxed);
}
ptr
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
LIVE.fetch_sub(layout.size() as u64, Relaxed);
unsafe { System.dealloc(ptr, layout) }
}
}
struct Count {
checks_scope: bool,
}
impl Count {
fn start() -> Self {
Self::with_scope(None)
}
fn with_scope(files: Option<BTreeSet<PathBuf>>) -> Self {
assert!(!COUNTING.load(Relaxed));
let checks_scope = files.is_some();
*DECLARATION_SCOPE.lock().unwrap() = files;
for counter in [
&DECLARATIONS,
&UNRELATED,
&WORKSPACES,
&CONTENT,
&SQL_STEPS,
&ALLOCATED,
] {
counter.store(0, Relaxed);
}
COUNTING.store(true, Relaxed);
Self { checks_scope }
}
fn finish(self) -> Sample {
let checks_scope = self.checks_scope;
drop(self);
let mut measures = BTreeMap::from([
("declaration-reads", DECLARATIONS.load(Relaxed) as f64),
("workspace-reads", WORKSPACES.load(Relaxed) as f64),
("declared-workspace-reads", WORKSPACES.load(Relaxed) as f64),
("content-reads", CONTENT.load(Relaxed) as f64),
("sql-steps", SQL_STEPS.load(Relaxed) as f64),
("allocated-bytes", ALLOCATED.load(Relaxed) as f64),
]);
if checks_scope {
measures.insert(
"unrelated-declaration-reads",
UNRELATED.load(Relaxed) as f64,
);
}
Sample(measures)
}
}
impl Drop for Count {
fn drop(&mut self) {
COUNTING.store(false, Relaxed);
if self.checks_scope {
*DECLARATION_SCOPE.lock().unwrap() = None;
}
}
}
struct FileReads;
impl FileReads {
fn start(expected: impl IntoIterator<Item = PathBuf>) -> Self {
let mut reads = FILE_READS.lock().unwrap();
assert!(reads.is_none());
*reads = Some(expected.into_iter().map(|path| (path, 0)).collect());
Self
}
fn max(self) -> u64 {
let reads = FILE_READS.lock().unwrap().take().unwrap();
for (path, reads) in &reads {
assert_ne!(*reads, 0, "full-status skipped {path:?}");
}
reads.into_values().max().unwrap()
}
}
impl Drop for FileReads {
fn drop(&mut self) {
*FILE_READS.lock().unwrap() = None;
}
}
struct Sample(BTreeMap<&'static str, f64>);
type Series = BTreeMap<(&'static str, &'static str), Vec<(usize, Sample)>>;
fn record(series: &mut Series, op: &'static str, axis: &'static str, size: usize, sample: Sample) {
series.entry((op, axis)).or_default().push((size, sample));
}
struct Fixture {
_root: tempfile::TempDir,
repo: PathBuf,
state: PathBuf,
}
impl Fixture {
fn input_name(n: usize) -> String {
format!("file-{n}.txt")
}
fn new(workspace: usize, scope: usize, files: usize) -> Self {
let root = tempfile::tempdir().unwrap();
let repo = root.path().join("repo");
let definitions = repo.join(".artifactize");
let inputs = repo.join("inputs");
fs::create_dir_all(&definitions).unwrap();
fs::create_dir(&inputs).unwrap();
for n in 0..files {
fs::write(inputs.join(Self::input_name(n)), format!("content {n}\n")).unwrap();
}
fs::write(
definitions.join("tools.artf"),
r#"tool inspect = { human read = builtin(op = "read", args = ["file-0.txt"]) }"#,
)
.unwrap();
fs::write(
definitions.join("macros.artf"),
r#"
artf! reviewed() : inspect = {
path = "inputs/"
eval approve : human = {
title = "Approve the fixture"
instruction = "Approve @{artf self}."
}
}
"#,
)
.unwrap();
fs::write(
definitions.join("selected.artf"),
"artf selected = reviewed!()",
)
.unwrap();
for n in 1..workspace {
let text = if n <= scope {
format!(
"artf member-{n} : files = {{ path = \"inputs/\" eval review : human = {{ title = \"Review the fixture\" instruction = \"Review @{{artf selected}}.\" }} }}"
)
} else {
format!("artf member-{n} = {{ path = \"inputs/\" basis = true }}")
};
fs::write(definitions.join(format!("member-{n}.artf")), text).unwrap();
}
let state = root.path().join("state");
Self {
_root: root,
repo,
state,
}
}
fn selection(scope: usize) -> Selection {
Selection::Artifacts {
artifact_ids: std::iter::once("selected".parse().unwrap())
.chain((1..=scope).map(|n| format!("member-{n}").parse().unwrap()))
.collect(),
}
}
fn declaration_files(&self, scope: usize) -> BTreeSet<PathBuf> {
let definitions = crate::platform::canonicalize(&self.repo)
.unwrap()
.join(".artifactize");
["selected.artf", "macros.artf", "tools.artf"]
.into_iter()
.map(|file| definitions.join(file))
.chain((1..=scope).map(|n| definitions.join(format!("member-{n}.artf"))))
.collect()
}
async fn reserve(&self, selection: &Selection) -> RunId {
self.reserve_in(&self.state, selection, &VerifyOptions::default())
.await
}
async fn admit_plan(&self, selection: &Selection) -> RunId {
let options = VerifyOptions {
reuse_only: [config::ProfileKind::Human].into(),
..VerifyOptions::default()
};
self.reserve_in(&self.state, selection, &options).await
}
async fn reserve_in(
&self,
state: &Path,
selection: &Selection,
options: &VerifyOptions,
) -> RunId {
reserve(
&self.repo,
Some(state),
selection,
options,
None,
None,
&Origin::Cli,
)
.await
.unwrap()
.0
}
async fn status(&self, selection: &Selection) -> project::StatusView {
project::status(
&self.repo,
Some(&self.state),
selection,
&VerifyOptions {
force: true,
..VerifyOptions::default()
},
CancellationToken::new(),
)
.await
.unwrap()
}
async fn forecast(
&self,
selection: &Selection,
sites: Arc<config::SiteIndex>,
) -> live::Current {
live::scan_scope(
&self.repo,
&self.state,
selection,
Some(sites),
CancellationToken::new(),
|_| {},
)
.await
.unwrap()
}
async fn finished_runs(&self, state: &Path, selection: &Selection, count: usize) -> Vec<RunId> {
let receipts = Receipts::open(state, &self.repo).await.unwrap();
let mut ids = Vec::with_capacity(count);
let mut last = time::OffsetDateTime::UNIX_EPOCH;
for _ in 0..count {
let id = self
.reserve_in(state, selection, &VerifyOptions::default())
.await;
let view = store::read_run(state, id.as_str()).await.unwrap();
let mut run = view.run;
let [request] = view.requests.as_slice() else {
panic!("one request per finished Run");
};
let mut request = request.as_ref().clone();
last = last.max(run.created_at.time()) + time::Duration::NANOSECOND;
let at = Timestamp::new(last).unwrap();
run.state = store::RunState::Green { at };
request.state = store::RequestState::completed(
store::ExecutionResult::Human {
verdict: Verdict::Green,
issues: vec![],
},
at,
);
receipts.finish(&run, &[request]).await.unwrap();
ids.push(id);
}
receipts.close().await.unwrap();
ids
}
async fn human(&self, series: &mut Series, workspace: usize) -> crate::types::RunId {
let run = self.reserve(&Self::selection(0)).await;
let view = store::read_run(&self.state, run.as_str()).await.unwrap();
let id = view.requests[0].id.clone();
let receipts = Receipts::open(&self.state, &self.repo).await.unwrap();
let cancellation = CancellationToken::new();
let (worker, actions) = tokio::join!(
project::verify::execute(view.run, &receipts, cancellation.clone()),
async {
let result = tokio::time::timeout(Duration::from_secs(60), async {
loop {
if let Ok(request) = receipts.waiting_human(&id).await {
break request;
}
tokio::task::yield_now().await;
}
})
.await;
let Ok(request) = result else {
cancellation.cancel();
return Err("Fixture Human request did not become answerable".to_owned());
};
let reviewer = "perf-fixture".parse().unwrap();
let tool = "inspect_read_selected".parse().unwrap();
let answer = Submission::new(Verdict::Green, vec![]).unwrap();
let counter = Count::start();
human::preview_tool_commands(Arc::new(request)).await?;
record(series, "human-open", "W", workspace, counter.finish());
let counter = Count::start();
human::claim(&receipts, &id, &reviewer).await?;
record(series, "human-claim", "W", workspace, counter.finish());
let counter = Count::start();
call_tool(&receipts, &id, &reviewer, &tool).await?;
record(series, "human-tool", "W", workspace, counter.finish());
let counter = Count::start();
human::submit(&receipts, &id, &reviewer, &answer, CancellationToken::new()).await?;
record(series, "human-submit", "W", workspace, counter.finish());
Ok(())
},
);
worker.unwrap();
actions.unwrap();
receipts.close().await.unwrap();
run
}
}
async fn call_tool(
receipts: &Receipts,
id: &crate::types::RequestId,
reviewer: &crate::types::ReviewerId,
tool: &config::ToolName,
) -> Result<(), String> {
let result = human::run_human_tool(
receipts,
id,
reviewer,
tool,
CancellationToken::new(),
crate::review::log::Run::unwatched(),
)
.await?;
assert!(!result.is_error(), "{:?}", result.content());
Ok(())
}
async fn cold_requests(series: &mut Series) {
let selection = Fixture::selection(1);
for workspace in WORKSPACE_SIZES {
let status = Fixture::new(workspace, 1, 4);
let count = Count::start();
status.status(&selection).await;
record(series, "cold-status", "W", workspace, count.finish());
let admission = Fixture::new(workspace, 1, 4);
let count = Count::start();
admission.reserve(&selection).await;
record(series, "cold-admission", "W", workspace, count.finish());
}
}
async fn config_and_scope(series: &mut Series) {
for workspace in WORKSPACE_SIZES {
let fixture = Fixture::new(workspace, 1, 4);
let count = Count::start();
let snapshot = config::read_workspace_config(&fixture.repo).unwrap();
let sample = count.finish();
assert_eq!(snapshot.artifacts.len(), workspace);
drop(snapshot);
record(series, "config-check", "W", workspace, sample);
let count = Count::start();
let mut graph = crate::monitor::live::outline(&fixture.repo).unwrap();
record(series, "graph-open", "W", workspace, count.finish());
let selected = "selected".parse().unwrap();
let count = Count::with_scope(Some(fixture.declaration_files(0)));
ArtifactDeclarations::read_indexed(&fixture.repo, &selected, &graph.sites)
.unwrap()
.tools()
.unwrap();
record(series, "detail-tools", "W", workspace, count.finish());
let count = Count::with_scope(Some(fixture.declaration_files(0)));
let expansion = config::expand::indexed(&fixture.repo, &graph.sites, &selected).unwrap();
assert_eq!(expansion.macro_name.as_deref(), Some("reviewed!"));
record(series, "detail-source", "W", workspace, count.finish());
scoped(series, &fixture, graph.sites.clone(), "W", workspace, 1).await;
let run = fixture.human(series, workspace).await;
let count = Count::start();
let place = crate::monitor::live::Place::Folder(
crate::platform::canonicalize(&fixture.repo).unwrap(),
);
apply_finished_run(&fixture, &place, &mut graph, &run).await;
let mut sample = count.finish();
sample
.0
.insert("workspace-scans", sample.0["workspace-reads"]);
record(series, "graph-run-finished", "W", workspace, sample);
}
const SCOPES: [usize; 4] = [8, 16, 32, 64];
for scope in SCOPES {
let fixture = Fixture::new(1_000, SCOPES[SCOPES.len() - 1], 4);
let sites = Arc::new(config::SiteIndex::read(&fixture.repo).unwrap());
let size = fixture.declaration_files(scope).len();
scoped(series, &fixture, sites, "S", size, scope).await;
}
}
async fn scoped(
series: &mut Series,
fixture: &Fixture,
sites: Arc<config::SiteIndex>,
axis: &'static str,
size: usize,
scope: usize,
) {
let selection = Fixture::selection(scope);
let count = Count::with_scope(Some(fixture.declaration_files(scope)));
fixture.forecast(&selection, sites).await;
record(series, "scoped-status", axis, size, count.finish());
let run = fixture.admit_plan(&selection).await;
let view = store::read_run(&fixture.state, run.as_str()).await.unwrap();
let receipts = Receipts::open(&fixture.state, &fixture.repo).await.unwrap();
let count = Count::with_scope(Some(fixture.declaration_files(scope)));
project::verify::execute(view.run, &receipts, CancellationToken::new())
.await
.unwrap();
record(series, "scoped-plan", axis, size, count.finish());
receipts.close().await.unwrap();
}
async fn content(series: &mut Series) {
for files in [32, 64, 128, 256] {
let fixture = Fixture::new(8, 4, files);
let selection = Fixture::selection(2);
let sites = Arc::new(config::SiteIndex::read(&fixture.repo).unwrap());
let count = Count::start();
fixture.forecast(&selection, sites).await;
record(series, "scoped-status", "F", files, count.finish());
let inputs = crate::platform::canonicalize(&fixture.repo)
.unwrap()
.join("inputs");
let file_reads = FileReads::start((0..files).map(|n| inputs.join(Fixture::input_name(n))));
let count = Count::start();
fixture.status(&Selection::All).await;
let mut sample = count.finish();
sample.0.insert("reads-per-file", file_reads.max() as f64);
record(series, "full-status", "F", files, sample);
}
}
async fn seed_run(receipts: &Receipts, state: &Path, view: &store::RunView) -> store::Run {
let mut run = view.run.clone();
run.state_dir = state.to_owned();
let requests: Vec<_> = view
.requests
.iter()
.map(|row| row.as_ref().clone())
.collect();
receipts.create_run(&run, &requests).await.unwrap();
run
}
fn stored_bytes(state: &Path, run: &RunId) -> i64 {
let db = rusqlite::Connection::open_with_flags(
state.join(store::DATABASE),
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
)
.unwrap();
db.query_row(
"WITH body(data) AS (SELECT data FROM definition_records
WHERE hash = (SELECT body FROM run_definitions WHERE run_id = ?1)),
named(hash) AS (
SELECT a.value ->> 1 FROM body, json_each(body.data, '$.artifacts') a
UNION SELECT e.value FROM body, json_each(body.data, '$.evals') e
UNION SELECT e.value FROM body, json_each(body.data, '$.relations') e)
SELECT length(CAST(r.data AS BLOB)) + length(CAST(d.data AS BLOB)) +
COALESCE((SELECT sum(length(CAST(q.data AS BLOB))) FROM requests q WHERE q.run_id = r.id), 0) +
COALESCE((SELECT sum(length(CAST(data AS BLOB))) FROM body), 0) +
COALESCE((SELECT sum(length(CAST(x.data AS BLOB))) FROM definition_records x JOIN named n ON n.hash = x.hash), 0)
FROM runs r JOIN run_definitions d ON d.run_id = r.id WHERE r.id = ?1",
[run],
|row| row.get(0),
)
.unwrap()
}
async fn run_history(series: &mut Series) {
const HISTORY_SIZES: [usize; 4] = [2, 4, 8, 16];
let fixture = Fixture::new(8, 4, 4);
fs::write(fixture.repo.join("history.txt"), "Unrelated content\n").unwrap();
fs::write(
fixture.repo.join(".artifactize/history.artf"),
r#"artf history : files = {
path = "history.txt"
eval approve : human = { title = "Approve history" instruction = "Approve history." }
}"#,
)
.unwrap();
let history_seed = fixture.state.with_file_name("history-seed");
let unrelated = Selection::Artifact {
artifact_id: "history".parse().unwrap(),
};
let history_ids = fixture
.finished_runs(
&history_seed,
&unrelated,
HISTORY_SIZES.into_iter().max().unwrap(),
)
.await;
let mut history = Vec::with_capacity(history_ids.len());
for id in history_ids {
history.push(store::read_run(&history_seed, id.as_str()).await.unwrap());
}
let selected = fixture.admit_plan(&Fixture::selection(1)).await;
let admitted = store::read_run(&fixture.state, selected.as_str())
.await
.unwrap();
for previous in HISTORY_SIZES {
let state = fixture
.state
.with_file_name(format!("history-{previous:02}"));
let receipts = Receipts::open(&state, &fixture.repo).await.unwrap();
for view in &history[..previous] {
seed_run(&receipts, &state, view).await;
}
let run = seed_run(&receipts, &state, &admitted).await;
project::verify::execute(run, &receipts, CancellationToken::new())
.await
.unwrap();
receipts.close().await.unwrap();
let bytes = stored_bytes(&state, &selected) as f64;
record(
series,
"scoped-plan",
"R",
previous,
Sample(BTreeMap::from([("stored-bytes", bytes)])),
);
}
}
fn definition_bytes(state: &Path) -> i64 {
let db = rusqlite::Connection::open_with_flags(
state.join(store::DATABASE),
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
)
.unwrap();
db.query_row(
"SELECT (SELECT coalesce(sum(length(CAST(data AS BLOB))),0) FROM run_definitions)
+ (SELECT coalesce(sum(length(CAST(data AS BLOB))),0) FROM definition_records)",
[],
|row| row.get(0),
)
.unwrap()
}
async fn repeat_admission(series: &mut Series) {
for workspace in WORKSPACE_SIZES {
const PARTS: usize = 50;
let fixture = Fixture::new(workspace - 1, 0, 1);
let nodes: Vec<_> = std::iter::once("whole".to_owned())
.chain((1..workspace - 1).map(|n| format!("member-{n}")))
.chain(std::iter::once("selected".to_owned()))
.collect();
let parts = |node: usize| {
nodes[(node * PARTS + 1).min(nodes.len())..(node * PARTS + PARTS + 1).min(nodes.len())]
.join(", ")
};
let definitions = fixture.repo.join(".artifactize");
for (node, name) in nodes.iter().enumerate().skip(1) {
let parts = parts(node);
if !parts.is_empty() {
fs::write(
definitions.join(format!("{name}.artf")),
format!("artf {name} = {{ path = \"inputs/\" parts = [{parts}] }}"),
)
.unwrap();
}
}
fs::write(
definitions.join("whole.artf"),
format!(
r#"artf whole : files = {{
path = "inputs/"
parts = [{}]
eval approve : human = {{ title = "Approve the whole" instruction = "Approve @{{artf self}}." }}
}}"#,
parts(0)
),
)
.unwrap();
assert_eq!(
config::read_workspace_config(&fixture.repo)
.unwrap()
.artifacts
.len(),
workspace
);
let whole = Selection::Artifact {
artifact_id: "whole".parse().unwrap(),
};
fixture.reserve(&whole).await;
let before = definition_bytes(&fixture.state);
fixture.reserve(&whole).await;
let added = definition_bytes(&fixture.state) - before;
record(
series,
"repeat-admission",
"W",
workspace,
Sample(BTreeMap::from([("definition-bytes", added as f64)])),
);
}
}
async fn review_reads(series: &mut Series) {
const PER_RUN: usize = 500;
const REQUESTS: [usize; 4] = [2_000, 4_000, 8_000, 16_000];
let fixture = Fixture::new(PER_RUN, PER_RUN - 1, 1);
let selection = Fixture::selection(PER_RUN - 1);
let query: crate::review::search::Query = "type:human".parse().unwrap();
let query = query.for_live_repositories();
let reviewer = "alice".parse().unwrap();
let mut saved = 0;
for requests in REQUESTS {
while saved < requests {
fixture.reserve(&selection).await;
saved += PER_RUN;
}
let count = Count::start();
let page = crate::review::search::search(&fixture.state, &query, &reviewer, 0)
.await
.unwrap();
record(series, "review-page", "Q", requests, count.finish());
assert_eq!(page.requests.len(), crate::review::search::PAGE);
let count = Count::start();
let found = crate::review::search::count(&fixture.state, &query, &reviewer)
.await
.unwrap();
record(series, "review-count", "Q", requests, count.finish());
assert_eq!(found, requests as u64);
}
}
fn open_detail(fixture: &Fixture, graph: &live::Current, selected: &ArtifactName) {
let node = graph.artifact(selected).unwrap();
let definition = (
node.name.to_string(),
node.definition.clone(),
node.binding
.as_ref()
.map(|binding| (binding.line, binding.macro_name.clone())),
node.written_path.clone(),
node.target_missing,
node.parts
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>(),
node.tools.clone(),
);
assert!(definition.1.ends_with("selected.artf"));
assert_eq!(
definition.2.and_then(|(_, name)| name).as_deref(),
Some("reviewed!")
);
let tools = ArtifactDeclarations::read_indexed(&fixture.repo, selected, &graph.sites)
.unwrap()
.tools()
.unwrap();
assert!(!tools.is_empty());
let source = config::expand::indexed(&fixture.repo, &graph.sites, selected).unwrap();
assert_eq!(source.macro_name.as_deref(), Some("reviewed!"));
}
async fn apply_finished_run(
fixture: &Fixture,
place: &live::Place,
graph: &mut live::Current,
run: &RunId,
) {
let evidence = live::current_run(&fixture.state, place, run).await.unwrap();
assert!(graph.apply_run(evidence));
}
async fn live_at_boundary() -> u64 {
tokio::task::spawn_blocking(|| LIVE.load(Relaxed))
.await
.unwrap()
}
async fn record_retained(
series: &mut Series,
operation: &'static str,
mut measure: impl AsyncFnMut(usize) -> u64,
) {
measure(*ACTION_COUNTS.last().unwrap()).await;
for n in ACTION_COUNTS {
const TRIALS: usize = 5;
let mut trials = [0; TRIALS];
for trial in &mut trials {
*trial = measure(n).await;
}
let bytes = trials.into_iter().max().unwrap();
if trials.iter().any(|&trial| trial != bytes) {
eprintln!("{operation}: retained-byte trials at N={n}: {trials:?}");
}
record(
series,
operation,
"N",
n,
Sample(BTreeMap::from([("retained-bytes", bytes as f64)])),
);
}
}
async fn repeated_actions(series: &mut Series) {
live_at_boundary().await;
let fixture = Fixture::new(1_000, 1, 4);
let selected: ArtifactName = "selected".parse().unwrap();
let selection = Selection::Artifact {
artifact_id: selected.clone(),
};
let runs = fixture
.finished_runs(
&fixture.state,
&selection,
1 + ACTION_COUNTS.last().unwrap(),
)
.await;
let (initial, runs) = runs.split_first().unwrap();
let place = live::Place::Folder(crate::platform::canonicalize(&fixture.repo).unwrap());
let outline = live::outline(&fixture.repo).unwrap();
record_retained(series, "detail-open", async |n| {
let before = live_at_boundary().await;
for _ in 0..n {
open_detail(&fixture, &outline, &selected);
}
live_at_boundary().await.saturating_sub(before)
})
.await;
record_retained(series, "scope-check", async |n| {
let mut graph = outline.clone();
let checked = fixture.forecast(&selection, graph.sites.clone()).await;
graph.merge_scope(checked);
assert_ne!(
graph.artifact(&selected).unwrap().plan,
live::Plan::Unchecked
);
let before = live_at_boundary().await;
for _ in 0..n {
let checked = fixture.forecast(&selection, graph.sites.clone()).await;
graph.merge_scope(checked);
}
live_at_boundary().await.saturating_sub(before)
})
.await;
record_retained(series, "graph-run-finished", async |n| {
let mut graph = outline.clone();
apply_finished_run(&fixture, &place, &mut graph, initial).await;
let before = live_at_boundary().await;
for run in &runs[..n] {
apply_finished_run(&fixture, &place, &mut graph, run).await;
}
live_at_boundary().await.saturating_sub(before)
})
.await;
}
fn contract() -> String {
fs::read_to_string(
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../project-specs/perf-complexity.md"),
)
.expect("the repository performance contract")
}
fn slope(samples: &[(f64, f64)]) -> f64 {
let n = samples.len() as f64;
let x = samples.iter().map(|(x, _)| x).sum::<f64>() / n;
let y = samples.iter().map(|(_, y)| y).sum::<f64>() / n;
let covariance = samples.iter().map(|(a, b)| (a - x) * (b - y)).sum::<f64>();
let variance = samples.iter().map(|(a, _)| (a - x).powi(2)).sum::<f64>();
covariance / variance
}
fn check(contract: &str, series: &Series) -> Vec<String> {
let mut failures = Vec::new();
for line in contract
.lines()
.filter(|line| line.starts_with('|'))
.skip(2)
{
let [op, metric, axis, kind, bound, tolerance, rule]: [&str; 7] = line
.trim_matches('|')
.split('|')
.map(str::trim)
.collect::<Vec<_>>()
.try_into()
.unwrap();
let label = format!("{op}: {metric} vs {axis}");
let values: Vec<_> = series
.get(&(op, axis))
.into_iter()
.flatten()
.filter_map(|(x, sample)| sample.0.get(metric).map(|y| (*x as f64, *y)))
.collect();
if values.is_empty() {
failures.push(format!("{label}: no measurement"));
continue;
}
let bound: f64 = bound.parse().unwrap();
let tolerance: f64 = tolerance.parse().unwrap();
let (value, passes) = match kind {
"order" => {
let points: Vec<_> = values
.iter()
.map(|(x, y)| (x.ln(), y.max(1.0).ln()))
.collect();
let value = slope(&points);
(value, value <= bound + tolerance)
}
"max" => {
let value = values
.iter()
.map(|(_, y)| *y)
.fold(f64::NEG_INFINITY, f64::max);
(value, value <= bound + tolerance)
}
"min" => {
let value = values.iter().map(|(_, y)| *y).fold(f64::INFINITY, f64::min);
(value, value >= bound - tolerance)
}
_ => panic!("{label}: unknown check {kind}"),
};
eprintln!(
"{label}: {kind} {value:.3}, bound {bound:.3} ± {tolerance:.3}, samples {values:?}"
);
if !passes {
failures.push(format!("{label}: {value:.3} violates {rule}"));
}
}
failures
}
#[test]
#[ignore = "performance Runtime eval runs this benchmark on its own"]
fn synthetic_performance_contract() {
let mut series = Series::new();
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
cold_requests(&mut series).await;
config_and_scope(&mut series).await;
content(&mut series).await;
run_history(&mut series).await;
repeat_admission(&mut series).await;
review_reads(&mut series).await;
});
const WORKER_KEEP_ALIVE: Duration = Duration::from_secs(3_600);
tokio::runtime::Builder::new_current_thread()
.enable_all()
.max_blocking_threads(1)
.thread_keep_alive(WORKER_KEEP_ALIVE)
.build()
.unwrap()
.block_on(repeated_actions(&mut series));
let failures = check(&contract(), &series);
assert!(failures.is_empty(), "{}", failures.join("\n"));
}