Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
280 changes: 272 additions & 8 deletions pkgs/id/scripts/update-nixpkgs-inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,157 @@
./scripts/update-nixpkgs-inputs.py master # master (or no ref) inputs
./scripts/update-nixpkgs-inputs.py nixos-unstable # nixos-unstable inputs
./scripts/update-nixpkgs-inputs.py master nixos-unstable # both categories, combined summary

Cache gate (#4553): inputs whose original.ref is "nixos-unstable" are NOT
updated to branch HEAD — HEAD runs days ahead of what Hydra has built and
cache.nixos.org serves, so a HEAD pin can turn the next system build into
a multi-day source build (see #2715). Gated inputs are pinned instead to
the newest revision Hydra has fully built for the channel: the `tested`
job of jobset nixos:unstable, resolved via
GET <hydra>/job/nixos/unstable/tested/latest-finished -> jobsetevals[0]
GET <hydra>/eval/<id> -> jobsetevalinputs.nixpkgs.revision
The pin rewrites only the input's `locked` entry (rev + narHash +
lastModified from a real `nix flake metadata` fetch of that revision);
`original` — including ref "nixos-unstable" — is left untouched so input
discovery keeps matching. The gate fails closed: if the Hydra lookups
fail or return an unexpected shape, the script exits non-zero before
touching flake.lock. The Hydra base URL can be overridden with the
UPDATE_NIXPKGS_HYDRA_URL environment variable (used by the tests).
"""

import json
import os
import re
import ssl
import subprocess
import sys
import urllib.request
from pathlib import Path

GATED_REF = "nixos-unstable"
HYDRA_BASE_URL_ENV = "UPDATE_NIXPKGS_HYDRA_URL"
DEFAULT_HYDRA_BASE_URL = "https://hydra.nixos.org"
HYDRA_LATEST_FINISHED_PATH = "/job/nixos/unstable/tested/latest-finished"
REV_RE = re.compile(r"^[0-9a-f]{40}$")


class HydraGateError(Exception):
"""The Hydra cache gate could not produce a trustworthy revision."""


def https_context():
"""SSL context for Hydra requests, with verification ON.

The .py shebang runs under `uv run --script`, whose standalone
Python builds can fail to locate a CA bundle at all (0 certs
loaded, every HTTPS request CERTIFICATE_VERIFY_FAILED) even on a
healthy system. When the default context comes up empty, point it
at the usual system bundle locations instead of failing."""
ctx = ssl.create_default_context()
if ctx.get_ca_certs():
return ctx
for cafile in (
os.environ.get("SSL_CERT_FILE"),
"/etc/ssl/certs/ca-certificates.crt", # Debian / NixOS
"/etc/pki/tls/certs/ca-bundle.crt", # RHEL family
"/etc/ssl/cert.pem", # macOS / Alpine
):
if cafile and os.path.exists(cafile):
return ssl.create_default_context(cafile=cafile)
return ctx


def fetch_hydra_json(url):
"""GET a Hydra JSON endpoint (follows redirects; Hydra content-
negotiates on the Accept header and serves HTML without it)."""
req = urllib.request.Request(url, headers={"Accept": "application/json"})
with urllib.request.urlopen(req, timeout=60, context=https_context()) as resp:
return json.load(resp)


def parse_latest_finished_eval_id(data):
"""Extract the jobset eval id from a latest-finished build payload."""
if not isinstance(data, dict):
raise HydraGateError("latest-finished payload is not a JSON object")
status = data.get("buildstatus")
if status is not None and status != 0:
raise HydraGateError(
f"latest finished 'tested' build did not succeed (buildstatus={status})"
)
evals = data.get("jobsetevals")
if not isinstance(evals, list) or not evals:
raise HydraGateError("latest-finished payload has no jobsetevals")
eval_id = evals[0]
if isinstance(eval_id, str) and eval_id.isdigit():
eval_id = int(eval_id)
if not isinstance(eval_id, int) or isinstance(eval_id, bool):
raise HydraGateError(f"unexpected jobsetevals[0]: {eval_id!r}")
return eval_id


def parse_eval_revision(data):
"""Extract the nixpkgs revision from a Hydra eval payload."""
if not isinstance(data, dict):
raise HydraGateError("eval payload is not a JSON object")
inputs = data.get("jobsetevalinputs")
if not isinstance(inputs, dict):
raise HydraGateError("eval payload has no jobsetevalinputs")
nixpkgs = inputs.get("nixpkgs")
if not isinstance(nixpkgs, dict):
raise HydraGateError("eval payload has no nixpkgs jobset eval input")
rev = nixpkgs.get("revision")
if not isinstance(rev, str) or not REV_RE.match(rev):
raise HydraGateError(f"unexpected nixpkgs revision: {rev!r}")
return rev


def hydra_cached_revision(base_url=None):
"""Newest nixos-unstable revision Hydra has fully built.

Returns (revision, eval_id). Raises HydraGateError on any lookup
failure or unexpected response shape — callers must fail closed.
"""
base = (
base_url or os.environ.get(HYDRA_BASE_URL_ENV) or DEFAULT_HYDRA_BASE_URL
).rstrip("/")
try:
latest = fetch_hydra_json(base + HYDRA_LATEST_FINISHED_PATH)
except Exception as e:
raise HydraGateError(
f"cannot fetch {base + HYDRA_LATEST_FINISHED_PATH}: {e}"
) from e
eval_id = parse_latest_finished_eval_id(latest)
try:
eval_data = fetch_hydra_json(f"{base}/eval/{eval_id}")
except Exception as e:
raise HydraGateError(f"cannot fetch {base}/eval/{eval_id}: {e}") from e
return parse_eval_revision(eval_data), eval_id


def fetch_locked_for_rev(rev):
"""Fetch github:NixOS/nixpkgs@<rev> with nix and return the locked
attrs (rev, narHash, lastModified, ...) a flake.lock entry needs.
Returns None if the fetch fails or the result does not check out."""
result = subprocess.run(
["nix", "flake", "metadata", f"github:NixOS/nixpkgs/{rev}", "--json"],
capture_output=True,
text=True,
)
if result.returncode != 0:
return None
try:
locked = json.loads(result.stdout)["locked"]
except (ValueError, KeyError, TypeError):
return None
if not isinstance(locked, dict):
return None
# `nix flake metadata` annotates its result with __final; flake.lock
# locked entries do not carry it.
locked = {k: v for k, v in locked.items() if k != "__final"}
if locked.get("rev") != rev or not locked.get("narHash"):
return None
return locked


def load_flake_lock(repo_dir):
"""Load and parse flake.lock."""
Expand Down Expand Up @@ -67,6 +211,31 @@ def get_input_info(lock_data, input_name):
return (rev, url, ref_display)


def get_input_node(lock_data, input_name):
"""Return the lock node for a root input name, or None."""
root_inputs = lock_data.get("nodes", {}).get("root", {}).get("inputs", {})
node_name = root_inputs.get(input_name)
if not isinstance(node_name, str):
return None
return lock_data.get("nodes", {}).get(node_name)


def get_input_ref(lock_data, input_name):
"""Return the input's original.ref (None when unset / not found)."""
node = get_input_node(lock_data, input_name)
if not node:
return None
return node.get("original", {}).get("ref")


def get_locked_rev(lock_data, input_name):
"""Return the input's full locked revision (None when not locked)."""
node = get_input_node(lock_data, input_name)
if not node:
return None
return node.get("locked", {}).get("rev")


def discover_inputs(lock_data, ref):
"""Discover NixOS/nixpkgs inputs by parsing flake.lock directly.

Expand Down Expand Up @@ -127,6 +296,22 @@ def update_input(input_name, repo_dir):
return result.returncode == 0


def pin_input(input_name, repo_dir, locked):
"""Pin an input to a pre-fetched locked entry, rewriting only the
node's `locked` in flake.lock (`original` stays untouched, so the
input's ref — and therefore discovery — is preserved). The dump
format matches nix's own flake.lock formatting byte for byte.
Returns True on success."""
lock_data = load_flake_lock(repo_dir)
node = get_input_node(lock_data, input_name)
if node is None:
return False
node["locked"] = dict(locked)
with open(repo_dir / "flake.lock", "w") as f:
f.write(json.dumps(lock_data, indent=2) + "\n")
return get_locked_rev(load_flake_lock(repo_dir), input_name) == locked["rev"]


def format_result_lines(results):
"""Format result detail lines grouped by source URL."""
url_order = []
Expand Down Expand Up @@ -233,25 +418,62 @@ def main():

refs = sys.argv[1:] if len(sys.argv) > 1 else [None]

# Planning pass: resolve, against the pristine lock, which inputs each
# requested ref will process (same discovery + cross-ref dedupe as the
# execution pass below). The cache gate must be resolved — and must
# fail closed — before any input is touched, so gated inputs are
# identified up front.
plan = []
seen_inputs = set()
gated_inputs = set()
initial_lock = load_flake_lock(repo_dir)
for ref in refs:
inputs = discover_inputs(initial_lock, ref)
new_inputs = [i for i in inputs if i not in seen_inputs]
seen_inputs.update(new_inputs)
plan.append((ref, inputs, new_inputs))
for name in new_inputs:
if get_input_ref(initial_lock, name) == GATED_REF:
gated_inputs.add(name)

gate_rev = None
gate_locked = None
if gated_inputs:
try:
gate_rev, gate_eval = hydra_cached_revision()
except HydraGateError as e:
print(
f"ERROR: Hydra cache gate failed: {e}\n"
f"Refusing to update {GATED_REF} inputs to uncached "
"revisions; flake.lock left untouched.",
file=sys.stderr,
)
sys.exit(1)
gate_locked = fetch_locked_for_rev(gate_rev)
if gate_locked is None:
print(
f"ERROR: could not fetch github:NixOS/nixpkgs@{gate_rev} "
"with nix flake metadata; flake.lock left untouched.",
file=sys.stderr,
)
sys.exit(1)
print(
f"Hydra gate: {GATED_REF} inputs pin to {gate_rev[:12]} "
f"(newest revision fully built by Hydra jobset nixos:unstable, "
f"eval {gate_eval})"
)

all_ref_data = []

for ref in refs:
for ref, inputs, new_inputs in plan:
label = ref if ref else "all"
ref_data = {"label": label, "results": [], "not_found": False}

lock_data = load_flake_lock(repo_dir)
inputs = discover_inputs(lock_data, ref)

if not inputs:
ref_data["not_found"] = True
all_ref_data.append(ref_data)
continue

# Filter out already-seen inputs
new_inputs = [i for i in inputs if i not in seen_inputs]
seen_inputs.update(new_inputs)

if not new_inputs:
all_ref_data.append(ref_data)
continue
Expand All @@ -264,6 +486,48 @@ def main():
lock_data = load_flake_lock(repo_dir)
old_rev, source_url, input_ref = get_input_info(lock_data, input_name)

if input_name in gated_inputs:
if get_locked_rev(lock_data, input_name) == gate_rev:
ref_data["results"].append(
{
"name": input_name,
"status": "skipped",
"old_rev": old_rev,
"new_rev": None,
"url": source_url,
"ref": input_ref,
}
)
elif pin_input(input_name, repo_dir, gate_locked):
lock_data = load_flake_lock(repo_dir)
new_rev, _, _ = get_input_info(lock_data, input_name)
ref_data["results"].append(
{
"name": input_name,
"status": "updated",
"old_rev": old_rev,
"new_rev": new_rev,
"url": source_url,
"ref": input_ref,
}
)
else:
ref_data["results"].append(
{
"name": input_name,
"status": "failed",
"old_rev": old_rev,
"new_rev": None,
"url": source_url,
"ref": input_ref,
}
)
print(
f"WARNING: failed to pin {input_name} to {gate_rev}",
file=sys.stderr,
)
continue

if update_input(input_name, repo_dir):
lock_data = load_flake_lock(repo_dir)
new_rev, _, _ = get_input_info(lock_data, input_name)
Expand Down
Loading
Loading