Skip to content

Independent rule validation

View as Markdown

Status: Complete on main. The P0 CI gate remains active.

Scope: Built-in SEO audit rules and their observable results.

Baseline: 398 rule IDs across 20 categories.

Establish an independent, reproducible validation suite that demonstrates whether each built-in Sonjoo rule behaves correctly under explicitly defined conditions. The suite must identify false positives, false negatives, incorrect not-measured decisions, missing implementations, misleading evidence, and regressions. A successful test must demonstrate the behavior of the real production rule, not simply prove that its ID exists in the registry.

The lab is development and CI infrastructure, not a new end-user product feature. It must run locally without live websites, paid services, external SEO tools, API credentials, or an LLM. Chromium is permitted and required for rules whose behavior depends on rendering; reuse the existing browser infrastructure. Do not introduce another runtime dependency or rewrite the audit engine merely to accommodate the suite.

Non-goals: proving rankings, actual search-engine indexing, AI citations, field Core Web Vitals, subjective expertise, legal compliance, or universal real-world accuracy from synthetic fixtures; replacing existing regression, transport, browser, or dashboard tests; adding production telemetry.

2. Existing architecture and integration points

Section titled “2. Existing architecture and integration points”

Use the current repository as the source of truth:

  • assets/audit/checks.tsv and engine::registry(): canonical rule IDs, categories, weights, advisory flags and render requirements.
  • src/engine.rs, src/engine/runtime.rs: production rule execution, context analysis, audit orchestration, scoring and not-measured handling.
  • src/rules/: existing implementations; fix verified defects here rather than duplicating detectors in the test harness.
  • tests/fixtures/sites.py, tests/fixtures/browser_sites.py and tests/network_support/mod.rs: reusable deterministic HTTP fixtures and real browser fixtures.
  • Existing Rust reference/golden tests and tests/transport_crawler.rs: preserve regression coverage. Existing expected outputs alone do not constitute independent validation unless their assumptions and assertions have been reviewed against an independent requirement.
  • tests/browser_live.rs, scripts/verify_workflows.py and tests/browser/dashboard.mjs: extend current end-to-end verification where needed; do not duplicate the whole UI test suite.
  • .github/workflows/checks.yml: the Rust job runs fast validation and the Linux runtime job runs the complete gate for changes that affect rules.

Use these files and the public engine APIs when changing the lab. Use existing configuration and report contracts. Preserve backward compatibility unless a documented correctness fix requires a behavior change.

The lab uses the following layout and shares helpers with the existing test support.

tests/
rule_validation.rs # Cargo integration-test target
fixtures/
rule_validation/
README.md # Fixture schema, conventions, source policy
core.json # Named cases grouped by catalog category
technical.json
... # One case file per catalog category
geo.json
sites/ # Reusable HTML/assets/routes when needed
scripts/
verify_rule_validation.py # Aggregate and enforce validation coverage
docs/
RULE_VALIDATION.md # This specification and run instructions
target/
rule-validation/ # Generated reports only; never committed

File organization may be adjusted to fit the existing fixture harness, but the single discoverable validation entry point, case traceability and automated coverage gate are mandatory. Do not create 398 independent websites or a separate repository. Group scenarios by category and share baseline pages and route definitions where they remain easy to understand.

Before writing cases, inventory every rule ID from the current registry and classify its contract:

Kind Validation basis
Objective Standards, protocol behavior, browser-observable facts, or published search-engine requirements
Policy or heuristic Explicit Sonjoo policy, documented thresholds, scope and limitations; not presented as a universal ranking factor
Advisory or manual review Observable signals, correct advisory state, evidence and honest uncertainty
Conditional Explicit prerequisites, such as rendering, crawl scope, network response, page type or configuration

Kinds may overlap. Record the rule’s expected behavior, applicable page types, prerequisites, meaningful outcomes, relevant evidence and authoritative source or explicit Sonjoo policy. Prefer primary sources such as Google Search Central, WHATWG HTML, RFC 9309, Schema.org, WCAG and provider-specific crawler documentation where applicable. Record the exact source URL/section and review date; distinguish requirements from recommendations. For product-defined heuristics, record a concise rationale and the actual configured threshold. Do not fetch sources during test execution.

Author expectations from the contract and fixture facts, not from the current implementation, a comparison product, or a captured Sonjoo report. Review them separately from the implementation changes. Do not bulk-accept generated snapshots, invent requirements, or silently change expectations to make CI pass. Any contract change needs a documented rationale and review. Use original fixtures or existing fixtures whose provenance permits reuse; retain applicable notices.

Use typed Rust deserialization for the fixture schema (existing Serde support). Give each case a unique stable ID and validate its schema strictly. Every case must specify:

  • Target rule ID, case ID, scenario intent, contract/source reference, fixture reference or input data, and execution mode (context, http, crawl, or browser).
  • Relevant page URL or fixture route, effective configuration, prerequisite state, and any explicit inputs (headers, redirects, robots directives, sitemap, related pages, rendered content, etc.).
  • Expected status (pass, warn, fail, not-measured) and the expected reason when unmeasured; expected advisory/scoring behavior where applicable.
  • Stable structured evidence assertions, e.g. affected URLs, counts, directive, field name, or metric bounds. Assert a relevant recommendation or message when needed to verify that the finding is actionable, without coupling every test to exact prose.

The missing-title case below comes from tests/fixtures/rule_validation/core.json. The rule’s contract in that file records its sources and review.

{
"case_id": "core-title-present.missing",
"rule_id": "core-title-present",
"intent": "defect",
"scenario": "Remove the title element while leaving the page unchanged.",
"prerequisites": "A parsed response body is available",
"mode": "context",
"input": {
"html": "<!doctype html><html lang=\"en\"><head></head><body></body></html>"
},
"expected": {
"status": "fail",
"evidence": { "/details/found": false },
"advisory": false,
"message_contains": "title"
},
"control": {
"group": "title-element",
"variant": "mutated"
}
}

Context-only fixtures use the supplied inputs without live network requests.

For each rule, define an explicit checklist of applicable case intents:

Intent Requirement
Healthy A valid input that must not produce an erroneous finding.
Defect A known violation or observable adverse signal that must be detected at the correct severity.
Boundary Values immediately below, at, and above a threshold, or the equivalent meaningful edge cases.
Not applicable A page, configuration, or condition outside the rule’s intended scope.
Unavailable Missing evidence, failed collection, incomplete crawl, or failed/disabled rendering.

Cover every meaningful outcome and applicable intent; a healthy/defect pair is the minimum for rules that can report both. Do not manufacture impossible states merely to satisfy a numeric quota. For example, a manual-review-only rule may not have a valid automated pass/fail pair. Document the contract and reason for each inapplicable intent, and still verify all observable behavior, uncertainty, evidence and scoring. An exemption from an intent is not an exemption from validating the rule. A rule without executable assertions cannot be marked validated.

Include representative regression cases for false positives and false negatives, malformed input, empty values, Unicode (Persian including ZWNJ, Arabic, Cyrillic and accented Latin), and duplicate or conflicting signals. Apply these where relevant rather than multiplying unrelated cases. Cover configurable thresholds and overrides without changing their defaults to obtain passing tests.

Construct real Context values and run the production engine/context analysis path with the intended rule selection. Assert exactly one relevant result for the requested rule and page scope. Use this for deterministic HTML, metadata, schema, content and scoring behavior.

Where synthetic measurement data is necessary (e.g. exact CWV boundaries), inject only input data through existing context or test seams, not expected rule outputs. These cases validate interpretation, not actual collection.

Reuse the fixture server(s), bind to loopback on an ephemeral port, and exercise the real fetcher, crawler, and audit orchestration. Cover status codes, redirect loops/chains, robots precedence, HTTP headers, malformed sitemaps, broken-link sources, canonicals, crawl completeness and cross-page findings. Use small multi-page graphs and explicit route/response expectations; assert relevant network requests as well as results when needed.

Keep fixture network traffic inside the test environment. No public DNS, remote assets or live third-party endpoints may be required. Use the current network safety design and narrowly scoped test support; never disable production URL, SSRF, redirect, authentication or browser protections.

Reuse the existing Chromium harness for rules that depend on the actual DOM, mobile parity, accessibility, runtime JavaScript, rendered links and browser measurements. Verify collection and the resulting rule behavior together, not only fabricated probe objects. Use controlled local HTML/CSS/JS and assets; avoid brittle exact timing assertions. For timing-based rules, test threshold interpretation with deterministic values and verify actual measurement collection separately. Use the existing synthetic-versus-field distinction.

Use the existing browser executable configuration (SONJOO_CHROMIUM). Keep browser cases explicit (e.g. ignored in the fast Rust suite and run by the browser job). Missing Chromium or failed collection must not be counted as a successful validation of a render-dependent case.

For representative critical cases, run the normal CLI or dashboard workflow and verify that structured findings, coverage, scoring, evidence and affected URLs survive into JSON, HTML and applicable dashboard views. Reuse existing scripts and Playwright tests for this layer. Check that advisory/unmeasured findings do not incorrectly affect scores and that disabled rules do not perform unintended probes.

For suitable rules, derive a defective fixture from a healthy fixture by changing one relevant property (remove a title, add a noindex directive, break a link, or introduce a conflicting canonical). Assert the rule changes to the expected outcome and that restoring the property restores its behavior. This is fixture mutation, not a requirement to add a source-code mutation-testing framework. Use it to isolate causality and avoid superficial tests. Retain independent negative controls.

Build a validation inventory dynamically from engine::registry(); do not maintain another hardcoded rule list. Keep 398/20 as the documented initial baseline, not a permanent limit. The suite must fail on unknown rule IDs, duplicate case IDs, invalid fixtures, missing applicable cases, missing or duplicate targeted results, status/evidence mismatches, or unjustified intent exemptions. A result with reason unsupported cannot satisfy validation. A rule returning not-measured must provide the correct reason when that is expected; otherwise treat it as a mismatch.

Distinguish these per-rule outcomes:

  • Validated: all required, independently reviewed cases executed and passed, including required HTTP/browser modes, with no unresolved known defects.
  • Incomplete: required contract, scenario, review, execution, or evidence is missing. Skipped tests do not count toward validation.
  • Failed: at least one required assertion failed or a known defect remains.

Produce machine-readable JSON and a concise human-readable summary in CI. Include commit SHA, suite/fixture version, relevant runtime/browser versions, catalog total, per-category and per-rule status, applicable intents, executed/passed/failed/skipped case counts, exemption rationale, expected versus actual results, and actionable failure diagnostics. Use stable rule and case IDs. Do not include secrets or private user audit data.

Report validation coverage as validated rule IDs / current catalog rule IDs. Separately report case pass rate and, for independently labeled and applicable binary healthy/defect cases, true positives, false positives, true negatives, false negatives, precision and recall (define the mapping of warn/fail to defect for each eligible rule). Report sample sizes and undefined denominators; exclude expected unmeasured/manual-review cases from binary metrics, but report unexpected unmeasured outcomes as misses on eligible defect cases and as mismatches. Do not present fixture metrics as empirical accuracy on the public web. A future separately curated real-world benchmark can measure that more directly; it is not a dependency of this lab.

Run the following commands from the repository root.

Fast validation without Chromium:

Terminal window
cargo test --locked --test rule_validation

Complete validation (Chromium installed and configured):

Terminal window
export SONJOO_CHROMIUM=/path/to/chromium
export SONJOO_VALIDATION_OUTPUT="$(mktemp -d)"
cargo test --locked --test rule_validation -- --include-ignored
python3 scripts/verify_rule_validation.py --input "$SONJOO_VALIDATION_OUTPUT" --require-complete

Define SONJOO_VALIDATION_OUTPUT as an optional test-only report directory. Each executed validation test writes its own structured results without concurrent overwrite. The verification script merges the results against the registry inventory emitted by the test harness, validates completeness and prints the final summary. Fail on stale, inconsistent or missing result records. Use a fresh output directory per full run. The script must return nonzero on invalid or incomplete coverage; it must not require any new Python package.

The Rust job runs formatting, Clippy, and all-target tests, including the fast suite. The Linux runtime job runs the full suite with Chromium, aggregates the JSON and text reports, and uploads the rule-validation artifact. The gate fails if a required rule or scenario is missing, skipped, or fails. Add independently reviewed validation cases in the same change as any new rule.

Use bounded timeouts, deterministic fixtures, isolated temporary storage (SONJOO_HOME where appropriate), cleanup on failure, and safe concurrent execution. Keep tests reproducible and practical for regular CI; reuse fixture server and browser sessions only where isolation is preserved.

The fixture README documents the versioned case format, evidence assertions, and review records. The verifier writes summary.json and summary.txt to the run directory by default. Review summary.json for each rule’s missing requirements, known gaps, and case diagnostics. A fast run omits the Chromium artifact by design and cannot establish complete coverage.

The lab has executable cases for every registered rule. Approval is tracked per rule. For HTTPS, the guarded transport can observe the verified leaf certificate expiry, negotiated TLS version, and selected ALPN protocol. The lab exercises these measurements with a scoped loopback CA. HSTS and Alt-Svc remain header observations with their own evidence.

The lab and its review fixes merged in PR #9. PR #10 removed the P0 milestone from the backlog. The main CI run at 0145788 validated all 398 rules across 20 categories and passed all 2,477 cases, including 140 Chromium cases, with zero skipped cases.

The PR #9 remediation compared release builds from the historical main baseline (0c370ac), the original PR head (7d09a27), and the remediation branch. To repeat the comparison, build sonjoo with cargo build --release --locked in separate worktrees and Cargo target directories. Run the comparisons against the same loopback fixture with other builds and tests idle.

Terminal window
python3 scripts/benchmark_audit_comparison.py \
--baseline /path/to/main/sonjoo --original /path/to/original/sonjoo \
--candidate /path/to/candidate/sonjoo --counts 1 20 --repeats 3
python3 scripts/benchmark_audit_comparison.py \
--baseline /path/to/main/sonjoo --original /path/to/original/sonjoo \
--candidate /path/to/candidate/sonjoo --style rich --categories crawl \
--counts 20 40 --repeats 3

The driver checks complete URL coverage and identical selected rule IDs, rotates binary order, and reports wall time, child CPU time, and HTTP request counts. The rich profile exercises cross-page rules on a denser link graph.

  • Inventory and baseline. Mapped the initial catalog to independent contracts, applicable intents, and required execution modes.
  • Harness and pilot. Added the shared fixture loader, production engine runner, assertions, and report aggregation. Added negative controls for invalid expectations and incomplete coverage.
  • Full catalog validation. Added reviewed cases for all 398 rules and regression tests for verified production defects. AEO passage matching has separate coverage.
  • Independent review and CI gate. Recorded per-rule approvals, resolved the blocking review findings, and enabled complete Chromium validation and reporting in CI.
  • Every current registered rule has an approved contract and executable, independently justified cases for every applicable intent.
  • Every rule is validated (398/398 at the initial baseline), with no unsupported implementations, missing required modes, or unresolved known validation defects. Required deterministic assertions pass.
  • All representative end-to-end findings and scoring/coverage assertions pass; existing Rust, transport, browser and dashboard checks remain green.
  • Full validation runs in CI without external services or credentials and emits an auditable report. A new or broken rule demonstrably fails the appropriate gate.
  • The suite, fixture schema, source provenance, review decisions and limits are documented. No generated artifacts or fixture infrastructure are shipped as part of the production executable unless already required.
  • A README statement such as “All 398 built-in rules have independently reviewed, reproducible validation scenarios” is permitted only when the report and passing gate substantiate it; update the count when the catalog changes. Do not claim universal real-world accuracy.