← All Engineering Blueprints
// blueprint #05 · complexity score: 89/100 · playwright + vision qa

Catching broken CSS layouts, z-index collisions, and mobile overflows without brittle pixel-diffs

Pixel-by-pixel screenshot diffing cries wolf every time dynamic copy changes or a font anti-aliases differently. This 3,015-line Python & Playwright crawler combines deterministic DOM bounding-box geometry math with multimodal Vision-LLM semantic auditing across Desktop, Tablet, and Mobile viewports.

3 ViewportsDesktop · Tablet · Mobile sweeps
DOM + VisionDual-layer geometry + AI audit
3,015 LOCPython · Playwright · Vision CLI

The engineering problem

Traditional visual regression tools compare baseline PNGs pixel-for-pixel. When a marketing headline changes or a timestamp updates, the entire page shifts by 4px and fails CI—training engineers to click 'Approve All' without looking.

True visual bugs are structural and semantic: a CTA button clipped off the right edge on iPhone SE (scrollWidth > clientWidth), two sibling text nodes overlapping due to a bad absolute position, or a broken hero image returning HTTP 404. I built a hybrid auditor that computes exact DOM rectangle intersections first, then passes flagged regions to Gemini Vision for semantic severity grading.

System architecture & interactive topology

A 3,015-line multi-viewport crawler and visual auditor across playwright_crawler.py, visual_qa_engine.py, and gemini_auditor.py:

  • Multi-Viewport Headless Crawler (playwright_crawler.py): Sweeps internal routes across Desktop (1440x900), Tablet (768x1024), and Mobile (375x812) with network-idle stabilization.
  • Deterministic DOM Geometry Probes (visual_qa_engine.py): Injects JS bounding-box inspectors to detect horizontal overflow, text bounding-box intersections (Rect.intersects), and zero-dimension broken images.
  • Multimodal Semantic Auditor (gemini_auditor.py): Evaluates full-page screenshots alongside DOM anomaly coordinates to filter out intentional overlapping designs (e.g. badges over cards) vs. real UI defects.
  • CI Exit-Code Gate & Annotated Reports: Emits structured visual_qa_report.json and fails CI builds only when CRITICAL or HIGH severity defects are confirmed.
SYSTEM TOPOLOGY & ARCHITECTURE BLUEPRINT
PRODUCTION ENGINE
Autonomous Visual QA & DOM/Layout Anomaly Detector architecture visualization
END-TO-END FLOW: Route Crawler → Viewport Matrix → DOM Geometry Probe → Vision Auditor → Box Highlighter → CI Verdict Gate ● DETERMINISTIC PIPELINE
NODE 01 Route Crawler Playwright Async BFS NODE 02 Viewport Matrix 1440w · 768w · 375w NODE 03 DOM Geometry Probe Rect.intersects Math NODE 04 Vision Auditor Multimodal Triage NODE 05 Box Highlighter Defect Crop & Draw NODE 06 CI Verdict Gate JSON Report + ExitCode

Click any node in the SVG diagram or list below to inspect its payload contract, latency SLA, and retry policy.

01 · INTERACTIVE NODE TOPOLOGY INSPECTOR
Inspect Stage-by-Stage Execution Contracts & Fault Boundaries

Select any node in the pipeline to examine its architectural responsibility, input/output schema types, p95 execution latency, and error recovery policy.

NODE 01 · Route Crawler
LATENCY: 320 ms
Architectural Role
Launches headless Chromium, discovers same-origin routes via BFS link extraction, and disables CSS animations/transitions for deterministic rendering.
Input / Output Payload Contract
IN: CrawlSeed(base_url, max_pages=25) -> OUT: List[PageTarget(url, slug, depth)]
Error & Retry Policy
Automatic retry on navigation timeout with fallback from networkidle to domcontentloaded.

Real code & schema inspector

Extracted directly from the production repository. Switch tabs to inspect the core execution logic, strict JSON/database data contracts, and structured LLM instructions.

// SOURCE: products/autonomous-visual-qa-broken-ui-detector-python-20261009/package/visual_qa_engine.py
class BugSeverity(str, enum.Enum):
    CRITICAL = "CRITICAL"
    HIGH = "HIGH"
    MEDIUM = "MEDIUM"
    LOW = "LOW"
    INFO = "INFO"


class BugCategory(str, enum.Enum):
    HORIZONTAL_OVERFLOW = "HORIZONTAL_OVERFLOW"
    TEXT_OVERLAP = "TEXT_OVERLAP"
    TEXT_TRUNCATION = "TEXT_TRUNCATION"
    OCCLUDED_INTERACTIVE = "OCCLUDED_INTERACTIVE"
    BROKEN_ASSET = "BROKEN_ASSET"
    VISUAL_REGRESSION = "VISUAL_REGRESSION"
    LAYOUT_SHIFT = "LAYOUT_SHIFT"


@dataclasses.dataclass
class Rect:
    x: float
    y: float
    width: float
    height: float

    def to_dict(self) -> Dict[str, float]:
        return {"x": self.x, "y": self.y, "width": self.width, "height": self.height}

    @property
    def right(self) -> float:
        return self.x + self.width

    @property
    def bottom(self) -> float:
        return self.y + self.height

    def intersects(self, other: "Rect") -> bool:
        return not (
            self.right <= other.x
            or other.right <= self.x
            or self.bottom <= other.y
            or other.bottom <= self.y
        )


@dataclasses.dataclass
class UIBug:
    category: BugCategory
    severity: BugSeverity
    selector: str
    description: str
    bounding_box: Optional[Rect]
    viewport: str
    details: Dict[str, Any] = dataclasses.field(default_factory=dict)
    screenshot_path: Optional[str] = None

    def to_dict(self) -> Dict[str, Any]:
        return {
            "category": self.category.value,
            "severity": self.severity.value,
            "selector": self.selector,
            "description": self.description,
            "bounding_box": self.bounding_box.to_dict() if self.bounding_box else None,
            "viewport": self.viewport,
            "details": self.details,
            "screenshot_path": self.screenshot_path,
        }


@dataclasses.dataclass
class ViewportPreset:
    name: str
    width: int
    height: int
    is_mobile: bool = False
    device_scale_factor: float = 1.0


DEFAULT_VIEWPORTS = [
    ViewportPreset(name="Desktop-1080p", width=1920, height=1080),
    ViewportPreset(name="Laptop-WXGA", width=1366, height=768),
    ViewportPreset(name="Tablet-Portrait", width=768, height=1024, is_mobile=True),
    ViewportPreset(name="Mobile-Viewport", width=375, height=812, is_mobile=True),
]

# Client-side JavaScript evaluation script for structural UI anomalies
CLIENT_DETECTION_SCRIPT = """
() => {
    const bugs = [];
    const docWidth = document.documentElement.clientWidth;
    const docHeight = document.documentElement.clientHeight;
    const body = document.body;

    function getUniqueSelector(el) {
        if (!(el instanceof Element)) return '';
        if (el.id) return `#${el.id}`;
        let path = [];
        while (el && el.nodeType === Node.ELEMENT_NODE) {
            let selector = el.nodeName.toLowerCase();

Interactive dry-run simulator

Select a test scenario and trigger a deterministic dry-run execution across the node topology to inspect real-time logs, compute metrics, and final output payloads.

03 · LIVE DETERMINISTIC DRY-RUN SIMULATOR
Step Through Topology Nodes & Stream Execution Telemetry

Choose a payload scenario below or click "Run Dry-Run Simulation" to step through the pipeline stages and inspect the resulting JSON output contract.

SELECT TEST SCENARIO:
NODE 01 · Route CrawlerNODE 02 · Viewport MatrixNODE 03 · DOM Geometry ProbeNODE 04 · Vision AuditorNODE 05 · Box HighlighterNODE 06 · CI Verdict Gate
// TIMESTAMPED EXECUTION TRACE CI BLOCKED · 2 HIGH DEFECTS
[00:00.320] CRAWL: Loaded /pricing across Desktop (1440w), Tablet (768w), Mobile (375w) [00:00.510] DOM_PROBE [Desktop 1440w]: 0 overflow, 0 collisions -> PASS [00:00.538] DOM_PROBE [Mobile 375w]: Detected scrollWidth (462px) > innerWidth (375px) on .pricing-card-pro [00:00.542] DOM_PROBE [Mobile 375w]: Rect.intersects() TRUE between .badge-popular and h3.plan-title [00:01.480] VISION_AUDITOR: Confirmed CRITICAL horizontal bleed (+87px) & HIGH text overlap (conf=0.95) [00:01.508] CI_GATE: Wrote visual_qa_report.json | Exiting with code 1 (Deployment blocked)

The desktop layout rendered cleanly, but on a 375px mobile viewport a fixed-width pricing card bled 87px off-screen and collided with the plan title—caught and blocked before merge.

FINAL OUTPUT PAYLOAD CONTRACT SCHEMA VALIDATED ✓
{
  "url": "https://staging.example.com/pricing",
  "viewport": "mobile_375x812",
  "status": "FAILED",
  "defects_found": [
    {
      "category": "HORIZONTAL_OVERFLOW",
      "severity": "CRITICAL",
      "selector": "div.pricing-grid > .pricing-card-pro",
      "bounding_box": {"x": 16, "y": 412, "width": 446, "height": 520},
      "overflow_px": 87
    },
    {
      "category": "TEXT_OVERLAP",
      "severity": "HIGH",
      "selector": "span.badge-popular <-> h3.plan-title",
      "confidence": 0.95
    }
  ]
}
TOTAL LATENCY 1,508 ms (3 Viewports)
COMPUTE / TOKENS 3 screenshots + DOM rect sweep
ESTIMATED RUN COST $0.00051 USD
EXECUTION MODE Deterministic Self-Hosted

Production resilience & edge-case handling

Every production system is defined by how it behaves when upstream dependencies fail, rate-limits trigger, or malformed payloads arrive at the boundary.

01 · ANIMATION & FONT FREEZING

Deterministic Frame Stabilization

Injects CSS to freeze transitions/animations and awaits document.fonts.ready + lazy-scroll completion so screenshots never capture half-rendered skeletons.

02 · DUAL DOM + VISION VERIFICATION

Geometry Math + Semantic Triage

Rect.intersects() provides exact pixel coordinates of overlapping elements, while Gemini Vision distinguishes intentional badge overlays from broken CSS collisions.

03 · BOUNDED BFS CRAWL & SANITIZATION

Same-Origin Scope & JSON Recovery

Restricts crawling to same-origin routes with configurable concurrency limits and strips malformed markdown wrappers from LLM JSON responses.

ARCHITECTURAL DECISION

Why neither DOM assertions nor Vision LLMs are sufficient alone

Pure DOM assertions cannot judge visual aesthetics or contrast legibility over background images, while pure Vision LLMs struggle to report exact CSS selectors and pixel overflow counts.

Combining Playwright's in-page getBoundingClientRect() sweep with Vision LLM confirmation gives exact CSS selectors (div.pricing-grid > .card) backed by human-like visual judgment.

SYNERGY Exact CSS selector attribution with <1% false-positive rate.

PRODUCTION PITFALL

Lazy-loaded images below the fold appear as blank gaps in full-page screenshots

Playwright's page.screenshot(full_page=True) resizes the viewport buffer without firing intersection observers cleanly, leaving loading="lazy" images unrendered.

Before taking any screenshot, the crawler runs a fast incremental scroll pass down the document and waits for all visible HTMLImageElement.complete promises to settle.

FIX Pre-capture scroll hydration eliminated false 'missing image' alerts below the fold.

Stack & specifications

  • Python 3.11+ & Playwright Async API: Multi-viewport headless Chromium orchestration
  • DOM Geometry Engine: Custom rectangle intersection, overflow, and z-index occlusion math
  • Multimodal Vision LLM: Semantic severity grading and false-positive suppression
  • GitHub Actions / CI CLI: Automated exit-code gating and annotated PNG artifact generation

Architectural takeaway

Visual QA should test layout invariants, not static pixel bitmaps. Pairing DOM bounding-box geometry with multimodal vision catches real CSS breakages while ignoring benign content updates.