Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Fail CI on a new exec/eval/compile of a value that is not written out (#9999)

Daniel Han6e8a1e15d134
diff --git a/.github/workflows/lint-ci.yml b/.github/workflows/lint-ci.yml
index 95c9a8ba807..883f20d8648 100644
--- a/.github/workflows/lint-ci.yml
+++ b/.github/workflows/lint-ci.yml
@@ -156,6 +156,12 @@ jobs:
python -m compileall -q -j 0 \
unsloth unsloth_cli studio tests cli.py unsloth-cli.py
+ - name: Dynamic-execution gate self-test
+ run: python scripts/lint_exec_literals.py --self-test
+
+ - name: No exec, eval or compile of a value that is not written out
+ run: python scripts/lint_exec_literals.py
+
- name: Python ruff check (whole repo)
# The narrow rule set in pyproject.toml [tool.ruff.lint]
# selects E9 / F63 / F7 / F82 -- syntax errors, broken
diff --git a/scripts/exec_literals_baseline.json b/scripts/exec_literals_baseline.json
new file mode 100644
index 00000000000..90652d0b3e5
--- /dev/null
+++ b/scripts/exec_literals_baseline.json
@@ -0,0 +1,496 @@
+{
+ "_comment": "Call sites that predate the gate. New ones fail; see scripts/lint_exec_literals.py.",
+ "targets": [
+ "unsloth",
+ "unsloth_cli",
+ "studio",
+ "scripts",
+ "cli.py",
+ "unsloth-cli.py"
+ ],
+ "entries": [
+ {
+ "file": "unsloth/models/_utils.py",
+ "sink": "eval",
+ "digest": "6f65bd10ad34f535",
+ "count": 1,
+ "reason": "Re-imports a transformers config module by its dotted path, derived from the installed package layout, and runs a config source this file generated."
+ },
+ {
+ "file": "unsloth/models/_utils.py",
+ "sink": "exec",
+ "digest": "02c93361a59d02a7",
+ "count": 1,
+ "reason": "Re-imports a transformers config module by its dotted path, derived from the installed package layout, and runs a config source this file generated."
+ },
+ {
+ "file": "unsloth/models/_utils.py",
+ "sink": "exec",
+ "digest": "16b70ffbbdbad15f",
+ "count": 2,
+ "reason": "Re-imports a transformers config module by its dotted path, derived from the installed package layout, and runs a config source this file generated."
+ },
+ {
+ "file": "unsloth/models/_utils.py",
+ "sink": "exec",
+ "digest": "48b77ebd764afeec",
+ "count": 1,
+ "reason": "Re-imports a transformers config module by its dotted path, derived from the installed package layout, and runs a config source this file generated."
+ },
+ {
+ "file": "unsloth/models/_utils.py",
+ "sink": "exec",
+ "digest": "73395828db366a08",
+ "count": 1,
+ "reason": "Re-imports a transformers config module by its dotted path, derived from the installed package layout, and runs a config source this file generated."
+ },
+ {
+ "file": "unsloth/models/_utils.py",
+ "sink": "exec",
+ "digest": "7a5e305efb369e7f",
+ "count": 1,
+ "reason": "Re-imports a transformers config module by its dotted path, derived from the installed package layout, and runs a config source this file generated."
+ },
+ {
+ "file": "unsloth/models/_utils.py",
+ "sink": "exec",
+ "digest": "97ca7ce74cdac597",
+ "count": 1,
+ "reason": "Re-imports a transformers config module by its dotted path, derived from the installed package layout, and runs a config source this file generated."
+ },
+ {
+ "file": "unsloth/models/_utils.py",
+ "sink": "exec",
+ "digest": "a1ca0b42925e7071",
+ "count": 1,
+ "reason": "Re-imports a transformers config module by its dotted path, derived from the installed package layout, and runs a config source this file generated."
+ },
+ {
+ "file": "unsloth/models/_utils.py",
+ "sink": "exec",
+ "digest": "ac8b8345e7bf04cf",
+ "count": 1,
+ "reason": "Re-imports a transformers config module by its dotted path, derived from the installed package layout, and runs a config source this file generated."
+ },
+ {
+ "file": "unsloth/models/_utils.py",
+ "sink": "exec",
+ "digest": "ca0d5d3cc2cd8f6c",
+ "count": 1,
+ "reason": "Re-imports a transformers config module by its dotted path, derived from the installed package layout, and runs a config source this file generated."
+ },
+ {
+ "file": "unsloth/models/_utils.py",
+ "sink": "exec",
+ "digest": "d452fc2117e42b99",
+ "count": 1,
+ "reason": "Re-imports a transformers config module by its dotted path, derived from the installed package layout, and runs a config source this file generated."
+ },
+ {
+ "file": "unsloth/models/_utils.py",
+ "sink": "exec",
+ "digest": "ffa18102ffbe15dd",
+ "count": 2,
+ "reason": "Re-imports a transformers config module by its dotted path, derived from the installed package layout, and runs a config source this file generated."
+ },
+ {
+ "file": "unsloth/models/cohere.py",
+ "sink": "eval",
+ "digest": "1892d8728c05a80c",
+ "count": 1,
+ "reason": "Installs a patched attention `__init__` generated by this file from a fixed template, and binds it by the name that template defines."
+ },
+ {
+ "file": "unsloth/models/cohere.py",
+ "sink": "exec",
+ "digest": "16b70ffbbdbad15f",
+ "count": 1,
+ "reason": "Installs a patched attention `__init__` generated by this file from a fixed template, and binds it by the name that template defines."
+ },
+ {
+ "file": "unsloth/models/falcon_h1.py",
+ "sink": "eval",
+ "digest": "1892d8728c05a80c",
+ "count": 1,
+ "reason": "Installs a patched attention `__init__` generated by this file from a fixed template, and binds it by the name that template defines."
+ },
+ {
+ "file": "unsloth/models/falcon_h1.py",
+ "sink": "exec",
+ "digest": "16b70ffbbdbad15f",
+ "count": 1,
+ "reason": "Installs a patched attention `__init__` generated by this file from a fixed template, and binds it by the name that template defines."
+ },
+ {
+ "file": "unsloth/models/gemma.py",
+ "sink": "eval",
+ "digest": "1892d8728c05a80c",
+ "count": 1,
+ "reason": "Installs a patched attention `__init__` generated by this file from a fixed template, and binds it by the name that template defines."
+ },
+ {
+ "file": "unsloth/models/gemma.py",
+ "sink": "exec",
+ "digest": "16b70ffbbdbad15f",
+ "count": 1,
+ "reason": "Installs a patched attention `__init__` generated by this file from a fixed template, and binds it by the name that template defines."
+ },
+ {
+ "file": "unsloth/models/gemma2.py",
+ "sink": "eval",
+ "digest": "1892d8728c05a80c",
+ "count": 1,
+ "reason": "Installs a patched attention `__init__` generated by this file from a fixed template, and binds it by the name that template defines."
+ },
+ {
+ "file": "unsloth/models/gemma2.py",
+ "sink": "exec",
+ "digest": "16b70ffbbdbad15f",
+ "count": 1,
+ "reason": "Installs a patched attention `__init__` generated by this file from a fixed template, and binds it by the name that template defines."
+ },
+ {
+ "file": "unsloth/models/granite.py",
+ "sink": "eval",
+ "digest": "1892d8728c05a80c",
+ "count": 1,
+ "reason": "Installs a patched attention `__init__` generated by this file from a fixed template, and binds it by the name that template defines."
+ },
+ {
+ "file": "unsloth/models/granite.py",
+ "sink": "exec",
+ "digest": "16b70ffbbdbad15f",
+ "count": 1,
+ "reason": "Installs a patched attention `__init__` generated by this file from a fixed template, and binds it by the name that template defines."
+ },
+ {
+ "file": "unsloth/models/llama.py",
+ "sink": "eval",
+ "digest": "1892d8728c05a80c",
+ "count": 1,
+ "reason": "Installs the patched inner training loop and attention this file generates from a fixed template."
+ },
+ {
+ "file": "unsloth/models/llama.py",
+ "sink": "eval",
+ "digest": "8c54ad1f5eaab0cd",
+ "count": 1,
+ "reason": "Installs the patched inner training loop and attention this file generates from a fixed template."
+ },
+ {
+ "file": "unsloth/models/llama.py",
+ "sink": "exec",
+ "digest": "16b70ffbbdbad15f",
+ "count": 1,
+ "reason": "Installs the patched inner training loop and attention this file generates from a fixed template."
+ },
+ {
+ "file": "unsloth/models/llama.py",
+ "sink": "exec",
+ "digest": "bf2e8c51f0f6c2ed",
+ "count": 1,
+ "reason": "Installs the patched inner training loop and attention this file generates from a fixed template."
+ },
+ {
+ "file": "unsloth/models/llama.py",
+ "sink": "exec",
+ "digest": "ffa18102ffbe15dd",
+ "count": 1,
+ "reason": "Installs the patched inner training loop and attention this file generates from a fixed template."
+ },
+ {
+ "file": "unsloth/models/mistral.py",
+ "sink": "eval",
+ "digest": "1892d8728c05a80c",
+ "count": 1,
+ "reason": "Installs a patched attention `__init__` generated by this file from a fixed template, and binds it by the name that template defines."
+ },
+ {
+ "file": "unsloth/models/mistral.py",
+ "sink": "exec",
+ "digest": "16b70ffbbdbad15f",
+ "count": 1,
+ "reason": "Installs a patched attention `__init__` generated by this file from a fixed template, and binds it by the name that template defines."
+ },
+ {
+ "file": "unsloth/models/qwen2.py",
+ "sink": "eval",
+ "digest": "1892d8728c05a80c",
+ "count": 1,
+ "reason": "Installs a patched attention `__init__` generated by this file from a fixed template, and binds it by the name that template defines."
+ },
+ {
+ "file": "unsloth/models/qwen2.py",
+ "sink": "exec",
+ "digest": "16b70ffbbdbad15f",
+ "count": 1,
+ "reason": "Installs a patched attention `__init__` generated by this file from a fixed template, and binds it by the name that template defines."
+ },
+ {
+ "file": "unsloth/models/qwen3.py",
+ "sink": "eval",
+ "digest": "1892d8728c05a80c",
+ "count": 1,
+ "reason": "Installs a patched attention `__init__` generated by this file from a fixed template, and binds it by the name that template defines."
+ },
+ {
+ "file": "unsloth/models/qwen3.py",
+ "sink": "exec",
+ "digest": "16b70ffbbdbad15f",
+ "count": 1,
+ "reason": "Installs a patched attention `__init__` generated by this file from a fixed template, and binds it by the name that template defines."
+ },
+ {
+ "file": "unsloth/models/qwen3_moe.py",
+ "sink": "eval",
+ "digest": "1892d8728c05a80c",
+ "count": 1,
+ "reason": "Installs a patched attention `__init__` generated by this file from a fixed template, and binds it by the name that template defines."
+ },
+ {
+ "file": "unsloth/models/qwen3_moe.py",
+ "sink": "exec",
+ "digest": "16b70ffbbdbad15f",
+ "count": 1,
+ "reason": "Installs a patched attention `__init__` generated by this file from a fixed template, and binds it by the name that template defines."
+ },
+ {
+ "file": "unsloth/models/rl.py",
+ "sink": "eval",
+ "digest": "040bea2f53f4a4a8",
+ "count": 1,
+ "reason": "Re-imports TRL trainer and config classes by name, and installs the RL trainer source this file generates. The names come from this file's own tables."
+ },
+ {
+ "file": "unsloth/models/rl.py",
+ "sink": "eval",
+ "digest": "12f9cfb57398f055",
+ "count": 1,
+ "reason": "Re-imports TRL trainer and config classes by name, and installs the RL trainer source this file generates. The names come from this file's own tables."
+ },
+ {
+ "file": "unsloth/models/rl.py",
+ "sink": "eval",
+ "digest": "1b541d091f185088",
+ "count": 1,
+ "reason": "Re-imports TRL trainer and config classes by name, and installs the RL trainer source this file generates. The names come from this file's own tables."
+ },
+ {
+ "file": "unsloth/models/rl.py",
+ "sink": "eval",
+ "digest": "485886920a5f24be",
+ "count": 1,
+ "reason": "Re-imports TRL trainer and config classes by name, and installs the RL trainer source this file generates. The names come from this file's own tables."
+ },
+ {
+ "file": "unsloth/models/rl.py",
+ "sink": "eval",
+ "digest": "751bc0188ade4910",
+ "count": 1,
+ "reason": "Re-imports TRL trainer and config classes by name, and installs the RL trainer source this file generates. The names come from this file's own tables."
+ },
+ {
+ "file": "unsloth/models/rl.py",
+ "sink": "eval",
+ "digest": "8d596db7f4780ece",
+ "count": 1,
+ "reason": "Re-imports TRL trainer and config classes by name, and installs the RL trainer source this file generates. The names come from this file's own tables."
+ },
+ {
+ "file": "unsloth/models/rl.py",
+ "sink": "eval",
+ "digest": "a107a7d59348af6b",
+ "count": 2,
+ "reason": "Re-imports TRL trainer and config classes by name, and installs the RL trainer source this file generates. The names come from this file's own tables."
+ },
+ {
+ "file": "unsloth/models/rl.py",
+ "sink": "eval",
+ "digest": "ffde228dbcc08d6e",
+ "count": 1,
+ "reason": "Re-imports TRL trainer and config classes by name, and installs the RL trainer source this file generates. The names come from this file's own tables."
+ },
+ {
+ "file": "unsloth/models/rl.py",
+ "sink": "exec",
+ "digest": "0c82f779093d048a",
+ "count": 1,
+ "reason": "Re-imports TRL trainer and config classes by name, and installs the RL trainer source this file generates. The names come from this file's own tables."
+ },
+ {
+ "file": "unsloth/models/rl.py",
+ "sink": "exec",
+ "digest": "71b3c1011fa9a32a",
+ "count": 1,
+ "reason": "Re-imports TRL trainer and config classes by name, and installs the RL trainer source this file generates. The names come from this file's own tables."
+ },
+ {
+ "file": "unsloth/models/rl.py",
+ "sink": "exec",
+ "digest": "95a7a7b591ba7c69",
+ "count": 1,
+ "reason": "Re-imports TRL trainer and config classes by name, and installs the RL trainer source this file generates. The names come from this file's own tables."
+ },
+ {
+ "file": "unsloth/models/rl.py",
+ "sink": "exec",
+ "digest": "9e3882f4d4a000a5",
+ "count": 1,
+ "reason": "Re-imports TRL trainer and config classes by name, and installs the RL trainer source this file generates. The names come from this file's own tables."
+ },
+ {
+ "file": "unsloth/models/rl.py",
+ "sink": "exec",
+ "digest": "cf3b35303f787f60",
+ "count": 1,
+ "reason": "Re-imports TRL trainer and config classes by name, and installs the RL trainer source this file generates. The names come from this file's own tables."
+ },
+ {
+ "file": "unsloth/models/rl.py",
+ "sink": "exec",
+ "digest": "e0d306bb2ec1ef96",
+ "count": 1,
+ "reason": "Re-imports TRL trainer and config classes by name, and installs the RL trainer source this file generates. The names come from this file's own tables."
+ },
+ {
+ "file": "unsloth/models/rl.py",
+ "sink": "exec",
+ "digest": "e1916de418366d67",
+ "count": 1,
+ "reason": "Re-imports TRL trainer and config classes by name, and installs the RL trainer source this file generates. The names come from this file's own tables."
+ },
+ {
+ "file": "unsloth/models/rl_replacements.py",
+ "sink": "compile",
+ "digest": "53f704f6a01044a0",
+ "count": 1,
+ "reason": "Runs an OpenEnv helper this file generated, into that module's own namespace."
+ },
+ {
+ "file": "unsloth/models/rl_replacements.py",
+ "sink": "compile",
+ "digest": "e687239bf1764e7b",
+ "count": 1,
+ "reason": "Runs an OpenEnv helper this file generated, into that module's own namespace."
+ },
+ {
+ "file": "unsloth/models/rl_replacements.py",
+ "sink": "exec",
+ "digest": "4c016c10e4e620df",
+ "count": 1,
+ "reason": "Runs an OpenEnv helper this file generated, into that module's own namespace."
+ },
+ {
+ "file": "unsloth/models/rl_replacements.py",
+ "sink": "exec",
+ "digest": "bf6c7a01e464bb2e",
+ "count": 1,
+ "reason": "Runs an OpenEnv helper this file generated, into that module's own namespace."
+ },
+ {
+ "file": "unsloth/models/vision.py",
+ "sink": "exec",
+ "digest": "8859505e5f6b735d",
+ "count": 1,
+ "reason": "The two code fields of UNSLOTH_FORCE_CUSTOM_DTYPE. Since #9777 they run only when this process is the one that set the variable; an inherited value is neutralised."
+ },
+ {
+ "file": "unsloth/models/vision.py",
+ "sink": "exec",
+ "digest": "bc99b6581c19626f",
+ "count": 1,
+ "reason": "The two code fields of UNSLOTH_FORCE_CUSTOM_DTYPE. Since #9777 they run only when this process is the one that set the variable; an inherited value is neutralised."
+ },
+ {
+ "file": "unsloth/save.py",
+ "sink": "eval",
+ "digest": "50e054a40711a42c",
+ "count": 1,
+ "reason": "Installs a generated push_to_hub, and reads a projection off a layer by attribute name from this file's own list."
+ },
+ {
+ "file": "unsloth/save.py",
+ "sink": "eval",
+ "digest": "511bf8655fb63a91",
+ "count": 1,
+ "reason": "Installs a generated push_to_hub, and reads a projection off a layer by attribute name from this file's own list."
+ },
+ {
+ "file": "unsloth/save.py",
+ "sink": "exec",
+ "digest": "a2cfaff818bc9d0a",
+ "count": 1,
+ "reason": "Installs a generated push_to_hub, and reads a projection off a layer by attribute name from this file's own list."
+ },
+ {
+ "file": "unsloth/tokenizer_utils.py",
+ "sink": "eval",
+ "digest": "5dfbb61217ed565e",
+ "count": 1,
+ "reason": "Installs tokenizer helpers this file generates from a fixed template."
+ },
+ {
+ "file": "unsloth/tokenizer_utils.py",
+ "sink": "eval",
+ "digest": "876b82a666155684",
+ "count": 1,
+ "reason": "Installs tokenizer helpers this file generates from a fixed template."
+ },
+ {
+ "file": "unsloth/tokenizer_utils.py",
+ "sink": "eval",
+ "digest": "bb2efe71038ee862",
+ "count": 1,
+ "reason": "Installs tokenizer helpers this file generates from a fixed template."
+ },
+ {
+ "file": "unsloth/tokenizer_utils.py",
+ "sink": "exec",
+ "digest": "0531bad2da0f6ae6",
+ "count": 1,
+ "reason": "Installs tokenizer helpers this file generates from a fixed template."
+ },
+ {
+ "file": "unsloth/tokenizer_utils.py",
+ "sink": "exec",
+ "digest": "16b70ffbbdbad15f",
+ "count": 1,
+ "reason": "Installs tokenizer helpers this file generates from a fixed template."
+ },
+ {
+ "file": "unsloth/tokenizer_utils.py",
+ "sink": "exec",
+ "digest": "334b23e645ea4deb",
+ "count": 1,
+ "reason": "Installs tokenizer helpers this file generates from a fixed template."
+ },
+ {
+ "file": "unsloth/tokenizer_utils.py",
+ "sink": "exec",
+ "digest": "5af2e964be736252",
+ "count": 1,
+ "reason": "Installs tokenizer helpers this file generates from a fixed template."
+ },
+ {
+ "file": "unsloth/tokenizer_utils.py",
+ "sink": "exec",
+ "digest": "82ee463f140c695e",
+ "count": 1,
+ "reason": "Installs tokenizer helpers this file generates from a fixed template."
+ },
+ {
+ "file": "unsloth/tokenizer_utils.py",
+ "sink": "exec",
+ "digest": "f9d16814a82a1e43",
+ "count": 1,
+ "reason": "Installs tokenizer helpers this file generates from a fixed template."
+ },
+ {
+ "file": "unsloth/trainer.py",
+ "sink": "exec",
+ "digest": "affd1e4daaf31ae7",
+ "count": 1,
+ "reason": "Installs the patched trainer method this file generates from a fixed template."
+ }
+ ]
+}
diff --git a/scripts/lint_exec_literals.py b/scripts/lint_exec_literals.py
new file mode 100644
index 00000000000..22c2d3ccf92
--- /dev/null
+++ b/scripts/lint_exec_literals.py
@@ -0,0 +1,313 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+"""Fail CI when `exec`, `eval` or `compile` is handed something that is not a literal.
+
+Two of the holes fixed in unsloth-zoo#1108 and unsloth#9777 were exactly this shape:
+`exec` of an HTTPS response body, and `exec` of a string built from a downloaded
+config. GitHub's CodeQL runs on these repositories with Python enabled and raises
+other injection findings here, `py/path-injection` among them, but it has never once
+raised `py/code-injection` - so this class is not covered by what is already running.
+
+The rule is deliberately the blunt one: the first argument to one of those three
+builtins must be a written-out string. Anything else - a name, a call, an f-string
+with a placeholder - is reported. That is coarse, and it is meant to be. The realistic
+failure is a contributor writing `exec(f"...")` without thinking about where the
+pieces came from, not somebody engineering a way past a checker they could equally
+well delete.
+
+Existing call sites are recorded in a baseline beside this script, so the gate starts
+green and only new ones fail. A baseline entry carries the call's own text rather than
+its line number, so moving code does not churn it, and it carries a count, so a new
+call cannot hide behind a removed one.
+
+ python scripts/lint_exec_literals.py # check, exit 1 on a new site
+ python scripts/lint_exec_literals.py --update # rewrite the baseline
+ python scripts/lint_exec_literals.py --self-test # prove the rule still fires
+"""
+
+from __future__ import annotations
+
+import argparse
+import ast
+import hashlib
+import json
+import sys
+from pathlib import Path
+
+# Only the bare names. `re.compile(pattern)` and `model.eval()` are not these builtins,
+# and matching on the attribute reported 69 of them across the two repositories.
+SINKS = ("exec", "eval", "compile")
+
+# Notebooks are scanned too: in the notebooks repository they are the maintained
+# source, and a cell runs the same interpreter a module does.
+SUFFIXES = (".py", ".ipynb")
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+BASELINE_PATH = Path(__file__).resolve().parent / "exec_literals_baseline.json"
+
+# Not part of any commit, or not ours to fail on. `tests` is excluded because a test
+# legitimately keeps a real `exec` around as the thing it is asserting about.
+EXCLUDED_PARTS = frozenset(
+ {
+ "tests",
+ "node_modules",
+ "build",
+ "dist",
+ ".venv",
+ "venv",
+ "site-packages",
+ ".git",
+ ".tox",
+ ".mypy_cache",
+ ".pytest_cache",
+ "__pycache__",
+ ".ipynb_checkpoints",
+ ".eggs",
+ }
+)
+
+
+def _is_written_out(node: ast.AST) -> bool:
+ """Whether this argument is a string the file spells out in full."""
+ if isinstance(node, ast.Constant):
+ return isinstance(node.value, (str, bytes))
+ if isinstance(node, ast.JoinedStr):
+ # An f-string with no placeholder is just a string. One with a placeholder is
+ # the whole point of this check.
+ return not any(isinstance(part, ast.FormattedValue) for part in node.values)
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
+ # `"import " + "torch"` is still written out; `"import " + name` is not.
+ return _is_written_out(node.left) and _is_written_out(node.right)
+ return False
+
+
+def _key(relative: str, call: ast.Call) -> dict:
+ """How a call is remembered: its file, its sink, and a digest of its own source.
+
+ The digest is over `ast.unparse`, so reformatting and moving the call leave the
+ entry alone while changing what is passed does not.
+ """
+ return {
+ "file": relative,
+ "sink": call.func.id,
+ "digest": hashlib.sha256(ast.unparse(call).encode()).hexdigest()[:16],
+ }
+
+
+def _notebook_source(path: Path, relative: str) -> str:
+ """The Python of a notebook's code cells, one blank line apart.
+
+ A cell is not a module, so they are joined rather than parsed one at a time; a
+ `%magic` or `!command` line is not Python at all and is blanked, which keeps the
+ line count and therefore the reported line numbers honest.
+ """
+ try:
+ document = json.loads(path.read_text(encoding = "utf-8"))
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError) as error:
+ raise SystemExit(f"{relative}: could not be read ({error.__class__.__name__})")
+ lines: list[str] = []
+ for cell in document.get("cells") or []:
+ if cell.get("cell_type") != "code":
+ continue
+ source = cell.get("source") or []
+ text = source if isinstance(source, str) else "".join(source)
+ for line in text.splitlines():
+ lines.append("" if line.lstrip().startswith(("%", "!")) else line)
+ lines.append("")
+ return "\n".join(lines)
+
+
+def scan_file(path: Path, relative: str) -> list[dict]:
+ if path.suffix == ".ipynb":
+ source: str | bytes = _notebook_source(path, relative)
+ else:
+ source = path.read_bytes()
+ try:
+ tree = ast.parse(source, filename = str(path))
+ except (SyntaxError, ValueError, MemoryError, RecursionError) as error:
+ if path.suffix == ".ipynb":
+ # A notebook that does not parse as one module is ordinary: a cell may be
+ # mid-edit, or depend on an earlier `%%capture`. Nothing to check, and
+ # failing the build for it would be noise.
+ return []
+ # A .py file that will not parse has not been checked, and reporting it clean
+ # is the bypass this whole gate exists to avoid.
+ raise SystemExit(f"{relative}: could not be parsed ({error.__class__.__name__})")
+ found = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call) or not node.args:
+ continue
+ if not isinstance(node.func, ast.Name) or node.func.id not in SINKS:
+ continue
+ if _is_written_out(node.args[0]):
+ continue
+ entry = _key(relative, node)
+ entry["line"] = node.lineno
+ found.append(entry)
+ return found
+
+
+def collect(targets: list[str]) -> list[dict]:
+ found = []
+ for target in targets:
+ root = REPO_ROOT / target
+ if root.is_file() and root.suffix in SUFFIXES:
+ paths = [root]
+ elif root.is_dir():
+ paths = sorted(q for s in SUFFIXES for q in root.rglob(f"*{s}"))
+ else:
+ # A target that resolves to nothing means the gate covers less than it
+ # claims to, which is a silent hole rather than a passing run.
+ raise SystemExit(
+ f"{target}: scan target does not exist, so nothing under it was checked"
+ )
+ for path in paths:
+ if not path.is_file():
+ continue
+ try:
+ relative = path.relative_to(REPO_ROOT).as_posix()
+ except ValueError:
+ # `--paths` may name a file outside the checkout, which is how the tests
+ # drive the gate. Report it by the name it was given.
+ relative = path.as_posix()
+ if EXCLUDED_PARTS & set(Path(relative).parts):
+ continue
+ found.extend(scan_file(path, relative))
+ return found
+
+
+def _counted(entries: list[dict]) -> dict:
+ """Identity -> how many times it appears. Identity AND count, so a new call cannot
+ take the place of one that was removed."""
+ counts: dict = {}
+ for entry in entries:
+ counts[(entry["file"], entry["sink"], entry["digest"])] = (
+ counts.get((entry["file"], entry["sink"], entry["digest"]), 0) + 1
+ )
+ return counts
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description = __doc__)
+ parser.add_argument("--update", action = "store_true", help = "rewrite the baseline")
+ parser.add_argument("--self-test", action = "store_true", help = "check the rule still fires")
+ parser.add_argument("--paths", nargs = "*", help = "scan these instead of the defaults")
+ arguments = parser.parse_args()
+
+ if arguments.self_test:
+ return self_test()
+
+ document = json.loads(BASELINE_PATH.read_text(encoding = "utf-8"))
+ targets = arguments.paths or document["targets"]
+ found = collect(targets)
+
+ if arguments.update:
+ # Existing reasons are carried over. Rebuilding the list from scratch reset
+ # every hand-written justification to nothing, which is how a reviewed entry
+ # silently becomes an unreviewed one.
+ reasons = {
+ (e["file"], e["sink"], e["digest"]): e.get("reason", "") for e in document["entries"]
+ }
+ document["entries"] = sorted(
+ (
+ {
+ "file": f,
+ "sink": s,
+ "digest": d,
+ "count": n,
+ "reason": reasons.get((f, s, d), "REVIEW ME"),
+ }
+ for (f, s, d), n in _counted(found).items()
+ ),
+ key = lambda e: (e["file"], e["sink"], e["digest"]),
+ )
+ BASELINE_PATH.write_text(json.dumps(document, indent = 2) + "\n", encoding = "utf-8")
+ print(f"baseline: {len(document['entries'])} entries, {len(found)} call sites")
+ return 0
+
+ allowed = {(e["file"], e["sink"], e["digest"]): e["count"] for e in document["entries"]}
+ observed = _counted(found)
+ lines = {(e["file"], e["sink"], e["digest"]): e["line"] for e in found}
+
+ new = [k for k, n in observed.items() if n > allowed.get(k, 0)]
+ if new:
+ print(f"{len(new)} dynamic-execution call site(s) not in the baseline:\n")
+ for f, s, d in sorted(new):
+ print(f" {f}:{lines[(f, s, d)]} {s}(...) is handed a value that is not written out")
+ print(
+ "\nEither pass a written-out string, or - if the value really is trusted - "
+ "record it with `--update` and say why in the pull request."
+ )
+ return 1
+
+ unreviewed = sorted(
+ (e["file"], e["sink"])
+ for e in document["entries"]
+ if not e.get("reason") or e["reason"] == "REVIEW ME"
+ )
+ if unreviewed:
+ print(f"{len(unreviewed)} baseline entr(y/ies) carry no justification:\n")
+ for f, s in unreviewed:
+ print(f" {f} {s}")
+ print("\nSay why the value is trusted in the entry's `reason` field.")
+ return 1
+
+ stale = sorted(k for k in allowed if k not in observed)
+ if stale:
+ # A baseline that outlives its call site quietly re-permits whatever lands on
+ # that digest next, so it is an error rather than a note.
+ print(f"{len(stale)} baseline entr(y/ies) no longer match any call. Run --update:\n")
+ for f, s, d in stale:
+ print(f" {f} {s} {d}")
+ return 1
+
+ print(f"ok: {len(found)} dynamic-execution call site(s), all recorded")
+ return 0
+
+
+_BAD = """
+def f(name):
+ exec(f"import {name}")
+ eval("torch." + name)
+ compile(source, "<x>", "exec")
+ exec("import MODULE".replace("MODULE", name))
+"""
+
+_GOOD = """
+import re
+def f(name, source):
+ exec("import torch")
+ exec(f"no placeholders here")
+ eval("1 + 1")
+ re.compile(name) # not the builtin
+ model.eval() # not the builtin
+ exec() # no arguments
+"""
+
+
+def self_test() -> int:
+ """The rule has to fire on the bad shapes and stay quiet on the good ones.
+
+ Written out here rather than in the test suite as well, so the gate can prove
+ itself on a runner that installs nothing but Python.
+ """
+ import tempfile
+
+ failures = []
+ with tempfile.TemporaryDirectory() as directory:
+ for label, source, expected in (("bad", _BAD, 4), ("good", _GOOD, 0)):
+ path = Path(directory) / f"{label}.py"
+ path.write_text(source, encoding = "utf-8")
+ count = len(scan_file(path, f"{label}.py"))
+ if count != expected:
+ failures.append(f"{label}: expected {expected} finding(s), got {count}")
+ if failures:
+ print("self-test FAILED:\n " + "\n ".join(failures))
+ return 1
+ print("self-test: ok")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/security/test_lint_exec_literals.py b/tests/security/test_lint_exec_literals.py
new file mode 100644
index 00000000000..6907c02eafa
--- /dev/null
+++ b/tests/security/test_lint_exec_literals.py
@@ -0,0 +1,230 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""`scripts/lint_exec_literals.py` fails CI on a new non-literal exec/eval/compile.
+
+The rule is coarse on purpose, so what these pin is the shape of the coarseness: which
+calls it fires on, which it leaves alone, and that the baseline cannot be used to
+smuggle a new call site past it.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "lint_exec_literals.py"
+BASELINE = SCRIPT.parent / "exec_literals_baseline.json"
+
+
+def _module():
+ spec = importlib.util.spec_from_file_location("lint_exec_literals_under_test", SCRIPT)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def _findings(
+ tmp_path,
+ source,
+ name = "sample.py",
+):
+ sample = tmp_path / name
+ sample.write_text(source, encoding = "utf-8")
+ return _module().scan_file(sample, name)
+
+
+REPORTED = {
+ "an f-string with a placeholder": 'def f(n):\n exec(f"import {n}")\n',
+ "concatenation with a name": 'def f(n):\n eval("torch." + n)\n',
+ "a bare name": "def f(source):\n exec(source)\n",
+ "a call": "def f():\n exec(download())\n",
+ "a value built by replace": 'def f(n):\n exec("import X".replace("X", n))\n',
+ "compile of a name": 'def f(s):\n compile(s, "<x>", "exec")\n',
+ "an f-string through a keyword sink": 'def f(n):\n eval(f"{n}", {})\n',
+}
+
+QUIET = {
+ "a written-out string": 'exec("import torch")\n',
+ "an f-string with no placeholder": 'exec(f"import torch")\n',
+ "two written-out strings added": 'exec("import " + "torch")\n',
+ "bytes": 'exec(b"import torch")\n',
+ "re.compile, which is not the builtin": "import re\ndef f(p):\n re.compile(p)\n",
+ "model.eval, which is not the builtin": "def f(m):\n m.eval()\n",
+ "a sink with no arguments": "exec()\n",
+ "a name that merely shares the spelling": "def f(exec):\n return exec\n",
+}
+
+
[email protected]("description", sorted(REPORTED))
+def test_a_value_that_is_not_written_out_is_reported(tmp_path, description):
+ assert _findings(tmp_path, REPORTED[description]), description
+
+
[email protected]("description", sorted(QUIET))
+def test_a_written_out_value_is_left_alone(tmp_path, description):
+ assert not _findings(tmp_path, QUIET[description]), description
+
+
+def test_a_notebook_cell_is_read_as_python(tmp_path):
+ """The notebooks in this repository are the maintained source, not the .py files."""
+ sample = tmp_path / "demo.ipynb"
+ sample.write_text(
+ json.dumps(
+ {
+ "cells": [
+ {"cell_type": "markdown", "metadata": {}, "source": ["# not code\n"]},
+ {
+ "cell_type": "code",
+ "metadata": {},
+ "execution_count": None,
+ "outputs": [],
+ "source": [
+ "%pip install unsloth\n",
+ "name = input()\n",
+ 'exec(f"import {name}")\n',
+ ],
+ },
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5,
+ }
+ )
+ )
+ found = _module().scan_file(sample, "demo.ipynb")
+ assert len(found) == 1, found
+
+
+def test_a_magic_line_does_not_shift_the_reported_line_number(tmp_path):
+ """A `%magic` is blanked rather than dropped, so the number still points at the cell."""
+ sample = tmp_path / "demo.ipynb"
+ sample.write_text(
+ json.dumps(
+ {
+ "cells": [
+ {
+ "cell_type": "code",
+ "metadata": {},
+ "execution_count": None,
+ "outputs": [],
+ "source": [
+ "%pip install unsloth\n",
+ "!echo hi\n",
+ "import os\n",
+ 'exec(f"import {os.name}")\n',
+ ],
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5,
+ }
+ )
+ )
+ found = _module().scan_file(sample, "demo.ipynb")
+ assert [f["line"] for f in found] == [4], found
+
+
+def test_the_baseline_matches_the_tree_it_was_recorded_against():
+ """A stale entry silently re-permits whatever lands on that digest next."""
+ proc = subprocess.run(
+ [sys.executable, str(SCRIPT)], capture_output = True, text = True, cwd = SCRIPT.parents[1]
+ )
+ assert proc.returncode == 0, f"{proc.stdout}\n{proc.stderr}"
+
+
+def test_the_gate_fails_on_a_call_the_baseline_does_not_have(tmp_path):
+ """The point of the gate: a new site is a build failure, not a note."""
+ sample = tmp_path / "new_offender.py"
+ sample.write_text('def f(n):\n exec(f"import {n}")\n')
+ proc = subprocess.run(
+ [sys.executable, str(SCRIPT), "--paths", str(sample)],
+ capture_output = True,
+ text = True,
+ cwd = SCRIPT.parents[1],
+ )
+ assert proc.returncode == 1, f"{proc.stdout}\n{proc.stderr}"
+ assert "not in the baseline" in proc.stdout, proc.stdout
+
+
+def test_the_digest_follows_what_is_passed_rather_than_where_it_sits(tmp_path):
+ """Moving a call must not churn the baseline; changing its argument must."""
+ module = _module()
+ moved = _findings(tmp_path, 'import os\n\n\ndef f(n):\n exec(f"import {n}")\n', "a.py")
+ same = _findings(tmp_path, 'def f(n):\n exec(f"import {n}")\n', "a.py")
+ changed = _findings(tmp_path, 'def f(n):\n exec(f"import {n}!")\n', "a.py")
+ assert moved[0]["digest"] == same[0]["digest"], "a line move changed the digest"
+ assert moved[0]["digest"] != changed[0]["digest"], "a changed argument kept the digest"
+ assert module is not None
+
+
+def test_the_self_test_is_wired_into_ci():
+ """Guards the guard: an unrun gate is not a gate."""
+ workflow = (SCRIPT.parents[1] / ".github" / "workflows" / "lint-ci.yml").read_text(
+ encoding = "utf-8"
+ )
+ assert "lint_exec_literals.py --self-test" in workflow
+ assert "lint_exec_literals.py\n" in workflow
+
+
+def test_the_baseline_targets_still_exist():
+ """A target that resolves to nothing means the gate covers less than it claims."""
+ document = json.loads(BASELINE.read_text(encoding = "utf-8"))
+ root = SCRIPT.parents[1]
+ missing = [t for t in document["targets"] if not (root / t).exists()]
+ assert not missing, missing
+
+
+def test_update_keeps_the_justifications_that_are_already_there(tmp_path, monkeypatch):
+ """Rebuilding the list from scratch is how a reviewed entry becomes unreviewed."""
+ module = _module()
+ sample = tmp_path / "held.py"
+ sample.write_text('def f(n):\n exec(f"import {n}")\n')
+ baseline = tmp_path / "baseline.json"
+ monkeypatch.setattr(module, "BASELINE_PATH", baseline)
+ monkeypatch.setattr(module, "REPO_ROOT", tmp_path)
+ baseline.write_text(json.dumps({"targets": ["held.py"], "entries": []}))
+
+ monkeypatch.setattr(sys, "argv", ["x", "--update"])
+ assert module.main() == 0
+ written = json.loads(baseline.read_text())
+ assert written["entries"], "nothing was recorded"
+ written["entries"][0]["reason"] = "reviewed: the name is validated above"
+ baseline.write_text(json.dumps(written))
+
+ monkeypatch.setattr(sys, "argv", ["x", "--update"])
+ assert module.main() == 0
+ assert json.loads(baseline.read_text())["entries"][0]["reason"] == (
+ "reviewed: the name is validated above"
+ )
+
+
+def test_an_entry_with_no_justification_fails_the_gate(tmp_path, monkeypatch):
+ """A recorded call that nobody explained is not a reviewed call."""
+ module = _module()
+ sample = tmp_path / "held.py"
+ sample.write_text('def f(n):\n exec(f"import {n}")\n')
+ baseline = tmp_path / "baseline.json"
+ monkeypatch.setattr(module, "BASELINE_PATH", baseline)
+ monkeypatch.setattr(module, "REPO_ROOT", tmp_path)
+ baseline.write_text(json.dumps({"targets": ["held.py"], "entries": []}))
+ monkeypatch.setattr(sys, "argv", ["x", "--update"])
+ assert module.main() == 0
+
+ monkeypatch.setattr(sys, "argv", ["x"])
+ assert module.main() == 1, "an unreviewed entry passed the gate"
+
+
+def test_every_baseline_entry_carries_a_reason():
+ """The committed baseline, not a synthetic one."""
+ document = json.loads(BASELINE.read_text(encoding = "utf-8"))
+ bare = [
+ e["file"] for e in document["entries"] if not e.get("reason") or e["reason"] == "REVIEW ME"
+ ]
+ assert not bare, bare