fix(chat-template): catch getattr and alias bypasses and pin operator vLLM kwargs

The completeness guard only flagged x.apply_chat_template(...) calls, so a
getattr call, a getattr or bound-method alias, or functools.partial passed
it. It now flags any apply_chat_template attribute or getattr lookup outside
the helper unless it is passed directly to callable() or hasattr(), and the
two capability probes use that form.

When an operator passes --default-chat-template-kwargs without date_string,
merge the pinned date into that JSON object (operator keys win) instead of
leaving vLLM unpinned. Document that scripts/ stays unpinned, the vLLM
version that first has the flag, that every resolved spec digest changes,
and that older verify-checkpoint references for date templates will not
match the pinned render.
This commit is contained in:
Joseph Magly committed 2026-11-27 13:50:44 -05:00
1 parent 7b0022ef2f
commit 90eae790a2
7 files changed
+161 -25

No files matched your search

+10 -2
View File
@@ -96,8 +96,16 @@ confidence-interval, and canonical substring-protocol behavior.
results for models whose template renders a date (Llama-3.2 and similar)
measured before this change used the run's own date and are not directly
comparable with new results, or with each other across days; re-measure the
stock baseline. The default verify-edit spec digest changes because of the
new field. Templates without a date render unchanged.
stock baseline. Every resolved verify-edit spec now carries
`generation.date_string`, so every resolved spec digest changes, not only the
default's: margins `resolved_sha256` and calibration and random-control
`spec_sha256`; expect new calibration and confirmation digests. Checkpoint
verification references (`verification_reference.json`) recorded before
this change store input ids rendered with that day's date, so for templates
that render a date they fail with `tokenizer_mismatch`; record a new one. When a `--vllm-command` already sets `--default-chat-template-kwargs`
without `date_string`, the date is added and the operator's keys are kept.
The one-off campaign scripts in `scripts/` call `apply_chat_template`
directly and stay unpinned. Templates without a date render unchanged.
- The release supply-chain `secrets` gate (Gitleaks 8.30.1) now reports zero
findings on the source tree without any suppression, allowlist or ignore
+4
View File
@@ -56,6 +56,10 @@ The command loads the checkpoint in its own process with `local_files_only=True`
`use_safetensors=True` and `trust_remote_code=False`, and tokenizes each reference
prompt again with the reloaded tokenizer, applying its chat template when one is
configured. It then greedy-decodes each prompt, one at a time and without padding.
Chat templates are rendered with a fixed date (`26 Jul 2024`, #690). A reference
recorded before that change for a model whose template renders a date (Llama-3.2
and similar) stored input ids rendered with that day's date, so it fails with
`tokenizer_mismatch`; record a new reference.
Unless `--dtype` is set, the reload uses the dtype recorded with the reference.
The checkpoint passes only when **every** check below holds:
+9 -5
View File
@@ -239,14 +239,18 @@ vllm serve {model} --host 127.0.0.1 --port {port} --served-model-name {served_na
vLLM renders the chat template on the server. When the command is a
`vllm serve` invocation, `verify-edit` appends
`--default-chat-template-kwargs '{"date_string": "<generation.date_string>"}'`
so templates that render a date use the spec's date (vLLM 0.23 and later accept
this flag, and they drop keys a template does not use). If your command already
sets that flag, your value is kept. The value in effect is recorded as
`chat_template_kwargs` in the capability scores. It is `null`, and the date is not
pinned, for an endpoint you serve yourself (`--stock-endpoint` /
so templates that render a date use the spec's date. The flag first appears in
vLLM 0.14.0 (`vllm/entrypoints/openai/cli_args.py`), and vLLM drops keys a
template does not use. If your command already sets that flag to a JSON object
without `date_string`, the spec's date is added to it and your other keys are
kept; if it sets `date_string`, your value is used. The value in effect is
recorded as `chat_template_kwargs` in the capability scores. It is `null`, and
the date is not pinned, for an endpoint you serve yourself (`--stock-endpoint` /
`--edited-endpoint`) and for a launcher that is not `vllm serve`. vLLM only
accepts JSON here, so a template that calls `strftime_now` directly, rather than
reading `date_string`, still uses the server's date. Local rendering pins both.
The one-off campaign scripts in `scripts/` call `apply_chat_template` directly
and do not pin the date.
The lm-eval backend scores MMLU by log-likelihood without a chat template.
The server counts as ready once `GET /v1/models` lists the served name, within
+1 -2
View File
@@ -665,8 +665,7 @@ def _encode_sample(
) -> tuple[int, ...]:
try:
if config.chat_template_mode == "required":
apply_template = getattr(tokenizer, "apply_chat_template", None)
if not callable(apply_template):
if not callable(getattr(tokenizer, "apply_chat_template", None)):
raise ContractError("tokenizer does not expose the required chat-template API")
value = _apply_chat_template(
tokenizer,
+2 -2
View File
@@ -42,8 +42,8 @@ def render_prompts(tokenizer, examples, settings):
"""Map example id to the text given to the tokenizer (chat-rendered when enabled)."""
if not settings["chat_template"]:
return {example.example_id: example.prompt for example in examples}
apply = getattr(tokenizer, "apply_chat_template", None)
if not callable(apply) or not getattr(tokenizer, "chat_template", None):
if (not callable(getattr(tokenizer, "apply_chat_template", None))
or not getattr(tokenizer, "chat_template", None)):
raise SpecError("prompt.chat_template requires a tokenizer that defines a chat template")
rendered = {}
for example in examples:
+28 -6
View File
@@ -88,20 +88,42 @@ def vllm_environment(capability: dict[str, Any]) -> dict[str, str]:
_CHAT_KWARGS_FLAG = "--default-chat-template-kwargs"
def _with_date_string(value: str, date_string: str | None) -> str:
"""Operator template kwargs with ``date_string`` added when absent (operator keys win).
A value that is not a JSON object is returned unchanged; vLLM rejects it at launch.
"""
if date_string is None:
return value
try:
kwargs = json.loads(value)
except ValueError:
return value
if not isinstance(kwargs, dict) or "date_string" in kwargs:
return value
vllm_chat_template_kwargs(date_string) # validates the date
return json.dumps({**kwargs, "date_string": date_string}, separators=(",", ":"))
def pin_chat_template_date(argv: list[str], date_string: str | None) -> str | None:
"""Append the pinned template date to a ``vllm serve`` command line (#690).
"""Pin the template date on a ``vllm serve`` command line (#690).
vLLM renders the chat template server-side, so templates that read
``strftime_now`` would otherwise follow the server's calendar day. Returns
the JSON now in effect: ours when appended, the operator's when the command
already sets the flag, or None when the command is not a recognisable
``vllm serve`` invocation (then the date is not pinned).
``strftime_now`` would otherwise follow the server's calendar day. When the
command already sets ``--default-chat-template-kwargs``, ``date_string`` is
merged into that JSON object unless the operator set it (operator keys win);
otherwise the flag is appended. Returns the JSON now in effect, or None when
the command is not a recognisable ``vllm serve`` invocation (then the date
is not pinned).
"""
for index, token in enumerate(argv):
if token == _CHAT_KWARGS_FLAG and index + 1 < len(argv):
argv[index + 1] = _with_date_string(argv[index + 1], date_string)
return argv[index + 1]
if token.startswith(_CHAT_KWARGS_FLAG + "="):
return token.split("=", 1)[1]
value = _with_date_string(token.split("=", 1)[1], date_string)
argv[index] = f"{_CHAT_KWARGS_FLAG}={value}"
return value
serve = any(Path(token).name == "vllm" and argv[index + 1:index + 2] == ["serve"]
for index, token in enumerate(argv))
if date_string is None or not serve:
+107 -8
View File
@@ -249,8 +249,6 @@ def test_observation_records_the_pinned_date():
@pytest.mark.parametrize("command, expected", [
("vllm serve m --port 1", '{"date_string":"26 Jul 2024"}'),
("env VLLM_X=0 /opt/v/bin/vllm serve m", '{"date_string":"26 Jul 2024"}'),
("vllm serve m --default-chat-template-kwargs '{\"x\":1}'", '{"x":1}'),
("vllm serve m '--default-chat-template-kwargs={\"x\":1}'", '{"x":1}'),
("python -m my_server m", None),
])
def test_vllm_launch_pins_the_template_date(command, expected):
@@ -267,6 +265,41 @@ def test_vllm_launch_pins_the_template_date(command, expected):
assert argv == before
@pytest.mark.parametrize("operator, expected", [
# Operator kwargs without a date: the pinned date is merged in, operator keys kept.
('{"enable_thinking":false}', '{"enable_thinking":false,"date_string":"26 Jul 2024"}'),
# Operator sets the date: their value wins and the flag is left exactly as given.
('{"x":1,"date_string":"01 Jan 2025"}', '{"x":1,"date_string":"01 Jan 2025"}'),
# Not a JSON object: left for vLLM to reject.
("not json", "not json"),
])
@pytest.mark.parametrize("form", ["separate", "equals"])
def test_vllm_operator_template_kwargs_get_the_pinned_date(operator, expected, form):
from obliteratus.verify_edit.capability import pin_chat_template_date
flag = "--default-chat-template-kwargs"
tail = [flag, operator] if form == "separate" else [f"{flag}={operator}"]
argv = ["vllm", "serve", "m", *tail]
assert pin_chat_template_date(argv, "26 Jul 2024") == expected
assert argv[3:] == ([flag, expected] if form == "separate" else [f"{flag}={expected}"])
assert argv.count(flag) + sum(t.startswith(flag + "=") for t in argv) == 1
def test_vllm_server_records_merged_operator_kwargs(tmp_path):
from obliteratus.verify_edit.capability import VllmServer
launcher = tmp_path / "vllm"
launcher.write_text("#!/bin/sh\n")
launcher.chmod(0o755)
server = VllmServer(
f"{launcher} serve {{model}} --default-chat-template-kwargs '{{{{\"enable_thinking\":false}}}}'",
model="m", served_name="s", port=1, ready_timeout=1, log_path=tmp_path / "log",
chat_template_date="01 Jan 2025")
merged = '{"enable_thinking":false,"date_string":"01 Jan 2025"}'
assert server.argv[-2:] == ["--default-chat-template-kwargs", merged]
assert server.chat_template_kwargs == merged
def test_vllm_server_records_the_pinned_kwargs(tmp_path):
from obliteratus.verify_edit.capability import VllmServer
@@ -280,21 +313,87 @@ def test_vllm_server_records_the_pinned_kwargs(tmp_path):
assert server.chat_template_kwargs == '{"date_string":"01 Jan 2025"}'
def _unpinned_calls(path):
tree = ast.parse(path.read_text(encoding="utf-8"))
return [node.lineno for node in ast.walk(tree)
if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
and node.func.attr == "apply_chat_template"]
_METHOD = "apply_chat_template"
# Dynamic lookups that can reach the method by name.
_NAME_LOOKUPS = {"getattr", "attrgetter", "methodcaller"}
# Capability probes: they test that the method exists and cannot render anything.
_PROBES = {"callable", "hasattr"}
def _call_name(node):
func = node.func
return func.id if isinstance(func, ast.Name) else getattr(func, "attr", None)
def _unpinned_uses(source):
"""Lines that reach ``apply_chat_template`` other than through the pinning helper.
Any ``x.apply_chat_template`` attribute and any ``getattr(x, "apply_chat_template")``
(or ``operator.attrgetter`` / ``methodcaller`` by that name) is flagged, whether it is
called, aliased, bound or wrapped in ``functools.partial``. Only a lookup passed
directly to ``callable(...)`` or ``hasattr(...)`` is allowed, because a probe never
renders a template.
"""
tree = ast.parse(source)
parents = {child: node for node in ast.walk(tree) for child in ast.iter_child_nodes(node)}
def probed(node):
parent = parents.get(node)
return (isinstance(parent, ast.Call) and node in parent.args
and isinstance(parent.func, ast.Name) and parent.func.id in _PROBES)
found = []
for node in ast.walk(tree):
if isinstance(node, ast.Attribute) and node.attr == _METHOD:
reaches = True
elif isinstance(node, ast.Call) and _call_name(node) in _NAME_LOOKUPS:
reaches = any(isinstance(arg, ast.Constant) and arg.value == _METHOD
for arg in node.args)
else:
reaches = False
if reaches and not probed(node):
found.append(node.lineno)
return sorted(found)
def test_no_package_call_site_renders_a_template_without_the_pinned_date():
sources = [ROOT / "app.py", *sorted((ROOT / "obliteratus").rglob("*.py"))]
helper = ROOT / "obliteratus" / "chat_template_date.py"
found = {str(path.relative_to(ROOT)): lines for path in sources if path != helper
for lines in [_unpinned_calls(path)] if lines}
for lines in [_unpinned_uses(path.read_text(encoding="utf-8"))] if lines}
assert found == {}
@pytest.mark.parametrize("snippet", [
"tok.apply_chat_template(messages)",
'getattr(tok, "apply_chat_template")(messages)',
'apply = getattr(tok, "apply_chat_template", None)\napply(messages)',
"apply = tok.apply_chat_template\napply(messages)",
"functools.partial(tok.apply_chat_template, tokenize=False)(messages)",
'functools.partial(getattr(tok, "apply_chat_template"), tokenize=False)(messages)',
'operator.methodcaller("apply_chat_template", messages)(tok)',
'operator.attrgetter("apply_chat_template")(tok)(messages)',
'if callable(apply := getattr(tok, "apply_chat_template", None)):\n apply(messages)',
], ids=["direct", "getattr-call", "getattr-alias", "bound-alias", "partial", "getattr-partial",
"methodcaller", "attrgetter", "walrus-in-probe"])
def test_completeness_guard_flags_every_way_to_reach_the_method(snippet):
assert _unpinned_uses(snippet) != []
@pytest.mark.parametrize("snippet", [
'if not callable(getattr(tok, "apply_chat_template", None)):\n raise E',
"ok = callable(tok.apply_chat_template)",
'if hasattr(tok, "apply_chat_template"):\n pass',
"ctd_apply(tok, messages)",
"from obliteratus.chat_template_date import apply_chat_template as render",
'getattr(pipeline, "_maybe_apply_chat_template", None)',
"pipeline._apply_chat_template_no_think(messages)",
], ids=["callable-getattr", "callable-attr", "hasattr", "helper-call", "helper-import",
"other-name-getattr", "other-name-attr"])
def test_completeness_guard_allows_capability_probes_and_the_helper(snippet):
assert _unpinned_uses(snippet) == []
def test_evaluation_profiles_carry_the_spec_date():
from obliteratus.recipes.evaluation_profiles import profile_from_spec, resolve_profile
from obliteratus.recipes.validation import RecipeError