Something went wrong. Try again.
Exploring the idea of generated web rendering engine.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398//! Runs every candidate over the cached corpus and reports per-case pass/fail.//! [`main`] is what a generated candidate crate's `main.rs` calls with its own registry//! of `(name, resolver)` pairs//! (`crate::candidate_crate::write`); [`evaluate`] is the pure function underneath it,//! exercised directly by this crate's own tests without compiling anything.
use std::collections::BTreeMap;use std::fs;use std::path::PathBuf;
use anyhow::{bail, Context, Result};use dom::Document;use harness::compare::{ compare, relative_offset, CaseComparison, CaseReport, Consensus, Metric, NodeDiff, VoteMeasurement,};use harness::dump::{Dump, Node as DumpNode, Rect, Viewport, TOLERANCE_PX};use layout::boxtree::BoxTree;use layout::fragment;use layout::width::WidthResolver;use serde::{Deserialize, Serialize};
use crate::groundtruth::CachedCase;
/// The harness's fixed viewport (`docs/dump-format.md`), matching every other consumer/// of the corpus (`crates/layout/src/bin/fragment_check.rs`).const VIEWPORT_WIDTH: f64 = 800.0;const VIEWPORT_HEIGHT: f64 = 600.0;
/// Renders `html` through the real layout path with `resolver` standing in for the/// width-equation seam, and reshapes the result into the same [`Dump`] shape a browser/// dump takes -- mirrors `crates/layout/src/bin/fragment_check.rs`'s `engine_dump`,/// generalized over which resolver runs.pub fn candidate_dump(html: &str, resolver: WidthResolver) -> Dump { let document = Document::parse(html); let elements = document.elements_in_document_order(); let tree = BoxTree::build(&document); let root_fragment = fragment::layout_with_resolver(&document, &tree, (VIEWPORT_WIDTH, VIEWPORT_HEIGHT), resolver);
let mut rects: BTreeMap<dom::node::NodeId, Rect> = BTreeMap::new(); root_fragment.walk_absolute(0.0, 0.0, &mut |node, x, y, w, h| { rects.insert(node, Rect { x, y, w, h }); });
let mut index_of: BTreeMap<dom::node::NodeId, usize> = BTreeMap::new(); for (i, &el) in elements.iter().enumerate() { index_of.insert(el, i); }
let nodes = elements .iter() .enumerate() .map(|(index, el)| { let parent = el.dom_parent().map(|p| index_of[&p] as i64).unwrap_or(-1); let mut depth = 0u32; let mut cur = *el; while let Some(p) = cur.dom_parent() { depth += 1; cur = p; } let rect = rects.get(el).copied(); DumpNode { index, parent, tag: el.tag(), depth, bounding: rect.unwrap_or(Rect { x: 0.0, y: 0.0, w: 0.0, h: 0.0 }), rects: rect.map(|r| vec![r]).unwrap_or_default(), scroll: None, style: Default::default(), } }) .collect();
Dump { engine: "candidate".to_string(), engine_version: "0".to_string(), viewport: Viewport { width: 800, height: 600 }, overflowed: false, nodes, }}
/// The value a trustworthy [`VoteMeasurement`] agrees on: any value from an engine other/// than the named outlier (`Consensus::Majority`), or any value at all (`Unanimous`,/// where every value already agrees). `None` for a full split -- untrustworthy, per/// `VoteMeasurement::is_trustworthy`.fn majority_value(m: &VoteMeasurement) -> Option<f64> { match &m.consensus { Consensus::Split => None, Consensus::Unanimous => m.values.values().next().copied(), Consensus::Majority { outlier } => { m.values.iter().find(|(engine, _)| *engine != outlier).map(|(_, v)| *v) } }}
/// The value `candidate` itself reports for one vote measurement's node and metric.fn candidate_value(candidate: &Dump, m: &VoteMeasurement) -> Option<f64> { let node = candidate.nodes.get(m.node_index)?; Some(match m.metric { Metric::Width => node.bounding.w, Metric::Height => node.bounding.h, Metric::OffsetX => relative_offset(candidate, node).0, Metric::OffsetY => relative_offset(candidate, node).1, Metric::FragmentCount => node.rects.len() as f64, Metric::FragmentWidth(i) => node.rects.get(i)?.w, Metric::FragmentHeight(i) => node.rects.get(i)?.h, })}
/// Whether `candidate` agrees, within tolerance, with every trustworthy measurement in/// `vote_report`. A measurement the vote itself could not agree on (a full split) carries/// no reward either way and is skipped, matching `VoteReport::untrustworthy`.fn agrees_with_vote(candidate: &Dump, vote_report: &harness::compare::VoteReport) -> bool { vote_report.measurements.iter().filter(|m| m.is_trustworthy()).all(|m| { let Some(reference) = majority_value(m) else { return true }; match candidate_value(candidate, m) { Some(v) => (v - reference).abs() <= TOLERANCE_PX, None => false, } })}
/// One case's outcome for one candidate.#[derive(Debug, Clone, Copy, PartialEq)]enum Outcome { Passed, Failed, /// Overflowed or too few cached engines to compare against -- excluded from both the /// numerator and denominator, matching `CaseComparison::is_trustworthy`. Untrustworthy,}
/// Scores one case and keeps the per-node numeric error alongside the verdict. The/// [`CaseReport`] is `None` for a case that never reached geometry comparison (discarded,/// or a shape mismatch) -- there is no per-node error to report when the node sequences/// themselves do not line up.fn score_case(case: &CachedCase, resolver: WidthResolver) -> (Outcome, Option<CaseReport>) { let Some(reference) = case.dumps.get("chromium").or_else(|| case.dumps.values().next()) else { return (Outcome::Untrustworthy, None); }; let candidate = candidate_dump(&case.html, resolver);
match compare(&candidate, reference) { CaseComparison::Discarded(_) => (Outcome::Untrustworthy, None), CaseComparison::ShapeMismatch(_) => (Outcome::Failed, None), CaseComparison::Compared(pairwise) => { let outcome = match case.vote() { // Enough engines cached to vote: geometry pass/fail is decided against the // vote's per-measurement majority, not against one engine alone. Ok(vote_report) => { if agrees_with_vote(&candidate, &vote_report) { Outcome::Passed } else { Outcome::Failed } } // Fewer than three engines cached for this case: fall back to the pairwise // comparison against the single reference dump above. Err(_) => { if pairwise.passed { Outcome::Passed } else { Outcome::Failed } } }; (outcome, Some(pairwise)) } }}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]pub struct CategoryTally { pub passed: u64, pub total: u64,}
/// One scalar's signed error against ground truth, mirroring/// `harness::compare::Measurement`. Mirrored rather than reused because a/// [`CandidateReport`] is written as JSON by the generated candidate binary and read back/// by the driver process, so every type inside it must round-trip; `Measurement` derives/// `Serialize` only.#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]pub struct MetricDiff { /// Candidate value minus reference value, in CSS pixels. pub delta: f64, pub within_tolerance: bool,}
impl From<harness::compare::Measurement> for MetricDiff { fn from(m: harness::compare::Measurement) -> Self { MetricDiff { delta: m.delta, within_tolerance: m.within_tolerance, } }}
/// One node's geometry error, mirroring `harness::compare::NodeDiff` minus its fragment/// list -- the four box metrics are what a geometry-diff prompt names/// (`crate::prompt::build_absolute_positioning_geometry_diff`).#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct NodeGeometryDiff { pub index: usize, pub tag: String, pub width: MetricDiff, pub height: MetricDiff, pub offset_x: MetricDiff, pub offset_y: MetricDiff,}
impl From<&NodeDiff> for NodeGeometryDiff { fn from(n: &NodeDiff) -> Self { NodeGeometryDiff { index: n.index, tag: n.tag.clone(), width: n.width.into(), height: n.height.into(), offset_x: n.offset_x.into(), offset_y: n.offset_y.into(), } }}
/// One failing case's per-node numeric error, carried out of the candidate process to/// whatever builds the next prompt. Only nodes with at least one metric outside tolerance/// are kept: a whole corpus of every node's zero-delta rows would dwarf the report file/// and tell a model nothing.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct CaseGeometryDiff { pub case_id: String, pub nodes: Vec<NodeGeometryDiff>, pub differing_nodes: usize, pub worst_abs_delta: f64, pub sum_abs_delta: f64,}
impl CaseGeometryDiff { /// Projects a compared case down to the nodes that actually differ. pub fn from_case_report(case_id: &str, report: &CaseReport) -> Self { CaseGeometryDiff { case_id: case_id.to_string(), nodes: report .nodes .iter() .filter(|node| !node.passed()) .map(NodeGeometryDiff::from) .collect(), differing_nodes: report.differing_nodes, worst_abs_delta: report.worst_abs_delta, sum_abs_delta: report.sum_abs_delta, } }}
#[derive(Debug, Clone, Serialize, Deserialize)]pub struct CandidateReport { pub name: String, pub cases_run: u64, pub cases_passed: u64, /// Whether this candidate lost any case in the permanent regression set -- the /// admission gate (`roadmap.md` -> "Re-verify"), not `cases_passed`'s raw rate. pub admitted: bool, /// Regression-set case ids this candidate failed. Empty when `regression_set` was /// not supplied to [`evaluate`], since nothing was checked. pub regressed_cases: Vec<String>, pub per_category: BTreeMap<String, CategoryTally>, /// Every case id this candidate passed, out-of-process callers' only way to extend /// the permanent regression set with what a newly-admitted candidate passes /// (`crates/generation/src/bin/generation_loop.rs`) without recomputing `score_case` /// against a resolver they cannot name (candidate resolvers live inside the /// generated batch crate, not the driver that reads this report). pub passed_case_ids: Vec<String>, /// Per-node numeric error for every case this candidate failed and that reached /// geometry comparison. This is what a geometry-diff prompt is built from /// (`crate::prompt::build_absolute_positioning_geometry_diff`): the driver process /// reads it back out of the report JSON, having no way to re-run `score_case` against /// a resolver that lives inside the generated batch crate. `#[serde(default)]` so a /// report written before this field existed still parses. #[serde(default)] pub failing_case_diffs: Vec<CaseGeometryDiff>,}
#[derive(Debug, Clone, Serialize, Deserialize)]pub struct Report { pub candidates: Vec<CandidateReport>,}
/// The case ids `resolver` passes over `cases`. Used to seed and extend the permanent/// regression set, which needs actual ids (`CandidateReport` carries only aggregates and/// a pre-computed regression check, not every case it passed).pub fn passing_case_ids(resolver: WidthResolver, cases: &[CachedCase]) -> Vec<String> { cases .iter() .filter(|case| score_case(case, resolver).0 == Outcome::Passed) .map(|case| case.case_id.clone()) .collect()}
/// Runs every `(name, resolver)` pair over `cases`, tallying pass/fail per case and per/// category, and checking each against `regression_set` (case ids required not to/// regress; `None` means nothing is checked, matching the state before any candidate has/// ever been admitted).pub fn evaluate( registry: &[(&str, WidthResolver)], cases: &[CachedCase], regression_set: Option<&[String]>,) -> Report { let candidates = registry .iter() .map(|(name, resolver)| { let mut cases_run = 0u64; let mut cases_passed = 0u64; let mut passed_ids: Vec<String> = Vec::new(); let mut per_category: BTreeMap<String, CategoryTally> = BTreeMap::new(); let mut failing_case_diffs: Vec<CaseGeometryDiff> = Vec::new();
for case in cases { let (outcome, case_report) = score_case(case, *resolver); if outcome == Outcome::Untrustworthy { continue; } cases_run += 1; let passed = outcome == Outcome::Passed; if passed { cases_passed += 1; passed_ids.push(case.case_id.clone()); } else if let Some(report) = &case_report { failing_case_diffs.push(CaseGeometryDiff::from_case_report(&case.case_id, report)); } for category in &case.categories { let tally = per_category.entry(category.clone()).or_default(); tally.total += 1; if passed { tally.passed += 1; } } }
let regressed_cases: Vec<String> = regression_set .unwrap_or(&[]) .iter() .filter(|id| !passed_ids.contains(id)) .cloned() .collect();
CandidateReport { name: name.to_string(), cases_run, cases_passed, admitted: regressed_cases.is_empty(), regressed_cases, per_category, passed_case_ids: passed_ids, failing_case_diffs, } }) .collect();
Report { candidates }}
/// Entry point a generated candidate crate's `main.rs` calls/// (`crate::candidate_crate::write`). Reads the cache directory from/// `GENERATION_CACHE_DIR` and, if set, the permanent regression set (a JSON array of case/// ids) from `GENERATION_REGRESSION_SET`; writes the JSON report to `GENERATION_REPORT_OUT`/// if set, and always prints it to stdout.pub fn main(registry: &[(&str, WidthResolver)]) -> Result<()> { let cache_dir = PathBuf::from( std::env::var("GENERATION_CACHE_DIR") .context("GENERATION_CACHE_DIR must name the ground-truth cache directory")?, ); let cases = crate::groundtruth::load_all(&cache_dir)?; if cases.is_empty() { bail!( "no cached cases under {}; run the ground_truth_cache binary first", cache_dir.display() ); }
let regression_set: Option<Vec<String>> = match std::env::var("GENERATION_REGRESSION_SET") { Ok(path) => { let json = fs::read_to_string(&path).with_context(|| format!("reading {path}"))?; Some(serde_json::from_str(&json).with_context(|| format!("parsing {path}"))?) } Err(_) => None, };
let report = evaluate(registry, &cases, regression_set.as_deref()); let json = serde_json::to_string_pretty(&report)?; if let Ok(out) = std::env::var("GENERATION_REPORT_OUT") { fs::write(&out, &json).with_context(|| format!("writing {out}"))?; } println!("{json}"); Ok(())}