Skip to content

Don't rewrite it in Rust. Rewrite the 5% that's slow: profile your app, port the hot functions with your coding agent, prove they behave the same. Python, JS/TS, Ruby, Java, Kotlin, Go, PHP, C/C++, C#, R.

port: hold out every 5th recorded call from the agent

Miloszf4a6237b599f
diff --git a/README.md b/README.md
index 259c15e..9f62a32 100644
--- a/README.md
+++ b/README.md
@@ -58,6 +58,8 @@ Or step by step:
That port looked right but compared bytes instead of characters. 148 of 500 real calls caught it. On top of the recorded calls, fast-anything derives extra cases and lets the original answer them: edge cases (NaN, ±infinity, -0.0, zero and ±1, non-ASCII text, empty and up to 16× bigger inputs) and shrunk inputs (tiny and random slices). Nothing is enabled until every case matches: same values (floats within 1e-9), errors where the original errors. A port that is right but slower per call than the original (calling into Rust costs more than the work saved) isn't enabled either. `FAST_ANYTHING_DISABLE=1` runs the original any time.
+Every 5th recorded call (from 5 calls up) is held out of the crate folder the agent works in: verify replays it too but reports a mismatch there without the values, so a port that special-cases the calls it was shown still fails.
+
## Results
Real runs on an i5-10500, Windows 11 (C and C++: a 4-core GitHub Actions Linux runner). Reproduce them from [`examples/`](examples).
diff --git a/src/backend.rs b/src/backend.rs
index aa07e77..f9242a4 100644
--- a/src/backend.rs
+++ b/src/backend.rs
@@ -297,6 +297,106 @@ impl Lang {
}
}
+// ------------------------------------------------------------------ held-out calls
+
+/// Every 5th recorded call is held out.
+fn held(k: usize) -> bool {
+ k % 5 == 4
+}
+
+/// Move every 5th recorded call (derived and edge cases stay) from the crate's recordings to
+/// `holdout`, outside the crate folder: the agent writing the port never sees them, so a port that
+/// special-cases the calls it was shown fails verify. Fewer than 5 recorded calls hold none back.
+/// An .rds of the recorded calls beside the recordings (R) moves along whole: verify picks the
+/// held-out ones by position (see replay_order). Returns how many calls are held out.
+pub fn hold_out(recordings: &Path, holdout: &Path) -> Result<usize> {
+ let (rds, held_rds) = (recordings.with_extension("rds"), holdout.with_extension("rds"));
+ let _ = fs::remove_file(holdout);
+ let _ = fs::remove_file(&held_rds);
+ let text = fs::read_to_string(recordings).context("reading recordings.jsonl")?;
+ let lines: Vec<(&str, bool)> = text
+ .lines()
+ .filter(|l| !l.trim().is_empty())
+ .map(|l| (l, serde_json::from_str::<serde_json::Value>(l).is_ok_and(|c| c.get("derived").is_none())))
+ .collect();
+ if lines.iter().filter(|(_, recorded)| *recorded).count() < 5 {
+ return Ok(0);
+ }
+ let (mut keep, mut out, mut k) = (String::new(), String::new(), 0);
+ for (line, recorded) in lines {
+ let into = if recorded && held(k) { &mut out } else { &mut keep };
+ into.push_str(line);
+ into.push('\n');
+ k += usize::from(recorded);
+ }
+ if let Some(dir) = holdout.parent() {
+ fs::create_dir_all(dir)?;
+ }
+ fs::write(holdout, &out)?;
+ fs::write(recordings, keep)?;
+ if rds.exists() {
+ fs::rename(&rds, &held_rds)?;
+ }
+ Ok(out.lines().count())
+}
+
+/// Positions of `recorded` calls in the order verify replays them: the visible ones, then the held-out ones.
+pub fn replay_order(recorded: usize) -> Vec<usize> {
+ let (visible, out): (Vec<usize>, Vec<usize>) = (0..recorded).partition(|&k| !held(k));
+ visible.into_iter().chain(out).collect()
+}
+
+/// What verify replays, and where the runner reports.
+pub struct Replay {
+ pub cases: PathBuf,
+ pub out: PathBuf,
+ pub held_out: usize,
+}
+
+/// Without held-out calls: the crate's recordings.jsonl and verify.json, as always. With them, both
+/// sit in .fast/verify/<port>/, outside the crate folder: the cases are recordings.jsonl followed by
+/// the held-out calls, and the report shows their values.
+pub fn replay(ctx: &Ctx, port: &Port) -> Result<Replay> {
+ let dir = ctx.crate_dir(port);
+ let held_out = ctx.held_out(port);
+ if held_out == 0 {
+ return Ok(Replay { cases: dir.join("recordings.jsonl"), out: dir.join("verify.json"), held_out });
+ }
+ let mut text = fs::read_to_string(dir.join("recordings.jsonl")).context("reading recordings.jsonl")?;
+ if !text.is_empty() && !text.ends_with('\n') {
+ text.push('\n');
+ }
+ text.push_str(&fs::read_to_string(ctx.holdout(port)).context("reading the held-out calls")?);
+ let verify_dir = ctx.fast.join("verify").join(dir.file_name().unwrap_or_default());
+ fs::create_dir_all(&verify_dir)?;
+ let cases = verify_dir.join("cases.jsonl");
+ fs::write(&cases, text)?;
+ Ok(Replay { cases, out: verify_dir.join("verify.json"), held_out })
+}
+
+/// Failures among the held-out calls (replayed right after the `visible` lines of recordings.jsonl)
+/// lose their values, so neither the output nor the agent's next prompt shows them.
+pub fn redact_held_out(v: &mut Verify, func: &str, visible: usize) {
+ for f in &mut v.failures {
+ if (visible..visible + v.held_out).contains(&f.case) {
+ f.call = format!("(held out) {func}(…)");
+ f.expected = "its recorded result".into();
+ f.got = "something else".into();
+ }
+ }
+}
+
+/// The TASK.md line about held-out calls, if there are any.
+pub fn held_out_note(held_out: usize) -> String {
+ match held_out {
+ 0 => String::new(),
+ 1 => "1 more recorded call is held out: verify checks it too and reports a mismatch there without the values.\n\n".into(),
+ n => format!(
+ "{n} more recorded calls are held out: verify checks them too and reports a mismatch there without the values.\n\n"
+ ),
+ }
+}
+
/// Settings shared by every generated crate: tuned for the machine that builds it
/// (.fast/lib is rebuilt per machine, never shipped), plus macOS extension linking.
pub const CARGO_CONFIG: &str = "# Built for the machine that runs it: .fast/lib is rebuilt per machine, never shipped.\n\
@@ -491,4 +591,111 @@ mod tests {
assert!(bom_on.starts_with('\u{feff}'));
assert_eq!(strip_marked(&bom_on, "#", "m.f"), bom_main);
}
+
+ fn call(k: usize) -> String {
+ format!("{{\"args\":[{k}],\"result\":{}}}", k * 1000 + 7)
+ }
+
+ #[test]
+ fn every_fifth_recorded_call_is_held_out() {
+ let dir = std::env::temp_dir().join(format!("fa-holdout-split-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&dir).unwrap();
+ let (recordings, holdout) = (dir.join("recordings.jsonl"), dir.join("holdout/demo.jsonl"));
+ let mut lines: Vec<String> = (0..12).map(call).collect();
+ lines.insert(6, r#"{"args":[-1],"result":-1,"derived":"edge"}"#.into());
+ lines.push(r#"{"args":[0],"result":7,"derived":true}"#.into());
+ fs::write(&recordings, lines.join("\n") + "\n").unwrap();
+ fs::write(dir.join("recordings.rds"), "every recorded call").unwrap();
+
+ assert_eq!(hold_out(&recordings, &holdout).unwrap(), 2);
+ assert_eq!(fs::read_to_string(&holdout).unwrap(), format!("{}\n{}\n", call(4), call(9)));
+ let kept = fs::read_to_string(&recordings).unwrap();
+ assert_eq!(kept.lines().count(), 12, "10 recorded calls and both derived ones stay: {kept}");
+ assert!(kept.contains("\"derived\":\"edge\"") && kept.contains("\"derived\":true"));
+ assert!(!kept.contains(&call(4)) && !kept.contains(&call(9)));
+ assert!(!dir.join("recordings.rds").exists() && dir.join("holdout/demo.rds").exists(), "the .rds moves along");
+
+ // Porting again records afresh; fewer than 5 recorded calls hold none back.
+ let few: Vec<String> = (0..4).map(call).chain([r#"{"args":[0],"result":7,"derived":true}"#.into()]).collect();
+ fs::write(&recordings, few.join("\n") + "\n").unwrap();
+ assert_eq!(hold_out(&recordings, &holdout).unwrap(), 0);
+ assert!(!holdout.exists() && !dir.join("holdout/demo.rds").exists());
+ assert_eq!(fs::read_to_string(&recordings).unwrap(), few.join("\n") + "\n");
+ let _ = fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn verify_replays_held_out_calls_after_the_visible_ones() {
+ assert_eq!(replay_order(12), [0, 1, 2, 3, 5, 6, 7, 8, 10, 11, 4, 9]);
+ assert_eq!(replay_order(4), [0, 1, 2, 3]);
+
+ let root = std::env::temp_dir().join(format!("fa-holdout-replay-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&root);
+ fs::create_dir_all(&root).unwrap();
+ let ctx = Ctx::open(&root).unwrap();
+ let port = Port {
+ id: "app.f".into(),
+ file: "app.py".into(),
+ module: "app".into(),
+ func: "f".into(),
+ ext: "fa_app_f".into(),
+ crate_dir: ".fast/ports/app.f".into(),
+ recorded: 12,
+ calls_seen: 12,
+ verify: None,
+ enabled: false,
+ lang: Lang::Python,
+ owner: None,
+ line: 1,
+ sources: vec![],
+ };
+ let dir = ctx.crate_dir(&port);
+ fs::create_dir_all(&dir).unwrap();
+ let recordings = dir.join("recordings.jsonl");
+ fs::write(&recordings, (0..12).map(call).collect::<Vec<_>>().join("\n") + "\n").unwrap();
+
+ // A port from before holding out: the crate's own files, as always.
+ let replay0 = replay(&ctx, &port).unwrap();
+ assert_eq!((replay0.cases, replay0.out, replay0.held_out), (recordings.clone(), dir.join("verify.json"), 0));
+
+ hold_out(&recordings, &ctx.holdout(&port)).unwrap();
+ assert_eq!(ctx.held_out(&port), 2);
+ let r = replay(&ctx, &port).unwrap();
+ assert_eq!(r.held_out, 2);
+ assert!(
+ !r.cases.starts_with(&dir) && !r.out.starts_with(&dir),
+ "outside the crate folder: {}",
+ r.cases.display()
+ );
+ let merged: Vec<String> = fs::read_to_string(&r.cases).unwrap().lines().map(str::to_string).collect();
+ let want: Vec<String> = replay_order(12).into_iter().map(call).collect();
+ assert_eq!(merged, want, "visible calls first, then the held-out ones at 10 and 11");
+ let _ = fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn held_out_failures_lose_their_values() {
+ let failure = |case: usize, value: &str| crate::state::Failure {
+ case,
+ call: format!("f({value})"),
+ expected: value.into(),
+ got: "0".into(),
+ };
+ let mut v = Verify {
+ built: true,
+ total: 20,
+ held_out: 2,
+ derived: 8,
+ failed: 3,
+ failures: vec![failure(3, "3007"), failure(10, "4007"), failure(12, "9")],
+ ..Verify::default()
+ };
+ redact_held_out(&mut v, "f", 10);
+ assert_eq!(v.failures[0].call, "f(3007)", "a visible call keeps its values");
+ assert_eq!(v.failures[0].expected, "3007");
+ assert_eq!(v.failures[1].call, "(held out) f(…)");
+ assert!(!format!("{:?}", v.failures[1]).contains("4007"), "{:?}", v.failures[1]);
+ assert_eq!(v.failures[2].call, "f(9)", "derived cases come after the held-out ones");
+ }
}
diff --git a/src/native.rs b/src/native.rs
index 6a7cded..fbcf33f 100644
--- a/src/native.rs
+++ b/src/native.rs
@@ -177,7 +177,14 @@ fn sample_calls(path: &Path, func: &str, n: usize) -> Vec<String> {
.collect()
}
-pub fn task_md(hs: &Hotspot, helpers: &[Hotspot], port: &Port, crate_dir: &Path, f: &Flavor) -> String {
+pub fn task_md(
+ hs: &Hotspot,
+ helpers: &[Hotspot],
+ port: &Port,
+ crate_dir: &Path,
+ f: &Flavor,
+ held_out: usize,
+) -> String {
let fence = "```";
let label = f.lang.label();
let samples = sample_calls(&crate_dir.join("recordings.jsonl"), &hs.name, 8).join("\n");
@@ -203,7 +210,7 @@ Only edit files in this folder. Don't touch the {label} project.\n\n\
## The original ({file}:{line})\n\n{fence}{lang}\n{source}\n{fence}\n\n\
{helper_md}\
## Real calls\n\n\
-fast-anything recorded {recorded} real calls (out of {seen} while the app ran). Arguments arrive as JSON. A few:\n\n{fence}\n{samples}\n{fence}\n\n\
+fast-anything recorded {recorded} real calls (out of {seen} while the app ran). Arguments arrive as JSON. A few:\n\n{fence}\n{samples}\n{fence}\n\n{held}\
## Rules\n\n\
- Same result for every input, edge cases included: empty input, zero, negatives, non-ASCII text, very long input. verify tests these too.\n\
{rules}\
@@ -220,7 +227,8 @@ Run `cargo check` here. Then fast-anything builds the crate in release mode and
line = hs.line,
lang = f.fence,
source = hs.source,
- recorded = port.recorded,
+ recorded = port.recorded.saturating_sub(held_out),
+ held = backend::held_out_note(held_out),
seen = util::thousands(port.calls_seen),
)
}
@@ -236,7 +244,7 @@ pub fn scaffold(ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port, f: &F
if !body.exists() {
fs::write(&body, port_rs(hs, port, f))?;
}
- let task = task_md(hs, helpers, port, &dir, f);
+ let task = task_md(hs, helpers, port, &dir, f, ctx.held_out(port));
fs::write(dir.join("TASK.md"), &task)?;
Ok(task)
}
@@ -265,10 +273,11 @@ fn half() -> f64 {
pub fn verify(ctx: &Ctx, port: &Port, loose_empty: bool) -> Result<Verify> {
let dir = ctx.crate_dir(port);
let (_, lib) = port.lang.artifact(&port.ext);
- let out = dir.join("verify.json");
+ let replay = backend::replay(ctx, port)?;
+ let out = replay.out;
let _ = fs::remove_file(&out);
let job = json!({
- "lib": ctx.lib_dir().join(lib), "cases": dir.join("recordings.jsonl"), "meta": dir.join("recordings.meta.json"),
+ "lib": ctx.lib_dir().join(lib), "cases": replay.cases, "meta": dir.join("recordings.meta.json"),
"func": port.func, "out": out, "loose_empty": loose_empty,
});
let job_path = dir.join("job-verify.json");
@@ -278,7 +287,7 @@ pub fn verify(ctx: &Ctx, port: &Port, loose_empty: bool) -> Result<Verify> {
let mut v = if run.status.success() && out.exists() {
serde_json::from_str::<Verify>(&fs::read_to_string(&out)?).context("reading verify results")?
} else {
- let total = fs::read_to_string(dir.join("recordings.jsonl")).map(|t| t.lines().count()).unwrap_or(0);
+ let total = util::count_lines(&replay.cases);
Verify {
total,
failed: total,
@@ -326,7 +335,7 @@ pub fn replay(job_path: &Path) -> Result<()> {
}
};
- let text = fs::read_to_string(&job.cases).context("reading recordings.jsonl")?;
+ let text = fs::read_to_string(&job.cases).context("reading the recorded calls")?;
let cases: Vec<Value> =
text.lines().filter(|l| !l.trim().is_empty()).filter_map(|l| serde_json::from_str(l).ok()).collect();
let (mut passed, mut failed, mut derived, mut edges) = (0, 0, 0, 0);
diff --git a/src/node.rs b/src/node.rs
index 5a8eab3..9a63de7 100644
--- a/src/node.rs
+++ b/src/node.rs
@@ -442,7 +442,7 @@ fn sample_calls(path: &Path, func: &str, n: usize) -> Vec<String> {
.collect()
}
-pub fn task_md(hs: &Hotspot, helpers: &[Hotspot], port: &Port, crate_dir: &Path) -> String {
+pub fn task_md(hs: &Hotspot, helpers: &[Hotspot], port: &Port, crate_dir: &Path, held_out: usize) -> String {
let fence = "```";
let lang =
if hs.file.ends_with(".ts") || hs.file.ends_with(".mts") || hs.file.ends_with(".cts") { "ts" } else { "js" };
@@ -455,7 +455,7 @@ Write `{func}` in `src/lib.rs` so it behaves **exactly** like the JavaScript bel
Only edit files in this folder. Don't touch the JavaScript project.\n\n\
## The original ({file}:{line})\n\n{fence}{lang}\n{source}\n{fence}\n\n\
{helpers}## Real calls\n\n\
-fast-anything recorded {recorded} real calls (out of {seen} while the app ran). A few:\n\n{fence}\n{samples}\n{fence}\n\n\
+fast-anything recorded {recorded} real calls (out of {seen} while the app ran). A few:\n\n{fence}\n{samples}\n{fence}\n\n{held}\
## Rules\n\n\
- Same result for every input, edge cases included: empty input, zero, negatives, NaN and infinity, non-ASCII text, very long input. verify tests these too.\n\
- JavaScript strings are UTF-16: `.length`, indexing and `charCodeAt` count UTF-16 code units. \
@@ -468,7 +468,7 @@ Use `s.encode_utf16()` for anything index- or length-based (bytes are fine after
- Keep `#[napi(js_name = \"{func}\", catch_unwind)]` as it is.\n\
{notes}\n\
## Check\n\n\
-Run `cargo check` here. Then fast-anything builds the crate in release mode and replays all {recorded} recorded calls against it\n\
+Run `cargo check` here. Then fast-anything builds the crate in release mode and replays all {total} recorded calls against it\n\
(`fast-anything verify {id}`).\n",
id = port.id,
dir = crate_dir.display(),
@@ -476,7 +476,9 @@ Run `cargo check` here. Then fast-anything builds the crate in release mode and
file = hs.file,
line = hs.line,
source = hs.source,
- recorded = port.recorded,
+ recorded = port.recorded.saturating_sub(held_out),
+ held = backend::held_out_note(held_out),
+ total = port.recorded,
seen = crate::util::thousands(port.calls_seen),
helpers = helpers_md(hs, helpers),
)
@@ -493,7 +495,7 @@ pub fn scaffold(ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port) -> Re
if !lib.exists() {
fs::write(&lib, lib_rs(hs, port))?;
}
- let task = task_md(hs, helpers, port, &dir);
+ let task = task_md(hs, helpers, port, &dir, ctx.held_out(port));
fs::write(dir.join("TASK.md"), &task)?;
Ok(task)
}
@@ -515,11 +517,11 @@ pub fn helpers_md(hs: &Hotspot, helpers: &[Hotspot]) -> String {
pub fn verify(ctx: &Ctx, port: &Port) -> Result<Verify> {
let node = ctx.runtime()?;
- let dir = ctx.crate_dir(port);
- let out = dir.join("verify.json");
+ let replay = backend::replay(ctx, port)?;
+ let out = replay.out;
let job = json!({
"addon": ctx.lib_dir().join(format!("{}.node", port.ext)), "js_name": port.func, "func": port.func,
- "module_file": ctx.root.join(&port.file), "cases": dir.join("recordings.jsonl"), "out": out, "budget": 0.5,
+ "module_file": ctx.root.join(&port.file), "cases": replay.cases, "held_out": replay.held_out, "out": out, "budget": 0.5,
});
// The original may not be exported: a block appended for this run hands it to the runner from
// inside the module, then the file goes back byte for byte.
diff --git a/src/node/runner.mjs b/src/node/runner.mjs
index fb14fba..234556a 100644
--- a/src/node/runner.mjs
+++ b/src/node/runner.mjs
@@ -1116,7 +1116,9 @@ async function verify(job) {
const cases = readFileSync(job.cases, "utf8").split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l));
const recorded = cases.length;
- const derived = typeof original === "function" ? derive(original, cases, job.derive_budget ?? 3, job.derive_limit ?? 200) : [];
+ // held-out calls (at the end) only get replayed: shrinking them would show their values in failures
+ const visible = cases.slice(0, recorded - (job.held_out ?? 0));
+ const derived = typeof original === "function" ? derive(original, visible, job.derive_budget ?? 3, job.derive_limit ?? 200) : [];
cases.push(...derived);
const report = { total: cases.length, derived: derived.length, edges: derived.filter((c) => c.derived === "edge").length, passed: 0, failed: 0, failures: [] };
const calls = [];
diff --git a/src/pipeline.rs b/src/pipeline.rs
index e4231d0..a6689cf 100644
--- a/src/pipeline.rs
+++ b/src/pipeline.rs
@@ -149,6 +149,7 @@ pub fn port(root: &Path, id: Option<&str>, samples: usize) -> Result<PortOut> {
line: hs.line,
sources: crate::state::verbatim(&text, &sources),
};
+ backend::hold_out(&dir.join("recordings.jsonl"), &ctx.holdout(&port))?;
let task = lang.scaffold(&ctx, &hs, &helpers, &port)?;
ctx.state.ports.insert(port.id.clone(), port);
ctx.save()?;
@@ -181,7 +182,11 @@ pub fn verify(root: &Path, id: Option<&str>) -> Result<(String, Verify)> {
port.recorded,
if port.recorded == 1 { "" } else { "s" }
));
- port.lang.verify(&ctx, &port)?
+ let visible = util::count_lines(&ctx.crate_dir(&port).join("recordings.jsonl"));
+ let mut v = port.lang.verify(&ctx, &port)?;
+ v.held_out = ctx.held_out(&port);
+ backend::redact_held_out(&mut v, &port.func, visible);
+ v
}
};
let mut v = v;
@@ -402,6 +407,11 @@ pub fn feedback(v: &Verify) -> String {
for f in &v.failures {
out.push_str(&format!("- `{}` should give `{}`, the port gave `{}`\n", f.call, f.expected, f.got));
}
+ if v.failures.iter().any(|f| f.call.starts_with("(held out) ")) {
+ out.push_str(
+ "\nCalls marked (held out) aren't in recordings.jsonl: port the logic, not the calls you were shown.\n",
+ );
+ }
}
out.push_str(if v.lang.c_bridge() { "\nFix src/port.rs.\n" } else { "\nFix src/lib.rs.\n" });
out
@@ -584,6 +594,29 @@ mod tests {
assert!(feedback(&wrong).contains("failed"));
}
+ #[test]
+ fn feedback_never_shows_a_held_out_call() {
+ let failure = |case: usize, value: &str| crate::state::Failure {
+ case,
+ call: format!("f({value}, \"secret-{value}\")"),
+ expected: format!("{value}.25"),
+ got: format!("{value}.5"),
+ };
+ let mut v = Verify {
+ built: true,
+ total: 600,
+ held_out: 100,
+ failed: 2,
+ failures: vec![failure(7, "31"), failure(450, "8675309")],
+ ..Verify::default()
+ };
+ backend::redact_held_out(&mut v, "f", 400);
+ let text = feedback(&v);
+ assert!(text.contains("`(held out) f(…)`") && text.contains("port the logic"), "{text}");
+ assert!(!text.contains("8675309"), "{text}");
+ assert!(text.contains("f(31, \"secret-31\")") && text.contains("31.25"), "{text}");
+ }
+
fn project(name: &str) -> (PathBuf, Port) {
let root = std::env::temp_dir().join(format!("fa-pipeline-{name}-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
diff --git a/src/python.rs b/src/python.rs
index 9d53d88..90bf049 100644
--- a/src/python.rs
+++ b/src/python.rs
@@ -735,7 +735,7 @@ pub fn sample_calls(path: &Path, func: &str, n: usize) -> Vec<String> {
.collect()
}
-pub fn task_md(hs: &Hotspot, helpers: &[Hotspot], port: &Port, crate_dir: &Path) -> String {
+pub fn task_md(hs: &Hotspot, helpers: &[Hotspot], port: &Port, crate_dir: &Path, held_out: usize) -> String {
let fence = "```";
let samples = sample_calls(&crate_dir.join("recordings.jsonl"), &hs.name, 8).join("\n");
let mut notes = String::new();
@@ -779,7 +779,7 @@ Write `{func}` in `src/lib.rs` so it behaves **exactly** like the Python below,
Only edit files in this folder. Don't touch the Python project.\n\n\
## The original ({file}:{line})\n\n{fence}python\n{source}\n{fence}\n\n\
{helpers}## Real calls\n\n\
-fast-anything recorded {recorded} real calls (out of {seen} while the app ran). A few:\n\n{fence}\n{samples}\n{fence}\n\n\
+fast-anything recorded {recorded} real calls (out of {seen} while the app ran). A few:\n\n{fence}\n{samples}\n{fence}\n\n{held}\
## Rules\n\n\
- Same result for every input, edge cases included: empty input, zero, negatives, NaN and infinity, non-ASCII text, very long input. verify tests these too.\n\
- Python `str` indexes by Unicode code point: use `.chars()` (or bytes only after checking `is_ascii()`).\n\
@@ -790,7 +790,7 @@ fast-anything recorded {recorded} real calls (out of {seen} while the app ran).
- std only, unless a crate clearly pays off. Keep the function and module names as they are.\n\
{notes}\n\
## Check\n\n\
-Run `cargo check` here. Then fast-anything builds the crate in release mode and replays all {recorded} recorded calls against it\n\
+Run `cargo check` here. Then fast-anything builds the crate in release mode and replays all {total} recorded calls against it\n\
(`fast-anything verify {id}`).\n",
id = port.id,
dir = crate_dir.display(),
@@ -798,7 +798,9 @@ Run `cargo check` here. Then fast-anything builds the crate in release mode and
file = hs.file,
line = hs.line,
source = hs.source,
- recorded = port.recorded,
+ recorded = port.recorded.saturating_sub(held_out),
+ held = backend::held_out_note(held_out),
+ total = port.recorded,
seen = crate::util::thousands(port.calls_seen),
helpers = helpers_md(hs, helpers),
)
@@ -815,7 +817,7 @@ pub fn scaffold(ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port) -> Re
if !lib.exists() {
fs::write(&lib, lib_rs(hs, port))?;
}
- let task = task_md(hs, helpers, port, &dir);
+ let task = task_md(hs, helpers, port, &dir, ctx.held_out(port));
fs::write(dir.join("TASK.md"), &task)?;
Ok(task)
}
@@ -839,12 +841,12 @@ pub fn helpers_md(hs: &Hotspot, helpers: &[Hotspot]) -> String {
pub fn verify(ctx: &Ctx, port: &Port) -> Result<Verify> {
let python = ctx.runtime()?;
- let dir = ctx.crate_dir(port);
- let out = dir.join("verify.json");
+ let replay = backend::replay(ctx, port)?;
+ let out = replay.out;
let job = json!({
"base": ctx.base_dir(), "libdir": ctx.lib_dir(), "ext": port.ext, "module": port.module,
"module_file": ctx.root.join(&port.file),
- "func": port.func, "owner": port.owner, "cases": dir.join("recordings.jsonl"), "out": out, "budget": 0.5,
+ "func": port.func, "owner": port.owner, "cases": replay.cases, "held_out": replay.held_out, "out": out, "budget": 0.5,
});
helper(ctx, python, "verify", job, &[])?;
let mut v: Verify = serde_json::from_str(&fs::read_to_string(&out)?).context("reading verify results")?;
diff --git a/src/python/runner.py b/src/python/runner.py
index 3af372f..8ec520e 100644
--- a/src/python/runner.py
+++ b/src/python/runner.py
@@ -973,7 +973,9 @@ def cmd_verify(job, _argv):
with open(job["cases"], encoding="utf-8") as f:
cases = [json.loads(line) for line in f if line.strip()]
recorded = len(cases)
- derived = derive(original, cases, job.get("derive_budget", 3.0), job.get("derive_limit", 200))
+ # held-out calls (at the end) only get replayed: shrinking them would show their values in failures
+ visible = cases[:recorded - job.get("held_out", 0)]
+ derived = derive(original, visible, job.get("derive_budget", 3.0), job.get("derive_limit", 200))
cases += derived
report = {"total": len(cases), "derived": len(derived), "passed": 0, "failed": 0, "failures": [],
diff --git a/src/r.rs b/src/r.rs
index ac908a4..f57538d 100644
--- a/src/r.rs
+++ b/src/r.rs
@@ -499,7 +499,7 @@ fn sample_calls(path: &Path, func: &str, n: usize) -> Vec<String> {
.collect()
}
-pub fn task_md(hs: &Hotspot, helpers: &[Hotspot], port: &Port, crate_dir: &Path) -> String {
+pub fn task_md(hs: &Hotspot, helpers: &[Hotspot], port: &Port, crate_dir: &Path, held_out: usize) -> String {
let fence = "```";
let samples = sample_calls(&crate_dir.join("recordings.jsonl"), &hs.name, 8).join("\n");
let mut helper_md = String::new();
@@ -521,7 +521,7 @@ Only edit files in this folder. Don't touch the R project.\n\n\
## The original ({file}:{line})\n\n{fence}r\n{source}\n{fence}\n\n\
{helper_md}\
## Real calls\n\n\
-fast-anything recorded {recorded} real calls (out of {seen} while the app ran). Arguments arrive as JSON, in parameter order. A few:\n\n{fence}\n{samples}\n{fence}\n\n\
+fast-anything recorded {recorded} real calls (out of {seen} while the app ran). Arguments arrive as JSON, in parameter order. A few:\n\n{fence}\n{samples}\n{fence}\n\n{held}\
## How R values arrive and go back\n\n\
- R has no scalars: a length-1 vector arrives as a plain value, a longer one as an array. Take vectors as `Vector<T>` (`crate::r::Vector`, accepts both; derefs to `Vec<T>`).\n\
- Integer and double vectors both arrive as numbers; take `f64` (or `i64` when the R code only uses whole numbers). NA arrives as null: `Option<T>`.\n\
@@ -543,7 +543,8 @@ Run `cargo check` here. Then fast-anything builds the crate in release mode and
file = hs.file,
line = hs.line,
source = hs.source,
- recorded = port.recorded,
+ recorded = port.recorded.saturating_sub(held_out),
+ held = backend::held_out_note(held_out),
seen = crate::util::thousands(port.calls_seen),
)
}
@@ -562,7 +563,7 @@ pub fn scaffold(ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port) -> Re
if !body.exists() {
fs::write(&body, port_rs(hs, port))?;
}
- let task = task_md(hs, helpers, port, &dir);
+ let task = task_md(hs, helpers, port, &dir, ctx.held_out(port));
fs::write(dir.join("TASK.md"), &task)?;
Ok(task)
}
@@ -570,11 +571,23 @@ pub fn scaffold(ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port) -> Re
pub fn verify(ctx: &Ctx, port: &Port) -> Result<Verify> {
let rscript = ctx.runtime()?;
let dir = ctx.crate_dir(port);
- let out = dir.join("verify.json");
+ let replay = backend::replay(ctx, port)?;
+ let out = replay.out;
+ // With calls held out, the .rds of every recorded call sits next to them (see backend::hold_out):
+ // the runner takes them in replay order, held-out ones last.
+ let (cases, order) = if replay.held_out == 0 {
+ (dir.join("recordings.rds"), Value::Null)
+ } else {
+ let recorded = crate::util::count_lines(&dir.join("recordings.jsonl")) + replay.held_out;
+ (
+ ctx.holdout(port).with_extension("rds"),
+ json!(backend::replay_order(recorded).iter().map(|k| k + 1).collect::<Vec<_>>()),
+ )
+ };
let (_, lib) = backend::Lang::R.artifact(&port.ext);
let job = json!({
- "root": ctx.root, "lib": ctx.lib_dir().join(lib), "func": port.func,
- "module_file": ctx.root.join(&port.file), "cases": dir.join("recordings.rds"), "out": out, "budget": 0.5,
+ "root": ctx.root, "lib": ctx.lib_dir().join(lib), "func": port.func, "module_file": ctx.root.join(&port.file),
+ "cases": cases, "order": order, "held_out": replay.held_out, "out": out, "budget": 0.5,
});
runner(ctx, rscript, "verify", job)?;
let mut v: Verify = serde_json::from_str(&fs::read_to_string(&out)?).context("reading verify results")?;
diff --git a/src/r/runner.R b/src/r/runner.R
index cfafc5a..0ac406f 100644
--- a/src/r/runner.R
+++ b/src/r/runner.R
@@ -192,6 +192,7 @@ if (mode == "verify") {
original <- get(job$func, envir = env)
port <- fa$.fa_port(job$lib, original)
cases <- readRDS(job$cases)
+ if (!is.null(job$order)) cases <- cases[unlist(job$order)] # held-out calls last
recorded <- length(cases)
derived <- list()
@@ -207,7 +208,8 @@ if (mode == "verify") {
if (inherits(result, "error") || is.null(tryCatch(fa$.fa_json(result), error = function(e) NULL))) return(invisible())
derived[[length(derived) + 1L]] <<- list(args = args, result = result, derived = kind)
}
- plain <- Filter(function(c) is.null(c$raises), cases)
+ # held-out calls (at the end) only get replayed: shrinking them would show their values in failures
+ plain <- Filter(function(c) is.null(c$raises), head(cases, recorded - job$held_out))
for (case in head(plain, 20)) {
base <- lapply(case$args, small)
for (i in seq_along(base)) {
diff --git a/src/ruby.rs b/src/ruby.rs
index f27cdfd..914a298 100644
--- a/src/ruby.rs
+++ b/src/ruby.rs
@@ -211,7 +211,7 @@ fn sample_calls(path: &Path, func: &str, n: usize) -> Vec<String> {
.collect()
}
-pub fn task_md(hs: &Hotspot, helpers: &[Hotspot], port: &Port, crate_dir: &Path) -> String {
+pub fn task_md(hs: &Hotspot, helpers: &[Hotspot], port: &Port, crate_dir: &Path, held_out: usize) -> String {
let fence = "```";
let samples = sample_calls(&crate_dir.join("recordings.jsonl"), &hs.name, 8).join("\n");
let mut helper_md = String::new();
@@ -233,7 +233,7 @@ Only edit files in this folder. Don't touch the Ruby project.\n\n\
## The original ({file}:{line})\n\n{fence}ruby\n{source}\n{fence}\n\n\
{helper_md}\
## Real calls\n\n\
-fast-anything recorded {recorded} real calls (out of {seen} while the app ran). Arguments arrive as JSON. A few:\n\n{fence}\n{samples}\n{fence}\n\n\
+fast-anything recorded {recorded} real calls (out of {seen} while the app ran). Arguments arrive as JSON. A few:\n\n{fence}\n{samples}\n{fence}\n\n{held}\
## Rules\n\n\
- Same result for every input, edge cases included: empty input, zero, negatives, NaN and infinity, non-ASCII text, very long input. verify tests these too.\n\
- Change the `serde_json::Value` parameter and return types to concrete ones: they're deserialized for you.\n\
@@ -251,7 +251,8 @@ Run `cargo check` here. Then fast-anything builds the crate in release mode and
file = hs.file,
line = hs.line,
source = hs.source,
- recorded = port.recorded,
+ recorded = port.recorded.saturating_sub(held_out),
+ held = backend::held_out_note(held_out),
seen = crate::util::thousands(port.calls_seen),
)
}
@@ -267,19 +268,19 @@ pub fn scaffold(ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port) -> Re
if !body.exists() {
fs::write(&body, port_rs(hs, port))?;
}
- let task = task_md(hs, helpers, port, &dir);
+ let task = task_md(hs, helpers, port, &dir, ctx.held_out(port));
fs::write(dir.join("TASK.md"), &task)?;
Ok(task)
}
pub fn verify(ctx: &Ctx, port: &Port) -> Result<Verify> {
let ruby = ctx.runtime()?;
- let dir = ctx.crate_dir(port);
- let out = dir.join("verify.json");
+ let replay = backend::replay(ctx, port)?;
+ let out = replay.out;
let (_, lib) = backend::Lang::Ruby.artifact(&port.ext);
let job = json!({
"lib": ctx.lib_dir().join(lib), "func": port.func, "owner": owner(port.owner.as_deref()),
- "module_file": ctx.root.join(&port.file), "cases": dir.join("recordings.jsonl"), "out": out, "budget": 0.5,
+ "module_file": ctx.root.join(&port.file), "cases": replay.cases, "held_out": replay.held_out, "out": out, "budget": 0.5,
});
runner(ctx, ruby, "verify", job, &[])?;
let mut v: Verify = serde_json::from_str(&fs::read_to_string(&out)?).context("reading verify results")?;
diff --git a/src/ruby/runner.rb b/src/ruby/runner.rb
index 944e2d7..fb196eb 100644
--- a/src/ruby/runner.rb
+++ b/src/ruby/runner.rb
@@ -419,7 +419,9 @@ def cmd_verify(job, _argv)
cases = File.readlines(job["cases"], chomp: true).reject(&:empty?).map { |l| JSON.parse(l) }
recorded = cases.length
- derived = derive(original, cases, job.fetch("derive_budget", 3.0), job.fetch("derive_limit", 200))
+ # held-out calls (at the end) only get replayed: shrinking them would show their values in failures
+ visible = cases.first(recorded - job.fetch("held_out", 0))
+ derived = derive(original, visible, job.fetch("derive_budget", 3.0), job.fetch("derive_limit", 200))
cases += derived
report = { "total" => cases.length, "derived" => derived.length, "edges" => derived.count { |c| c["derived"] == "edge" },
"passed" => 0, "failed" => 0, "failures" => [] }
diff --git a/src/show.rs b/src/show.rs
index 3451e17..0a06801 100644
--- a/src/show.rs
+++ b/src/show.rs
@@ -118,21 +118,22 @@ pub fn verify(id: &str, v: &Verify) {
return;
}
if v.ok() {
- if v.derived > 0 {
+ if v.derived + v.held_out > 0 {
+ let mut parts = vec![format!("{} recorded", v.total - v.derived - v.held_out)];
+ if v.held_out > 0 {
+ parts.push(format!("{} held out", v.held_out));
+ }
+ if v.edges > 0 {
+ parts.push(format!("{} edge cases", v.edges));
+ parts.push(format!("{} derived", v.derived - v.edges));
+ } else if v.derived > 0 {
+ parts.push(format!("{} derived", v.derived));
+ }
ui::ok(format!(
"{}/{} calls give the same result {}",
v.passed,
v.total,
- dim(if v.edges > 0 {
- format!(
- "({} recorded + {} edge cases + {} derived)",
- v.total - v.derived,
- v.edges,
- v.derived - v.edges
- )
- } else {
- format!("({} recorded + {} derived)", v.total - v.derived, v.derived)
- })
+ dim(format!("({})", parts.join(" + ")))
));
} else {
ui::ok(format!("{}/{} recorded calls give the same result", v.passed, v.total));
diff --git a/src/state.rs b/src/state.rs
index 82010c4..925ed6a 100644
--- a/src/state.rs
+++ b/src/state.rs
@@ -67,6 +67,8 @@ pub struct Verify {
pub derived: usize,
/// Of derived: edge cases (special numbers, non-ASCII text, empty and much bigger inputs).
pub edges: usize,
+ /// Of total, not derived: recorded calls kept out of the crate folder (see backend::hold_out).
+ pub held_out: usize,
pub passed: usize,
pub failed: usize,
pub failures: Vec<Failure>,
@@ -224,6 +226,17 @@ impl Ctx {
self.root.join(port.crate_dir.replace('/', std::path::MAIN_SEPARATOR_STR))
}
+ /// Recorded calls of the port kept out of its crate folder, so the agent writing it never sees them.
+ pub fn holdout(&self, port: &Port) -> PathBuf {
+ let name = Path::new(&port.crate_dir).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
+ self.fast.join("holdout").join(format!("{name}.jsonl"))
+ }
+
+ /// How many recorded calls of the port are held out.
+ pub fn held_out(&self, port: &Port) -> usize {
+ util::count_lines(&self.holdout(port))
+ }
+
pub fn base_dir(&self) -> PathBuf {
self.root.join(if self.state.base.is_empty() { "." } else { &self.state.base })
}
diff --git a/src/util.rs b/src/util.rs
index af2c925..efac7f7 100644
--- a/src/util.rs
+++ b/src/util.rs
@@ -40,6 +40,11 @@ pub fn slug(id: &str) -> String {
id.chars().map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '_' }).collect()
}
+/// Non-blank lines in a file, 0 if it can't be read.
+pub fn count_lines(path: &Path) -> usize {
+ std::fs::read_to_string(path).map(|t| t.lines().filter(|l| !l.trim().is_empty()).count()).unwrap_or(0)
+}
+
pub fn output(cmd: &mut Command, what: &str) -> Result<Output> {
cmd.output().with_context(|| format!("couldn't start {what} ({})", cmd.get_program().to_string_lossy()))
}