Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/nix/vm-test-typecheck.nix
maia 132d876668 vm-tests: the typecheck fails a step that rebinds a function of its script
A VM test script and `lib/k3s.py` share one namespace, so a step that assigns
`pod = ...` replaces the library's `pod()` for every later call and the test dies
mid-run with `TypeError: 'dict' object is not callable`. `ty` and
`ruff --select F` accept a module-level rebinding, so this cost a full VM round
on #6947.

`vm-test-shadow-scan.py` parses the script and fails when a name bound at module
level (assignment, `for` or `with` target, `import ... as`, walrus, `except ... as`)
is also a module-level `def`. It looks into `with`, `if`, `for`, `while` and `try`
bodies, where `with subtest(...)` steps live, and not into function or
comprehension bodies. Every `vm-test-typecheck-<name>` runs it on the script alone.
`vm-test-typecheck-shadow-control` passes only when it rejects each form of
rebinding and accepts the same names where they are local.

The one existing case, `sources` in `k8s-services`, is renamed `cred_sources`.

Closes #6951
2026-11-28 09:59:25 +01:00

235 lines
7.5 KiB
Nix

# `vm-test-typecheck-<name>` checks: run the type check and lint that nixpkgs'
# test driver applies to a VM test script (`ty check`, `ruff check --select F`)
# without building the driver. The driver derivation references every node's
# `system.build.vm`, so building or even evaluating it costs a full NixOS
# evaluation per node; the check itself needs only the script text and the
# machine names, and `nodes` is a lazy attribute set, so reading its names
# forces no node configuration.
{ pkgs, vmTests }:
let
inherit (pkgs) lib;
# nixos/lib/testing/driver.nix:24-31 (the pinned nixpkgs).
pythonizeName =
name:
let
head = lib.substring 0 1 name;
tail = lib.substring 1 (-1) name;
in
(if builtins.match "[A-z_]" head == null then "_" else head)
+ lib.stringAsChars (c: if builtins.match "[A-z0-9_]" c == null then "_" else c) tail;
# The type hints of nixos/lib/testing/driver.nix:22-53: one stub machine per
# node, one per container, and `machine` when it is the only node and no
# machine already has that name. The `vlanN` hints are left out: they need
# every node's `virtualisation.vlans`, and no script here uses a `vlanN` name.
hintsFor =
test:
let
nodeNames = lib.attrNames test.config.nodes;
containerNames = lib.attrNames test.config.containers;
alias = lib.optional (
lib.length nodeNames == 1 && !lib.elem "machine" (nodeNames ++ containerNames)
) "machine";
in
lib.concatStringsSep "\n" (
map (n: "${pythonizeName n} = create_fake_qemu_machine()") (nodeNames ++ alias)
++ map (n: "${pythonizeName n} = create_fake_nspawn_machine()") containerNames
);
# `test_driver` reaches ty through `buildInputs`, as in driver.nix:66.
checkInputs = {
nativeBuildInputs = [
pkgs.ty
pkgs.ruff
];
buildInputs = [ pkgs.nixos-test-driver ];
};
# The text driver.nix:77-82 assembles: the prelude from the pinned nixpkgs,
# the hints, then the script.
assemble = ''
cat ${pkgs.path}/nixos/lib/test-script-prepend.py > testScriptWithTypes
echo "$hints" >> testScriptWithTypes
echo -n "$testScript" >> testScriptWithTypes
'';
# The tests that interpolate node config or an agent toplevel name a stand-in
# script in `passthru.typecheckScript`, built by the same function as their real
# `testScript`; reading `testScriptString` there would evaluate a NixOS system.
scriptOf = test: test.config.passthru.typecheckScript or test.config.testScriptString;
typecheck =
name: test:
pkgs.runCommand "vm-test-typecheck-${name}"
(
checkInputs
// {
testScript = scriptOf test;
hints = hintsFor test;
}
)
''
${assemble}
ty check testScriptWithTypes
# driver.nix:91-99
ruff check --select F testScriptWithTypes
# What neither of them sees: a step that rebinds a function the script
# defines. The script alone, so a name of the prelude or a hint isn't read
# as the script's own.
echo -n "$testScript" > testScriptOnly
${shadowScan} testScriptOnly
touch $out
'';
# `vm-test-shadow-scan.py` as a command; the scan reads nothing of the machine
# it runs on, so `-I`.
shadowScan = "${pkgs.python3}/bin/python3 -I ${./vm-test-shadow-scan.py}";
# Succeeds only when the scan rejects every way a step rebinds a function of
# its script and accepts the same names where they are local. The first
# script is accepted whole: if it were not, the rejections below could be the
# scan failing on anything.
shadowControl =
let
script = body: pkgs.writeText "script.py" body;
accepted = script ''
def pod(name):
return {"name": name}
def other():
pod = 1 # local to the function
return [pod for pod in range(3)] # a comprehension has its own scope
with subtest("a variable with a name of its own"):
result = pod("a")
'';
rejected = {
"a plain assignment" = ''
def pod(name):
return {}
pod = pod("a")
'';
"an assignment inside a subtest" = ''
def pod(name):
return {}
with subtest("x"):
pod = pod("a")
'';
"a for target" = ''
def pod(name):
return {}
for pod in range(3):
pass
'';
"a with target" = ''
def pod(name):
return {}
with open("x") as pod:
pass
'';
"an import" = ''
def pod(name):
return {}
import json as pod
'';
"an except target" = ''
def pod(name):
return {}
try:
pass
except Exception as pod:
pass
'';
};
in
pkgs.runCommand "vm-test-typecheck-shadow-control" { } ''
${shadowScan} ${accepted}
${lib.concatStrings (
lib.mapAttrsToList (what: body: ''
if ${shadowScan} ${script body} 2> scan.err; then
echo "the scan accepted ${what}" >&2
exit 1
fi
grep -q '`pod` is bound at module level' scan.err
'') rejected
)}
touch $out
'';
# Succeeds only when `ty` rejects an `Optional` dereference and three calls on
# the stub machines of `hintsFor`. If `test_driver` stops resolving, every
# name is `Unknown`, the real checks pass on anything, and this one fails.
control =
pkgs.runCommand "vm-test-typecheck-control"
(
checkInputs
// {
testScript = ''
import re
def first_group(s: str) -> str:
return re.search(r"x", s).group(1)
my_node.no_such_node()
machine.no_such_alias()
c_1.no_such_container()
'';
hints = hintsFor {
config = {
nodes."my-node" = { };
containers."c-1" = { };
};
};
}
)
''
${assemble}
if ty check testScriptWithTypes > ty.out 2>&1; then
cat ty.out
echo "ty accepted re.search(...).group(1); the type check is not effective" >&2
exit 1
fi
cat ty.out
# `group` comes from the stdlib stubs; the other three are attributes of
# the stub machines `hintsFor` declares, so they show the node, `machine`
# alias and container hints each resolve to a typed machine.
grep -q "Attribute .group. is not defined on .None." ty.out
grep -q "has no attribute .no_such_node." ty.out
grep -q "has no attribute .no_such_alias." ty.out
grep -q "has no attribute .no_such_container." ty.out
if grep -q unresolved-import ty.out; then
echo "test_driver does not resolve" >&2
exit 1
fi
touch $out
'';
tests = {
inherit (vmTests)
agent-android-dev
hive-squid
hive-egress-antispoof
swarm-archive
agent-ephemeral-rootfs
full-setup
semi-spread
swarm-builder-offline
tuwunel-fallocate-probe
container-deferred-start
k8s-swarm-images
k8s-node
k8s-collector-switch
k8s-bao-login
k8s-services
k8s-controller
k8s-nats
k8s-join
;
};
in
(lib.mapAttrs' (n: t: lib.nameValuePair "vm-test-typecheck-${n}" (typecheck n t)) tests)
// {
vm-test-typecheck-control = control;
vm-test-typecheck-shadow-control = shadowControl;
}