← Back to Pull requests

validate: audit Maestro scheduling against the pipeline forecast #1541

Open
nuclearcat opened this pull request with 978 lines diff across 3 files
View on GitHub
nuclearcat nuclearcat commented on Jul 09, 2026 01:19 UTC
Author

kci config forecast (kernelci-core) predicts which kbuilds each tree/branch checkout should produce and which test jobs each kbuild should trigger, but nothing verified that Maestro actually scheduled them. Add a daily audit, following the same pattern as the dashboard validation (workflow + supplementary script in tests/):

tests/validate_forecast.py fetches checkout nodes old enough for their whole job tree to have settled (24h, over a 24h window), rebuilds the forecast graph with each checkout's real kernel revision, and compares expected vs actual kbuild children, then expected vs actual test jobs per (job, platform) for every kbuild that passed. A missing child is only a finding when its parent succeeded: a failed checkout produces no kbuilds and a failed kbuild triggers no test jobs, so those absences are expected.

Nodes that exist but are not forecast are classified before being flagged: externally-owned jobs (e.g. owner=qualcomm scheduling on runtimes outside our config) and runner-created children (the per-suite kselftest build nodes kbuild.py attaches) are counted as informational instead of reported as drift.

.github/workflows/validate-forecast.yml runs it daily, rewinding config/ to its git state at the start of the validated window so jobs added to the config since the checkout ran are not falsely reported as missing. kernelci-core is checked out from the branch carrying the forecast graph support until it lands upstream.

A trial run against production caught a real gap noticed by @bhcopeland, missing pull lab jobs, while the same job ran on the same platforms two days earlier.

Diff: 978 lines (+978 / -0) across 3 files Reviewer: bhcopeland Review duration: 130315m
All Vouch review confidence checks passed
Residual risk 0.08 = Change Risk (0.53) × (1 − Review Confidence (0.85)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.53 · 978 lines diff across 3 files
0.53
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.90 · 5 substantive comment(s)
0.90
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
85%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.400
Real PR Conversation Timeline
10 items
bhcopeland bhcopeland commented on code on Jul 09, 2026 07:44 UTC
Code Review
tests/validate_forecast.py:1
@@ -0,0 +1,674 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: LGPL-2.1-or-later
+#
+# Copyright (C) 2026 Collabora Limited
+# Author: Denys Fedoryshchenko <denys.f@collabora.com>
+#
+# The forecast graph walk mirrors build_forecast_graph() in
+# kernelci-core (kernelci/cli/config.py) by Guillaume Tucker and
+# Denys Fedoryshchenko, re-rooted at a real checkout node.
+"""
+Validate Maestro scheduling against the pipeline forecast.
+
+`kci config forecast` (kernelci-core) predicts, from the merged pipeline
+YAML, which kbuilds a checkout should produce and which test jobs each
+kbuild should trigger.  This script turns that prediction into a daily
+audit of what actually ran:
+
+  * fetch checkout nodes old enough for their whole job tree to have
+    settled (at least --age-hours old, over a --window-hours period);
+  * for each checkout, compare the actual kbuild child nodes against the
+    forecast built with the checkout's real kernel revision;
+  * for each kbuild that passed, compare its actual test job child nodes
+    against the forecast.
+
+A missing child is only a finding when its parent succeeded: a failed
+checkout produces no kbuilds and a failed kbuild triggers no test jobs,
+so those absences are expected and are just counted.  Nodes that exist
+but are not in the forecast are reported as unexpected (forecast or
+rules drift).
+
+Finding categories (actionable, in `findings`):
+  * MISSING_KBUILD    - checkout passed, forecast expects the kbuild,
+                        no such node exists.
+  * MISSING_JOB       - kbuild passed (or checkout passed for jobs
+                        triggered directly by the checkout), forecast
+                        expects the job, no such node exists.
+  * UNEXPECTED_KBUILD - kbuild node exists but the forecast does not
+                        predict it.
+  * UNEXPECTED_JOB    - job node exists but the forecast does not
+                        predict it (e.g. rules or runtime drift).
+
+Informational (counted, listed in the JSON report only):
+  * external nodes      - owner differs from the checkout owner:
+                          external submitters (e.g. qualcomm) schedule
+                          their own jobs under Maestro kbuilds, outside
+                          this pipeline's forecast.
+  * non-scheduler nodes - no scheduler entry creates this job from this
+                          parent: nodes created dynamically by job
+                          runners, e.g. the per-suite kselftest build
+                          nodes kbuild.py attaches to kbuilds.
+
+Validating old checkouts against today's config flags jobs added to the
+config since then as MISSING; run against the pipeline config as it was
+at the start of the window (the GitHub workflow does this) to avoid it.
+
+Exit status is 1 when --fail-on-miss is given and any MISSING_* finding
+was recorded.
+"""
+
+import argparse
+import datetime
+import json
+import os
+import sys
+
+import requests
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from validate_yaml import merge_files  # noqa: E402
+
+MISSING_CATEGORIES = ("MISSING_KBUILD", "MISSING_JOB")
+UNEXPECTED_CATEGORIES = ("UNEXPECTED_KBUILD", "UNEXPECTED_JOB")
+
+
+def import_forecast(core_dir):
+    """Import the forecast entry evaluator from kernelci-core"""
+    if core_dir:
+        sys.path.insert(0, core_dir)
+    try:
+        from kernelci.cli.config import evaluate_forecast_entry
+    except ImportError as exc:
+        sys.exit(
+            "Cannot import evaluate_forecast_entry from kernelci-core: "
+            f"{exc}\n"
+            "Install a kernelci-core tree with forecast graph support "
+            "and point --core-dir at it (or add it to PYTHONPATH)."
+        )
+    return evaluate_forecast_entry
+
+
+class MaestroAPI:
+    """Read-only Maestro API client with pagination"""
+
+    def __init__(self, url, timeout=60, page_size=1000):
+        self.base = url.rstrip("/")
+        self.timeout = timeout
+        self.page_size = page_size
+        self.session = requests.Session()
+        adapter = requests.adapters.HTTPAdapter(
+            max_retries=requests.adapters.Retry(
+                total=3, backoff_factor=2, status_forcelist=[500, 502, 504]
+            )
+        )
+        self.session.mount("http://", adapter)
+        self.session.mount("https://", adapter)
+
+    def nodes(self, **filters):
+        """Fetch all nodes matching the filters, following pagination"""
+        items = []
+        offset = 0
+        while True:
+            params = dict(filters)
+            params.update({"limit": self.page_size, "offset": offset})
+            resp = self.session.get(
+                f"{self.base}/latest/nodes",
+                params=params,
+                timeout=self.timeout,
+            )
+            resp.raise_for_status()
+            data = resp.json()
+            page = data.get("items", [])
+            items.extend(page)
+            offset += len(page)
+            if not page or offset >= data.get("total", 0):
+                break
+        return items
+
+
+def event_source_name(event):
+    """Job name whose nodes feed a scheduler entry (checkout for root)"""
+    if event.get("kind") == "checkout":
+        return event.get("name", "checkout")
+    return event.get("name")
+
+
+def node_signature(node):
+    return json.dumps(node, sort_keys=True)
+
+
+def build_expected_graph(evaluate_entry, merged_data, checkout_cfg, root_node):
+    """Build the forecast graph rooted at a real checkout node.
+
+    Returns {source job name: {(child name, platform, kind, runtime)}}
+    where 'checkout' is the root source.  A platform of None means the
+    scheduler entry has no platform list (e.g. docker/kubernetes jobs).
+    """
+    nodes = {"checkout": [root_node]}
+    signatures = {"checkout": {node_signature(root_node)}}
+    edges = {}
+    scheduler_entries = merged_data.get("scheduler", [])
+
+    changed = True
+    while changed:
+        changed = False
+        for entry in scheduler_entries:
+            source = event_source_name(entry.get("event", {}))
+            if not source:
+                continue
+            for input_node in list(nodes.get(source, [])):
+                children, _ = evaluate_entry(
+                    merged_data, entry, input_node, checkout_cfg
+                )
+                for child in children:
+                    name = child["name"]
+                    edges.setdefault(source, set()).add(
+                        (
+                            name,
+                            child["data"].get("platform"),
+                            child["kind"],
+                            child["data"].get("runtime"),
+                        )
+                    )
+                    sig = node_signature(child)
+                    sigs = signatures.setdefault(name, set())
+                    if sig in sigs:
+                        continue
+                    sigs.add(sig)
+                    nodes.setdefault(name, []).append(child)
+                    changed = True
+
+    return edges
+
+
+def scheduler_pairs(merged_data):
+    """Set of (source job name, job name) pairs the scheduler can create.
+
+    Used to tell scheduler-created children apart from nodes attached
+    dynamically by job runners (e.g. per-suite kselftest build nodes).
+    """
+    pairs = set()
+    for entry in merged_data.get("scheduler", []):
+        source = event_source_name(entry.get("event", {}))
+        if source and entry.get("job"):
+            pairs.add((source, entry["job"]))
+    return pairs
+
+
+def checkout_build_config(merged_data, tree, branch):
+    """Merge the build_configs entries matching a tree/branch.
+
+    Multiple entries can point at the same tree/branch with different
+    architecture filters; the forecast should expect the union.
+    """
+    matches = [
+        cfg
+        for cfg in merged_data.get("build_configs", {}).values()
+        if cfg.get("tree") == tree and cfg.get("branch") == branch
+    ]
+    if not matches:
+        return None
+    architectures = set()
+    for cfg in matches:
+        if not cfg.get("architectures"):
+            architectures = None
+            break
+        architectures.update(cfg["architectures"])
+    merged = dict(matches[0])
+    merged["architectures"] = sorted(architectures) if architectures else None
+    return merged
+
+
+def match_children(expected, actual):
+    """Compare forecast {(name, platform): runtime} with actual children.
+
+    A platform of None means any platform.  Returns (missing,
+    unexpected) where missing is a list of (name, platform) keys and
+    unexpected a list of node dicts.
+    """
+    actual_pairs = [
+        (node.get("name"), node.get("data", {}).get("platform"), node)
+        for node in actual
+    ]
+    missing = []
+    for name, platform in sorted(
+        expected, key=lambda item: (item[0], item[1] or "")
+    ):
+        if platform is None:
+            found = any(a_name == name for a_name, _, _ in actual_pairs)
+        else:
+            found = any(
+                a_name == name and a_platform == platform
+                for a_name, a_platform, _ in actual_pairs
+            )
+        if not found:
+            missing.append((name, platform))
+
+    expected_names = {name for name, platform in expected if platform is None}
+    unexpected = [
+        node
+        for a_name, a_platform, node in actual_pairs
+        if a_name not in expected_names and (a_name, a_platform) not in expected
+    ]
+    return missing, unexpected
+
+
+def node_ok(node):
+    return node.get("result") == "pass"
+
+
+def node_settled(node):
+    return node.get("state") == "done"
+
+
+def describe_node(node):
+    data = node.get("data", {})
+    parts = [f"{node.get('name')} ({node.get('id')})"]
+    if data.get("platform"):
+        parts.append(f"platform={data['platform']}")
+    if data.get("runtime"):
+        parts.append(f"runtime={data['runtime']}")
+    if node.get("owner"):
+        parts.append(f"owner={node['owner']}")
+    parts.append(f"result={node.get('result')}")
+    return " ".join(parts)
+
+
+def _checkout_skip_reason(merged_data, checkout):
+    """Reason not to validate a checkout at all, or None"""
+    if checkout.get("jobfilter") or checkout.get("platform_filter"):
+        return "custom checkout with job/platform filter"
+    revision = checkout.get("data", {}).get("kernel_revision", {})
+    version = revision.get("version") or {}
+    if version.get("version") is None or version.get("patchlevel") is None:
+        return "checkout has no parsed kernel version"
+    if not checkout_build_config(
+        merged_data, revision.get("tree"), revision.get("branch")
+    ):
+        return "no build_config for this tree/branch"
+    return None
+
+
+def _checkout_forecast(merged_data, evaluate_entry, checkout, graph_cache):
+    """Forecast edges for a checkout, cached per tree/branch/version"""
+    revision = checkout["data"]["kernel_revision"]
+    version = revision["version"]
+    cache_key = (
+        revision["tree"],
+        revision["branch"],
+        version["version"],
+        version["patchlevel"],
+    )
+    edges = graph_cache.get(cache_key)
+    if edges is None:
+        build_config = checkout_build_config(
+            merged_data, revision["tree"], revision["branch"]
+        )
+        root_node = {
+            "kind": "checkout",
+            "name": "checkout",
+            "data": {"kernel_revision": revision},
+        }
+        edges = build_expected_graph(
+            evaluate_entry, merged_data, build_config, root_node
+        )
+        graph_cache[cache_key] = edges
+    return edges
+
+
+def _fetch_children(api, checkout):
+    """Fetch kbuild children and all job nodes grouped by parent ID"""
+    revision = checkout["data"]["kernel_revision"]
+    filters = {
+        "data.kernel_revision.commit": revision["commit"],
+        "data.kernel_revision.tree": revision["tree"],
+        "data.kernel_revision.branch": revision["branch"],
+    }
+    kbuilds = [
+        node
+        for node in api.nodes(kind="kbuild", **filters)
+        if node.get("parent") == checkout["id"]
+    ]
+    jobs_by_parent = {}
+    for job in api.nodes(kind="job", **filters):
+        jobs_by_parent.setdefault(job.get("parent"), []).append(job)
+    return kbuilds, jobs_by_parent
+
+
+def validate_checkout(
+    api, merged_data, evaluate_entry, pairs, checkout, graph_cache
+):
+    """Validate one checkout node; returns a per-checkout report dict"""
+    revision = checkout.get("data", {}).get("kernel_revision", {})
+    tree = revision.get("tree")
+    branch = revision.get("branch")
+    commit = revision.get("commit")
+    report = {
+        "id": checkout.get("id"),
+        "tree": tree,
+        "branch": branch,
+        "commit": commit,
+        "state": checkout.get("state"),
+        "result": checkout.get("result"),
+        "owner": checkout.get("owner"),
+        "skipped": None,
+        "findings": [],
+        "external": [],
+        "non_scheduler": [],
+        "skipped_failed_kbuilds": [],
+        "unsettled_kbuilds": [],
+    }
+
+    report["skipped"] = _checkout_skip_reason(merged_data, checkout)
+    if report["skipped"]:
+        return report
+
+    edges = _checkout_forecast(
+        merged_data, evaluate_entry, checkout, graph_cache
+    )
+    kbuilds, jobs_by_parent = _fetch_children(api, checkout)
+
+    expected_root = edges.get("checkout", set())
+    expected_kbuilds = {
+        (name, None): runtime
+        for name, _, kind, runtime in expected_root
+        if kind == "kbuild"
+    }
+    expected_root_jobs = {
+        (name, platform): runtime
+        for name, platform, kind, runtime in expected_root
+        if kind == "job"
+    }
+
+    missing, unexpected = match_children(expected_kbuilds, kbuilds)
+    if node_ok(checkout):
+        for key in missing:
+            name, _ = key
+            report["findings"].append(
+                {
+                    "category": "MISSING_KBUILD",
+                    "parent": checkout["id"],
+                    "parent_name": "checkout",
+                    "job": name,
+                    "platform": None,
+                    "runtime": expected_kbuilds[key],
+                }
+            )
+    for node in unexpected:
+        _report_unexpected(report, pairs, node, "checkout", "UNEXPECTED_KBUILD")
+
+    root_jobs = jobs_by_parent.get(checkout["id"], [])
+    _validate_jobs(
+        report,
+        pairs,
+        expected_root_jobs,
+        root_jobs,
+        source_name="checkout",
+        parent_id=checkout["id"],
+        parent_ok=node_ok(checkout),
+    )
+
+    for kbuild in kbuilds:
+        expected_jobs = {
+            (name, platform): runtime
+            for name, platform, kind, runtime in edges.get(
+                kbuild.get("name"), set()
+            )
+            if kind == "job"
+        }
+        actual_jobs = jobs_by_parent.get(kbuild.get("id"), [])
+        if not node_settled(kbuild):
+            report["unsettled_kbuilds"].append(describe_node(kbuild))
+            continue
+        if not node_ok(kbuild):
+            # A failed kbuild legitimately triggers nothing; only count it.
+            report["skipped_failed_kbuilds"].append(describe_node(kbuild))

So we will surpress jobs that won't run, but will incomplete builds also be dropped? Might be worth a seperate counter for the other uses cases than just their children.

bhcopeland bhcopeland commented on code on Jul 09, 2026 07:44 UTC
Code Review
tests/validate_forecast.py:1
@@ -0,0 +1,674 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: LGPL-2.1-or-later
+#
+# Copyright (C) 2026 Collabora Limited
+# Author: Denys Fedoryshchenko <denys.f@collabora.com>
+#
+# The forecast graph walk mirrors build_forecast_graph() in
+# kernelci-core (kernelci/cli/config.py) by Guillaume Tucker and
+# Denys Fedoryshchenko, re-rooted at a real checkout node.
+"""
+Validate Maestro scheduling against the pipeline forecast.
+
+`kci config forecast` (kernelci-core) predicts, from the merged pipeline
+YAML, which kbuilds a checkout should produce and which test jobs each
+kbuild should trigger.  This script turns that prediction into a daily
+audit of what actually ran:
+
+  * fetch checkout nodes old enough for their whole job tree to have
+    settled (at least --age-hours old, over a --window-hours period);
+  * for each checkout, compare the actual kbuild child nodes against the
+    forecast built with the checkout's real kernel revision;
+  * for each kbuild that passed, compare its actual test job child nodes
+    against the forecast.
+
+A missing child is only a finding when its parent succeeded: a failed
+checkout produces no kbuilds and a failed kbuild triggers no test jobs,
+so those absences are expected and are just counted.  Nodes that exist
+but are not in the forecast are reported as unexpected (forecast or
+rules drift).
+
+Finding categories (actionable, in `findings`):
+  * MISSING_KBUILD    - checkout passed, forecast expects the kbuild,
+                        no such node exists.
+  * MISSING_JOB       - kbuild passed (or checkout passed for jobs
+                        triggered directly by the checkout), forecast
+                        expects the job, no such node exists.
+  * UNEXPECTED_KBUILD - kbuild node exists but the forecast does not
+                        predict it.
+  * UNEXPECTED_JOB    - job node exists but the forecast does not
+                        predict it (e.g. rules or runtime drift).
+
+Informational (counted, listed in the JSON report only):
+  * external nodes      - owner differs from the checkout owner:
+                          external submitters (e.g. qualcomm) schedule
+                          their own jobs under Maestro kbuilds, outside
+                          this pipeline's forecast.
+  * non-scheduler nodes - no scheduler entry creates this job from this
+                          parent: nodes created dynamically by job
+                          runners, e.g. the per-suite kselftest build
+                          nodes kbuild.py attaches to kbuilds.
+
+Validating old checkouts against today's config flags jobs added to the
+config since then as MISSING; run against the pipeline config as it was
+at the start of the window (the GitHub workflow does this) to avoid it.
+
+Exit status is 1 when --fail-on-miss is given and any MISSING_* finding
+was recorded.
+"""
+
+import argparse
+import datetime
+import json
+import os
+import sys
+
+import requests
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from validate_yaml import merge_files  # noqa: E402
+
+MISSING_CATEGORIES = ("MISSING_KBUILD", "MISSING_JOB")
+UNEXPECTED_CATEGORIES = ("UNEXPECTED_KBUILD", "UNEXPECTED_JOB")
+
+
+def import_forecast(core_dir):
+    """Import the forecast entry evaluator from kernelci-core"""
+    if core_dir:
+        sys.path.insert(0, core_dir)
+    try:
+        from kernelci.cli.config import evaluate_forecast_entry
+    except ImportError as exc:
+        sys.exit(
+            "Cannot import evaluate_forecast_entry from kernelci-core: "
+            f"{exc}\n"
+            "Install a kernelci-core tree with forecast graph support "
+            "and point --core-dir at it (or add it to PYTHONPATH)."
+        )
+    return evaluate_forecast_entry
+
+
+class MaestroAPI:
+    """Read-only Maestro API client with pagination"""
+
+    def __init__(self, url, timeout=60, page_size=1000):
+        self.base = url.rstrip("/")
+        self.timeout = timeout
+        self.page_size = page_size
+        self.session = requests.Session()
+        adapter = requests.adapters.HTTPAdapter(
+            max_retries=requests.adapters.Retry(
+                total=3, backoff_factor=2, status_forcelist=[500, 502, 504]
+            )
+        )
+        self.session.mount("http://", adapter)
+        self.session.mount("https://", adapter)
+
+    def nodes(self, **filters):
+        """Fetch all nodes matching the filters, following pagination"""
+        items = []
+        offset = 0
+        while True:
+            params = dict(filters)
+            params.update({"limit": self.page_size, "offset": offset})
+            resp = self.session.get(
+                f"{self.base}/latest/nodes",
+                params=params,
+                timeout=self.timeout,
+            )
+            resp.raise_for_status()
+            data = resp.json()
+            page = data.get("items", [])
+            items.extend(page)
+            offset += len(page)
+            if not page or offset >= data.get("total", 0):
+                break
+        return items
+
+
+def event_source_name(event):
+    """Job name whose nodes feed a scheduler entry (checkout for root)"""
+    if event.get("kind") == "checkout":
+        return event.get("name", "checkout")
+    return event.get("name")
+
+
+def node_signature(node):
+    return json.dumps(node, sort_keys=True)
+
+
+def build_expected_graph(evaluate_entry, merged_data, checkout_cfg, root_node):
+    """Build the forecast graph rooted at a real checkout node.
+
+    Returns {source job name: {(child name, platform, kind, runtime)}}
+    where 'checkout' is the root source.  A platform of None means the
+    scheduler entry has no platform list (e.g. docker/kubernetes jobs).
+    """
+    nodes = {"checkout": [root_node]}
+    signatures = {"checkout": {node_signature(root_node)}}
+    edges = {}
+    scheduler_entries = merged_data.get("scheduler", [])
+
+    changed = True
+    while changed:
+        changed = False
+        for entry in scheduler_entries:
+            source = event_source_name(entry.get("event", {}))
+            if not source:
+                continue
+            for input_node in list(nodes.get(source, [])):
+                children, _ = evaluate_entry(
+                    merged_data, entry, input_node, checkout_cfg
+                )
+                for child in children:
+                    name = child["name"]
+                    edges.setdefault(source, set()).add(
+                        (
+                            name,
+                            child["data"].get("platform"),
+                            child["kind"],
+                            child["data"].get("runtime"),
+                        )
+                    )
+                    sig = node_signature(child)
+                    sigs = signatures.setdefault(name, set())
+                    if sig in sigs:
+                        continue
+                    sigs.add(sig)
+                    nodes.setdefault(name, []).append(child)
+                    changed = True
+
+    return edges
+
+
+def scheduler_pairs(merged_data):
+    """Set of (source job name, job name) pairs the scheduler can create.
+
+    Used to tell scheduler-created children apart from nodes attached
+    dynamically by job runners (e.g. per-suite kselftest build nodes).
+    """
+    pairs = set()
+    for entry in merged_data.get("scheduler", []):
+        source = event_source_name(entry.get("event", {}))
+        if source and entry.get("job"):
+            pairs.add((source, entry["job"]))
+    return pairs
+
+
+def checkout_build_config(merged_data, tree, branch):
+    """Merge the build_configs entries matching a tree/branch.
+
+    Multiple entries can point at the same tree/branch with different
+    architecture filters; the forecast should expect the union.
+    """
+    matches = [
+        cfg
+        for cfg in merged_data.get("build_configs", {}).values()
+        if cfg.get("tree") == tree and cfg.get("branch") == branch
+    ]
+    if not matches:
+        return None
+    architectures = set()
+    for cfg in matches:
+        if not cfg.get("architectures"):
+            architectures = None
+            break
+        architectures.update(cfg["architectures"])
+    merged = dict(matches[0])
+    merged["architectures"] = sorted(architectures) if architectures else None
+    return merged
+
+
+def match_children(expected, actual):
+    """Compare forecast {(name, platform): runtime} with actual children.
+
+    A platform of None means any platform.  Returns (missing,
+    unexpected) where missing is a list of (name, platform) keys and
+    unexpected a list of node dicts.
+    """
+    actual_pairs = [
+        (node.get("name"), node.get("data", {}).get("platform"), node)
+        for node in actual
+    ]
+    missing = []
+    for name, platform in sorted(
+        expected, key=lambda item: (item[0], item[1] or "")
+    ):
+        if platform is None:
+            found = any(a_name == name for a_name, _, _ in actual_pairs)
+        else:
+            found = any(
+                a_name == name and a_platform == platform
+                for a_name, a_platform, _ in actual_pairs
+            )
+        if not found:
+            missing.append((name, platform))
+
+    expected_names = {name for name, platform in expected if platform is None}
+    unexpected = [
+        node
+        for a_name, a_platform, node in actual_pairs
+        if a_name not in expected_names and (a_name, a_platform) not in expected
+    ]
+    return missing, unexpected
+
+
+def node_ok(node):
+    return node.get("result") == "pass"
+
+
+def node_settled(node):
+    return node.get("state") == "done"
+
+
+def describe_node(node):
+    data = node.get("data", {})
+    parts = [f"{node.get('name')} ({node.get('id')})"]
+    if data.get("platform"):
+        parts.append(f"platform={data['platform']}")
+    if data.get("runtime"):
+        parts.append(f"runtime={data['runtime']}")
+    if node.get("owner"):
+        parts.append(f"owner={node['owner']}")
+    parts.append(f"result={node.get('result')}")
+    return " ".join(parts)
+
+
+def _checkout_skip_reason(merged_data, checkout):
+    """Reason not to validate a checkout at all, or None"""
+    if checkout.get("jobfilter") or checkout.get("platform_filter"):
+        return "custom checkout with job/platform filter"
+    revision = checkout.get("data", {}).get("kernel_revision", {})
+    version = revision.get("version") or {}
+    if version.get("version") is None or version.get("patchlevel") is None:
+        return "checkout has no parsed kernel version"
+    if not checkout_build_config(
+        merged_data, revision.get("tree"), revision.get("branch")
+    ):
+        return "no build_config for this tree/branch"
+    return None
+
+
+def _checkout_forecast(merged_data, evaluate_entry, checkout, graph_cache):
+    """Forecast edges for a checkout, cached per tree/branch/version"""
+    revision = checkout["data"]["kernel_revision"]
+    version = revision["version"]
+    cache_key = (
+        revision["tree"],
+        revision["branch"],
+        version["version"],
+        version["patchlevel"],
+    )
+    edges = graph_cache.get(cache_key)
+    if edges is None:
+        build_config = checkout_build_config(
+            merged_data, revision["tree"], revision["branch"]
+        )
+        root_node = {
+            "kind": "checkout",
+            "name": "checkout",
+            "data": {"kernel_revision": revision},
+        }
+        edges = build_expected_graph(
+            evaluate_entry, merged_data, build_config, root_node
+        )
+        graph_cache[cache_key] = edges
+    return edges
+
+
+def _fetch_children(api, checkout):
+    """Fetch kbuild children and all job nodes grouped by parent ID"""
+    revision = checkout["data"]["kernel_revision"]
+    filters = {
+        "data.kernel_revision.commit": revision["commit"],
+        "data.kernel_revision.tree": revision["tree"],
+        "data.kernel_revision.branch": revision["branch"],
+    }
+    kbuilds = [
+        node
+        for node in api.nodes(kind="kbuild", **filters)
+        if node.get("parent") == checkout["id"]
+    ]
+    jobs_by_parent = {}
+    for job in api.nodes(kind="job", **filters):
+        jobs_by_parent.setdefault(job.get("parent"), []).append(job)
+    return kbuilds, jobs_by_parent
+
+
+def validate_checkout(
+    api, merged_data, evaluate_entry, pairs, checkout, graph_cache
+):
+    """Validate one checkout node; returns a per-checkout report dict"""
+    revision = checkout.get("data", {}).get("kernel_revision", {})
+    tree = revision.get("tree")
+    branch = revision.get("branch")
+    commit = revision.get("commit")
+    report = {
+        "id": checkout.get("id"),
+        "tree": tree,
+        "branch": branch,
+        "commit": commit,
+        "state": checkout.get("state"),
+        "result": checkout.get("result"),
+        "owner": checkout.get("owner"),
+        "skipped": None,
+        "findings": [],
+        "external": [],
+        "non_scheduler": [],
+        "skipped_failed_kbuilds": [],
+        "unsettled_kbuilds": [],
+    }
+
+    report["skipped"] = _checkout_skip_reason(merged_data, checkout)
+    if report["skipped"]:
+        return report
+
+    edges = _checkout_forecast(
+        merged_data, evaluate_entry, checkout, graph_cache
+    )
+    kbuilds, jobs_by_parent = _fetch_children(api, checkout)
+
+    expected_root = edges.get("checkout", set())
+    expected_kbuilds = {
+        (name, None): runtime
+        for name, _, kind, runtime in expected_root
+        if kind == "kbuild"
+    }
+    expected_root_jobs = {
+        (name, platform): runtime
+        for name, platform, kind, runtime in expected_root
+        if kind == "job"
+    }
+
+    missing, unexpected = match_children(expected_kbuilds, kbuilds)
+    if node_ok(checkout):
+        for key in missing:
+            name, _ = key
+            report["findings"].append(
+                {
+                    "category": "MISSING_KBUILD",
+                    "parent": checkout["id"],
+                    "parent_name": "checkout",
+                    "job": name,
+                    "platform": None,
+                    "runtime": expected_kbuilds[key],
+                }
+            )
+    for node in unexpected:
+        _report_unexpected(report, pairs, node, "checkout", "UNEXPECTED_KBUILD")
+
+    root_jobs = jobs_by_parent.get(checkout["id"], [])
+    _validate_jobs(
+        report,
+        pairs,
+        expected_root_jobs,
+        root_jobs,
+        source_name="checkout",
+        parent_id=checkout["id"],
+        parent_ok=node_ok(checkout),
+    )
+
+    for kbuild in kbuilds:

I think this will miss 3 levels down, as it will check only its children groups.

I.e.

  # Execute nipa-update on the blktests-ddp-x86 node
  # complete with the blktests-ddp-x86 event
  - job: nipa-update
    event:
      <<: *job-event
      name: blktests-ddp-x86
    runtime:
      type: shell

bhcopeland bhcopeland commented on code on Jul 09, 2026 07:44 UTC
Code Review
.github/workflows/validate-forecast.yml:1
@@ -0,0 +1,93 @@
+name: Validate Maestro against forecast
+
+on:
+  schedule:
+    # Run daily at 07:00 UTC, after the dashboard validation.
+    - cron: '0 7 * * *'
+  workflow_dispatch:
+    inputs:
+      age_hours:
+        description: Only validate checkouts at least this old
+        required: false
+        default: '24'
+      window_hours:
+        description: Length of the validated period before age_hours
+        required: false
+        default: '24'
+      tree:
+        description: Only validate this tree
+        required: false
+        default: ''
+
+permissions:
+  contents: read
+
+concurrency:
+  group: validate-forecast
+  cancel-in-progress: false
+
+jobs:
+  validate:
+    runs-on: ubuntu-slim
+
+    steps:
+      - name: Check out source code
+        uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
+        with:
+          # Full history so the config can be rewound to the window start.
+          fetch-depth: 0
+
+      - name: Rewind config to the start of the validated window
+        # Checkouts up to (age + window) hours old are validated; using
+        # today's config would flag jobs added since then as MISSING.
+        env:
+          KCI_AGE_HOURS: ${{ github.event.inputs.age_hours || '24' }}
+          KCI_WINDOW_HOURS: ${{ github.event.inputs.window_hours || '24' }}
+        run: |
+          hours=$(python3 -c "print(int(float('${KCI_AGE_HOURS}') + float('${KCI_WINDOW_HOURS}')))")
+          ref=$(git rev-list -1 --before="${hours} hours ago" HEAD)
+          if [ -n "$ref" ]; then
+            echo "Using config from $ref ($(git log -1 --format='%ci %s' "$ref"))"
+            git checkout "$ref" -- config
+          else
+            echo "No commit older than ${hours}h; keeping HEAD config"
+          fi
+
+      - name: Check out kernelci-core (forecast tool)
+        uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
+        with:
+          # TODO: switch to kernelci/kernelci-core@main once the forecast
+          # graph support (evaluate_forecast_entry) lands upstream.
+          repository: nuclearcat/kernelci-core
+          ref: codex/forecast-missing-job-debug
+          path: kernelci-core
+
+      - name: Set up Python
+        uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
+        with:
+          python-version: '3.13'
+          cache: 'pip'
+
+      - name: Install dependencies
+        # Only what `import kernelci.cli.config` pulls in, plus the
+        # validator's own deps; the heavy kernelci-core extras (azure,
+        # kubernetes, docker) are not needed for the forecast code.
+        run: |
+          python -m pip install --upgrade pip
+          python -m pip install click requests cloudevents toml pyyaml jinja2
+
+      - name: Validate scheduled jobs against forecast

We should probably have a check here so MISSING_KBUILD does spam. I think for example gcc-15 changes, will cause this to be quite noisey until we get prod up-to-date. And in this setting its merged, but not yet deployed. We probably want to catch this differently, rather than noticing its a scheduler bug or something.

bhcopeland bhcopeland commented on code on Jul 09, 2026 07:44 UTC
Code Review
tests/validate_forecast.py:1
@@ -0,0 +1,674 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: LGPL-2.1-or-later
+#
+# Copyright (C) 2026 Collabora Limited
+# Author: Denys Fedoryshchenko <denys.f@collabora.com>
+#
+# The forecast graph walk mirrors build_forecast_graph() in
+# kernelci-core (kernelci/cli/config.py) by Guillaume Tucker and
+# Denys Fedoryshchenko, re-rooted at a real checkout node.
+"""
+Validate Maestro scheduling against the pipeline forecast.
+
+`kci config forecast` (kernelci-core) predicts, from the merged pipeline
+YAML, which kbuilds a checkout should produce and which test jobs each
+kbuild should trigger.  This script turns that prediction into a daily
+audit of what actually ran:
+
+  * fetch checkout nodes old enough for their whole job tree to have
+    settled (at least --age-hours old, over a --window-hours period);
+  * for each checkout, compare the actual kbuild child nodes against the
+    forecast built with the checkout's real kernel revision;
+  * for each kbuild that passed, compare its actual test job child nodes
+    against the forecast.
+
+A missing child is only a finding when its parent succeeded: a failed
+checkout produces no kbuilds and a failed kbuild triggers no test jobs,
+so those absences are expected and are just counted.  Nodes that exist
+but are not in the forecast are reported as unexpected (forecast or
+rules drift).
+
+Finding categories (actionable, in `findings`):
+  * MISSING_KBUILD    - checkout passed, forecast expects the kbuild,
+                        no such node exists.
+  * MISSING_JOB       - kbuild passed (or checkout passed for jobs
+                        triggered directly by the checkout), forecast
+                        expects the job, no such node exists.
+  * UNEXPECTED_KBUILD - kbuild node exists but the forecast does not
+                        predict it.
+  * UNEXPECTED_JOB    - job node exists but the forecast does not
+                        predict it (e.g. rules or runtime drift).
+
+Informational (counted, listed in the JSON report only):
+  * external nodes      - owner differs from the checkout owner:
+                          external submitters (e.g. qualcomm) schedule
+                          their own jobs under Maestro kbuilds, outside
+                          this pipeline's forecast.
+  * non-scheduler nodes - no scheduler entry creates this job from this
+                          parent: nodes created dynamically by job
+                          runners, e.g. the per-suite kselftest build
+                          nodes kbuild.py attaches to kbuilds.
+
+Validating old checkouts against today's config flags jobs added to the
+config since then as MISSING; run against the pipeline config as it was
+at the start of the window (the GitHub workflow does this) to avoid it.
+
+Exit status is 1 when --fail-on-miss is given and any MISSING_* finding
+was recorded.
+"""
+
+import argparse
+import datetime
+import json
+import os
+import sys
+
+import requests
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from validate_yaml import merge_files  # noqa: E402
+
+MISSING_CATEGORIES = ("MISSING_KBUILD", "MISSING_JOB")
+UNEXPECTED_CATEGORIES = ("UNEXPECTED_KBUILD", "UNEXPECTED_JOB")
+
+
+def import_forecast(core_dir):
+    """Import the forecast entry evaluator from kernelci-core"""
+    if core_dir:
+        sys.path.insert(0, core_dir)
+    try:
+        from kernelci.cli.config import evaluate_forecast_entry
+    except ImportError as exc:
+        sys.exit(
+            "Cannot import evaluate_forecast_entry from kernelci-core: "
+            f"{exc}\n"
+            "Install a kernelci-core tree with forecast graph support "
+            "and point --core-dir at it (or add it to PYTHONPATH)."
+        )
+    return evaluate_forecast_entry
+
+
+class MaestroAPI:
+    """Read-only Maestro API client with pagination"""
+
+    def __init__(self, url, timeout=60, page_size=1000):
+        self.base = url.rstrip("/")
+        self.timeout = timeout
+        self.page_size = page_size
+        self.session = requests.Session()
+        adapter = requests.adapters.HTTPAdapter(
+            max_retries=requests.adapters.Retry(
+                total=3, backoff_factor=2, status_forcelist=[500, 502, 504]

We should probably add the other status codes here, 503, and 429.

bhcopeland bhcopeland commented on code on Jul 09, 2026 07:44 UTC
Code Review
.github/workflows/validate-forecast.yml:1
@@ -0,0 +1,93 @@
+name: Validate Maestro against forecast
+
+on:
+  schedule:
+    # Run daily at 07:00 UTC, after the dashboard validation.
+    - cron: '0 7 * * *'
+  workflow_dispatch:
+    inputs:
+      age_hours:
+        description: Only validate checkouts at least this old
+        required: false
+        default: '24'
+      window_hours:
+        description: Length of the validated period before age_hours
+        required: false
+        default: '24'
+      tree:
+        description: Only validate this tree
+        required: false
+        default: ''
+
+permissions:
+  contents: read
+
+concurrency:
+  group: validate-forecast
+  cancel-in-progress: false
+
+jobs:
+  validate:
+    runs-on: ubuntu-slim
+
+    steps:
+      - name: Check out source code
+        uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
+        with:
+          # Full history so the config can be rewound to the window start.
+          fetch-depth: 0
+
+      - name: Rewind config to the start of the validated window
+        # Checkouts up to (age + window) hours old are validated; using
+        # today's config would flag jobs added since then as MISSING.
+        env:
+          KCI_AGE_HOURS: ${{ github.event.inputs.age_hours || '24' }}
+          KCI_WINDOW_HOURS: ${{ github.event.inputs.window_hours || '24' }}
+        run: |
+          hours=$(python3 -c "print(int(float('${KCI_AGE_HOURS}') + float('${KCI_WINDOW_HOURS}')))")
+          ref=$(git rev-list -1 --before="${hours} hours ago" HEAD)
+          if [ -n "$ref" ]; then
+            echo "Using config from $ref ($(git log -1 --format='%ci %s' "$ref"))"
+            git checkout "$ref" -- config

We probably want to add rm -rf config before this. Also up in line 3 we have python3 commands going on, but setup python is down on like 65. I would put setup python at the top before these steps. (or we use some sort of awk command here.

bhcopeland bhcopeland commented on code on Jul 09, 2026 07:44 UTC
Code Review
.github/workflows/validate-forecast.yml:1
@@ -0,0 +1,93 @@
+name: Validate Maestro against forecast
+
+on:
+  schedule:
+    # Run daily at 07:00 UTC, after the dashboard validation.
+    - cron: '0 7 * * *'
+  workflow_dispatch:
+    inputs:
+      age_hours:
+        description: Only validate checkouts at least this old
+        required: false
+        default: '24'
+      window_hours:
+        description: Length of the validated period before age_hours
+        required: false
+        default: '24'
+      tree:
+        description: Only validate this tree
+        required: false
+        default: ''
+
+permissions:
+  contents: read
+
+concurrency:
+  group: validate-forecast
+  cancel-in-progress: false
+
+jobs:
+  validate:
+    runs-on: ubuntu-slim
+
+    steps:
+      - name: Check out source code
+        uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
+        with:
+          # Full history so the config can be rewound to the window start.
+          fetch-depth: 0
+
+      - name: Rewind config to the start of the validated window
+        # Checkouts up to (age + window) hours old are validated; using
+        # today's config would flag jobs added since then as MISSING.
+        env:
+          KCI_AGE_HOURS: ${{ github.event.inputs.age_hours || '24' }}
+          KCI_WINDOW_HOURS: ${{ github.event.inputs.window_hours || '24' }}
+        run: |
+          hours=$(python3 -c "print(int(float('${KCI_AGE_HOURS}') + float('${KCI_WINDOW_HOURS}')))")
+          ref=$(git rev-list -1 --before="${hours} hours ago" HEAD)
+          if [ -n "$ref" ]; then
+            echo "Using config from $ref ($(git log -1 --format='%ci %s' "$ref"))"
+            git checkout "$ref" -- config
+          else
+            echo "No commit older than ${hours}h; keeping HEAD config"
+          fi
+
+      - name: Check out kernelci-core (forecast tool)
+        uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
+        with:
+          # TODO: switch to kernelci/kernelci-core@main once the forecast
+          # graph support (evaluate_forecast_entry) lands upstream.
+          repository: nuclearcat/kernelci-core
+          ref: codex/forecast-missing-job-debug

I think we should pin this to a commit sha, until it lands upstream, rathar than a outside repo

bhcopeland bhcopeland commented on Jul 09, 2026 07:48 UTC
Contributor

Thanks for putting this together @nuclearcat this is a good approach to catch this going forward. I wonder if we should add something around the if: failure() step (like create github issue, or some sort of of discord message)?

nuclearcat nuclearcat commented on code on Jul 09, 2026 08:05 UTC
Code Review
tests/validate_forecast.py:1
@@ -0,0 +1,674 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: LGPL-2.1-or-later
+#
+# Copyright (C) 2026 Collabora Limited
+# Author: Denys Fedoryshchenko <denys.f@collabora.com>
+#
+# The forecast graph walk mirrors build_forecast_graph() in
+# kernelci-core (kernelci/cli/config.py) by Guillaume Tucker and
+# Denys Fedoryshchenko, re-rooted at a real checkout node.
+"""
+Validate Maestro scheduling against the pipeline forecast.
+
+`kci config forecast` (kernelci-core) predicts, from the merged pipeline
+YAML, which kbuilds a checkout should produce and which test jobs each
+kbuild should trigger.  This script turns that prediction into a daily
+audit of what actually ran:
+
+  * fetch checkout nodes old enough for their whole job tree to have
+    settled (at least --age-hours old, over a --window-hours period);
+  * for each checkout, compare the actual kbuild child nodes against the
+    forecast built with the checkout's real kernel revision;
+  * for each kbuild that passed, compare its actual test job child nodes
+    against the forecast.
+
+A missing child is only a finding when its parent succeeded: a failed
+checkout produces no kbuilds and a failed kbuild triggers no test jobs,
+so those absences are expected and are just counted.  Nodes that exist
+but are not in the forecast are reported as unexpected (forecast or
+rules drift).
+
+Finding categories (actionable, in `findings`):
+  * MISSING_KBUILD    - checkout passed, forecast expects the kbuild,
+                        no such node exists.
+  * MISSING_JOB       - kbuild passed (or checkout passed for jobs
+                        triggered directly by the checkout), forecast
+                        expects the job, no such node exists.
+  * UNEXPECTED_KBUILD - kbuild node exists but the forecast does not
+                        predict it.
+  * UNEXPECTED_JOB    - job node exists but the forecast does not
+                        predict it (e.g. rules or runtime drift).
+
+Informational (counted, listed in the JSON report only):
+  * external nodes      - owner differs from the checkout owner:
+                          external submitters (e.g. qualcomm) schedule
+                          their own jobs under Maestro kbuilds, outside
+                          this pipeline's forecast.
+  * non-scheduler nodes - no scheduler entry creates this job from this
+                          parent: nodes created dynamically by job
+                          runners, e.g. the per-suite kselftest build
+                          nodes kbuild.py attaches to kbuilds.
+
+Validating old checkouts against today's config flags jobs added to the
+config since then as MISSING; run against the pipeline config as it was
+at the start of the window (the GitHub workflow does this) to avoid it.
+
+Exit status is 1 when --fail-on-miss is given and any MISSING_* finding
+was recorded.
+"""
+
+import argparse
+import datetime
+import json
+import os
+import sys
+
+import requests
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from validate_yaml import merge_files  # noqa: E402
+
+MISSING_CATEGORIES = ("MISSING_KBUILD", "MISSING_JOB")
+UNEXPECTED_CATEGORIES = ("UNEXPECTED_KBUILD", "UNEXPECTED_JOB")
+
+
+def import_forecast(core_dir):
+    """Import the forecast entry evaluator from kernelci-core"""
+    if core_dir:
+        sys.path.insert(0, core_dir)
+    try:
+        from kernelci.cli.config import evaluate_forecast_entry
+    except ImportError as exc:
+        sys.exit(
+            "Cannot import evaluate_forecast_entry from kernelci-core: "
+            f"{exc}\n"
+            "Install a kernelci-core tree with forecast graph support "
+            "and point --core-dir at it (or add it to PYTHONPATH)."
+        )
+    return evaluate_forecast_entry
+
+
+class MaestroAPI:
+    """Read-only Maestro API client with pagination"""
+
+    def __init__(self, url, timeout=60, page_size=1000):
+        self.base = url.rstrip("/")
+        self.timeout = timeout
+        self.page_size = page_size
+        self.session = requests.Session()
+        adapter = requests.adapters.HTTPAdapter(
+            max_retries=requests.adapters.Retry(
+                total=3, backoff_factor=2, status_forcelist=[500, 502, 504]
+            )
+        )
+        self.session.mount("http://", adapter)
+        self.session.mount("https://", adapter)
+
+    def nodes(self, **filters):
+        """Fetch all nodes matching the filters, following pagination"""
+        items = []
+        offset = 0
+        while True:
+            params = dict(filters)
+            params.update({"limit": self.page_size, "offset": offset})
+            resp = self.session.get(
+                f"{self.base}/latest/nodes",
+                params=params,
+                timeout=self.timeout,
+            )
+            resp.raise_for_status()
+            data = resp.json()
+            page = data.get("items", [])
+            items.extend(page)
+            offset += len(page)
+            if not page or offset >= data.get("total", 0):
+                break
+        return items
+
+
+def event_source_name(event):
+    """Job name whose nodes feed a scheduler entry (checkout for root)"""
+    if event.get("kind") == "checkout":
+        return event.get("name", "checkout")
+    return event.get("name")
+
+
+def node_signature(node):
+    return json.dumps(node, sort_keys=True)
+
+
+def build_expected_graph(evaluate_entry, merged_data, checkout_cfg, root_node):
+    """Build the forecast graph rooted at a real checkout node.
+
+    Returns {source job name: {(child name, platform, kind, runtime)}}
+    where 'checkout' is the root source.  A platform of None means the
+    scheduler entry has no platform list (e.g. docker/kubernetes jobs).
+    """
+    nodes = {"checkout": [root_node]}
+    signatures = {"checkout": {node_signature(root_node)}}
+    edges = {}
+    scheduler_entries = merged_data.get("scheduler", [])
+
+    changed = True
+    while changed:
+        changed = False
+        for entry in scheduler_entries:
+            source = event_source_name(entry.get("event", {}))
+            if not source:
+                continue
+            for input_node in list(nodes.get(source, [])):
+                children, _ = evaluate_entry(
+                    merged_data, entry, input_node, checkout_cfg
+                )
+                for child in children:
+                    name = child["name"]
+                    edges.setdefault(source, set()).add(
+                        (
+                            name,
+                            child["data"].get("platform"),
+                            child["kind"],
+                            child["data"].get("runtime"),
+                        )
+                    )
+                    sig = node_signature(child)
+                    sigs = signatures.setdefault(name, set())
+                    if sig in sigs:
+                        continue
+                    sigs.add(sig)
+                    nodes.setdefault(name, []).append(child)
+                    changed = True
+
+    return edges
+
+
+def scheduler_pairs(merged_data):
+    """Set of (source job name, job name) pairs the scheduler can create.
+
+    Used to tell scheduler-created children apart from nodes attached
+    dynamically by job runners (e.g. per-suite kselftest build nodes).
+    """
+    pairs = set()
+    for entry in merged_data.get("scheduler", []):
+        source = event_source_name(entry.get("event", {}))
+        if source and entry.get("job"):
+            pairs.add((source, entry["job"]))
+    return pairs
+
+
+def checkout_build_config(merged_data, tree, branch):
+    """Merge the build_configs entries matching a tree/branch.
+
+    Multiple entries can point at the same tree/branch with different
+    architecture filters; the forecast should expect the union.
+    """
+    matches = [
+        cfg
+        for cfg in merged_data.get("build_configs", {}).values()
+        if cfg.get("tree") == tree and cfg.get("branch") == branch
+    ]
+    if not matches:
+        return None
+    architectures = set()
+    for cfg in matches:
+        if not cfg.get("architectures"):
+            architectures = None
+            break
+        architectures.update(cfg["architectures"])
+    merged = dict(matches[0])
+    merged["architectures"] = sorted(architectures) if architectures else None
+    return merged
+
+
+def match_children(expected, actual):
+    """Compare forecast {(name, platform): runtime} with actual children.
+
+    A platform of None means any platform.  Returns (missing,
+    unexpected) where missing is a list of (name, platform) keys and
+    unexpected a list of node dicts.
+    """
+    actual_pairs = [
+        (node.get("name"), node.get("data", {}).get("platform"), node)
+        for node in actual
+    ]
+    missing = []
+    for name, platform in sorted(
+        expected, key=lambda item: (item[0], item[1] or "")
+    ):
+        if platform is None:
+            found = any(a_name == name for a_name, _, _ in actual_pairs)
+        else:
+            found = any(
+                a_name == name and a_platform == platform
+                for a_name, a_platform, _ in actual_pairs
+            )
+        if not found:
+            missing.append((name, platform))
+
+    expected_names = {name for name, platform in expected if platform is None}
+    unexpected = [
+        node
+        for a_name, a_platform, node in actual_pairs
+        if a_name not in expected_names and (a_name, a_platform) not in expected
+    ]
+    return missing, unexpected
+
+
+def node_ok(node):
+    return node.get("result") == "pass"
+
+
+def node_settled(node):
+    return node.get("state") == "done"
+
+
+def describe_node(node):
+    data = node.get("data", {})
+    parts = [f"{node.get('name')} ({node.get('id')})"]
+    if data.get("platform"):
+        parts.append(f"platform={data['platform']}")
+    if data.get("runtime"):
+        parts.append(f"runtime={data['runtime']}")
+    if node.get("owner"):
+        parts.append(f"owner={node['owner']}")
+    parts.append(f"result={node.get('result')}")
+    return " ".join(parts)
+
+
+def _checkout_skip_reason(merged_data, checkout):
+    """Reason not to validate a checkout at all, or None"""
+    if checkout.get("jobfilter") or checkout.get("platform_filter"):
+        return "custom checkout with job/platform filter"
+    revision = checkout.get("data", {}).get("kernel_revision", {})
+    version = revision.get("version") or {}
+    if version.get("version") is None or version.get("patchlevel") is None:
+        return "checkout has no parsed kernel version"
+    if not checkout_build_config(
+        merged_data, revision.get("tree"), revision.get("branch")
+    ):
+        return "no build_config for this tree/branch"
+    return None
+
+
+def _checkout_forecast(merged_data, evaluate_entry, checkout, graph_cache):
+    """Forecast edges for a checkout, cached per tree/branch/version"""
+    revision = checkout["data"]["kernel_revision"]
+    version = revision["version"]
+    cache_key = (
+        revision["tree"],
+        revision["branch"],
+        version["version"],
+        version["patchlevel"],
+    )
+    edges = graph_cache.get(cache_key)
+    if edges is None:
+        build_config = checkout_build_config(
+            merged_data, revision["tree"], revision["branch"]
+        )
+        root_node = {
+            "kind": "checkout",
+            "name": "checkout",
+            "data": {"kernel_revision": revision},
+        }
+        edges = build_expected_graph(
+            evaluate_entry, merged_data, build_config, root_node
+        )
+        graph_cache[cache_key] = edges
+    return edges
+
+
+def _fetch_children(api, checkout):
+    """Fetch kbuild children and all job nodes grouped by parent ID"""
+    revision = checkout["data"]["kernel_revision"]
+    filters = {
+        "data.kernel_revision.commit": revision["commit"],
+        "data.kernel_revision.tree": revision["tree"],
+        "data.kernel_revision.branch": revision["branch"],
+    }
+    kbuilds = [
+        node
+        for node in api.nodes(kind="kbuild", **filters)
+        if node.get("parent") == checkout["id"]
+    ]
+    jobs_by_parent = {}
+    for job in api.nodes(kind="job", **filters):
+        jobs_by_parent.setdefault(job.get("parent"), []).append(job)
+    return kbuilds, jobs_by_parent
+
+
+def validate_checkout(
+    api, merged_data, evaluate_entry, pairs, checkout, graph_cache
+):
+    """Validate one checkout node; returns a per-checkout report dict"""
+    revision = checkout.get("data", {}).get("kernel_revision", {})
+    tree = revision.get("tree")
+    branch = revision.get("branch")
+    commit = revision.get("commit")
+    report = {
+        "id": checkout.get("id"),
+        "tree": tree,
+        "branch": branch,
+        "commit": commit,
+        "state": checkout.get("state"),
+        "result": checkout.get("result"),
+        "owner": checkout.get("owner"),
+        "skipped": None,
+        "findings": [],
+        "external": [],
+        "non_scheduler": [],
+        "skipped_failed_kbuilds": [],
+        "unsettled_kbuilds": [],
+    }
+
+    report["skipped"] = _checkout_skip_reason(merged_data, checkout)
+    if report["skipped"]:
+        return report
+
+    edges = _checkout_forecast(
+        merged_data, evaluate_entry, checkout, graph_cache
+    )
+    kbuilds, jobs_by_parent = _fetch_children(api, checkout)
+
+    expected_root = edges.get("checkout", set())
+    expected_kbuilds = {
+        (name, None): runtime
+        for name, _, kind, runtime in expected_root
+        if kind == "kbuild"
+    }
+    expected_root_jobs = {
+        (name, platform): runtime
+        for name, platform, kind, runtime in expected_root
+        if kind == "job"
+    }
+
+    missing, unexpected = match_children(expected_kbuilds, kbuilds)
+    if node_ok(checkout):
+        for key in missing:
+            name, _ = key
+            report["findings"].append(
+                {
+                    "category": "MISSING_KBUILD",
+                    "parent": checkout["id"],
+                    "parent_name": "checkout",
+                    "job": name,
+                    "platform": None,
+                    "runtime": expected_kbuilds[key],
+                }
+            )
+    for node in unexpected:
+        _report_unexpected(report, pairs, node, "checkout", "UNEXPECTED_KBUILD")
+
+    root_jobs = jobs_by_parent.get(checkout["id"], [])
+    _validate_jobs(
+        report,
+        pairs,
+        expected_root_jobs,
+        root_jobs,
+        source_name="checkout",
+        parent_id=checkout["id"],
+        parent_ok=node_ok(checkout),
+    )
+
+    for kbuild in kbuilds:

nipa is a bit weird job btw, it must be deprecated as seems netdev changed things since long time

nuclearcat nuclearcat commented on Jul 09, 2026 08:09 UTC
Author

Thanks for putting this together @nuclearcat this is a good approach to catch this going forward. I wonder if we should add something around the if: failure() step (like create github issue, or some sort of of discord message)?

I am planning that after we make sure there is no unnecessary noise (as we already have too much from -status latency warnings, and it must be reduced).

Reviewers
Assignees
nuclearcat nuclearcat
Labels
risk: low confidence: 85.4% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 52.9% (MEDIUM) · Higher = larger blast radius
52.9%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 85.4% · Lower = rushed or shallow review
85.4%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 7.7% · Safe to merge
7.7%