diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 242c4333..372531d8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1610,16 +1610,17 @@ jobs: echo " $listed " | grep -q " $name " || { echo "$f is in the repo and install-image.sh never applies it"; exit 1; } done - - name: Every text lane's chat template takes what the real clients send + - name: Every text lane's chat template takes the message shapes the real clients send # opencode 1.19.4 sends two system messages before the user's, and the Ornith lane's # published template refused the second: a 400 on every opencode request from v1.38.6 to # v1.40.1, as each release proved the clients on the lane that served (found 2026-10-24). # This fetches each text target's template at its pin (each of switch-model.sh's targets # but the image and video lanes), patches it as its installer does, and renders the shapes - # the real clients send (tests/fixtures/client-shapes.json), with tools and without, each - # content in the form its engine hands it (vLLM's and SGLang's own reading of the template), - # the way transformers does (280 renders identical to its own on the reference box). A - # template that raises fails here, and so does a text target the check does not know. + # the real clients send (tests/fixtures/client-shapes.json), with tools and without, sent as + # strings and as lists of parts and handed on as each engine hands them (vLLM's and SGLang's + # own reading of the template and conversion of the messages), the way transformers does + # (364 renders identical to its own on the reference box). A template that raises fails + # here, and so do a text target the check does not know and an installer it cannot read. run: | pip install 'jinja2==3.1.6' "$(./tests/testpy.sh jinja2)" tests/lane-templates-check.py diff --git a/tests/lane-templates-check.py b/tests/lane-templates-check.py index da155156..2234bcfb 100644 --- a/tests/lane-templates-check.py +++ b/tests/lane-templates-check.py @@ -9,11 +9,12 @@ release proved the clients on the lane that happened to serve (found on 2026-10- This takes each text lane's chat template at its pinned revision on Hugging Face (chat_template.jinja, or the chat_template of tokenizer_config.json, the one named tool_use when tools are sent and it has one, as transformers picks), patches it as its installer does (patch-template.py with the lane's ---patches, from chat_template.jinja only, as the installer reads it), and renders, as transformers -renders it for vLLM and SGLang, every message shape the real clients send -(tests/fixtures/client-shapes.json), with tools and without, each message's content as a string and as -a list of parts (what vLLM hands a template it reads as taking OpenAI's content format). A template -that raises fails the run, naming the lane and the client. So do a text target of +TEMPLATE_FIXES, from chat_template.jinja only, as the installer reads it), and renders, as +transformers renders it for vLLM and SGLang, every message shape the real clients send +(tests/fixtures/client-shapes.json), with tools and without, sent as strings and as lists of parts, +each handed to the template as its engine hands it (the engines' own reading of the template and +conversion of the messages, ported below). A template that raises fails the run, naming the lane and +the client. So do a text target of switch-model.sh this check does not know (a variant is a target: Kolibri's FP8, its default, and its NVFP4 each have their pin) and a lane whose installer patches its template otherwise than the table below says. @@ -62,17 +63,37 @@ def pin(text, prefix): return repo.group(1), rev.group(1) -def fixes_of(installer_text): +def fixes_of(installer_text, name="the installer"): """What an installer tells patch-template.py, from its one TEMPLATE_FIXES line (vlane_template in vllm-lane.sh runs it with them): None when it patches nothing, else {"patches": its --patches, and - each VAR=value of its environment}.""" + each VAR=value of its environment}. It stops on an installer that runs patch-template.py itself, one + whose call of vlane_template leaves its fixes out, and an option this check cannot pass on (each + would have rendered a template the lane does not serve: code review, 2026-10-24).""" + # patch-template.py named anywhere but in the list of files its preflight checks, however the call + # is written (${HERE}, python3 -I, the file run itself, a line continued): code review, 2026-10-24 + code = [re.sub(r"(^|\s)#.*$", "", line).strip() for line in re.sub(r"\\\n", " ", installer_text).splitlines()] + for line in code: + if "patch-template.py" in line and not line.startswith("vlane_preflight "): + raise SystemExit(f"{name} runs patch-template.py itself: give it a TEMPLATE_FIXES line, run through vlane_template") + calls = [c.group(1) for c in (re.search(r"\bvlane_template(?:_if_cached)? (\S.*?)(?:; *\}|$)", line) for line in code) if c] + if sum(bool(re.match(r"TEMPLATE_FIXES\+?=", line)) for line in code) > 1: + raise SystemExit(f"{name} sets TEMPLATE_FIXES more than once: this check reads one line") m = re.search(r"^TEMPLATE_FIXES=\(([^)]*)\)$", installer_text, re.M) if not m: - return None if "vlane_template" not in installer_text else {"unread": "TEMPLATE_FIXES"} + if calls: + raise SystemExit(f"{name} calls vlane_template without a TEMPLATE_FIXES line this check reads") + return None + if not calls or any(c.strip() != '"$TEMPLATE" "${TEMPLATE_FIXES[@]}"' for c in calls): + raise SystemExit(f'{name} declares TEMPLATE_FIXES and does not pass them all: vlane_template "$TEMPLATE" "${{TEMPLATE_FIXES[@]}}"') spec = {} for item in m.group(1).split(): - key, _, value = item.lstrip("-").partition("=") - spec[key] = value + if item.startswith("--patches="): + spec["patches"] = item[len("--patches="):] + elif re.fullmatch(r"[A-Z][A-Z0-9_]*=\S*", item): + key, _, value = item.partition("=") + spec[key] = value + else: + raise SystemExit(f"{name}: TEMPLATE_FIXES holds {item}, which this check cannot pass to patch-template.py") return spec @@ -85,6 +106,13 @@ def lane_specs(repo_dir=REPO): targets = re.findall(r'^\s+([a-z0-9-]+)\)\s+MODEL_REPO="\$([A-Z0-9_]+)_REPO"', install, re.M) if not targets: raise SystemExit("install.sh no longer maps its targets the way this check reads them") + # the four fixes there: install.sh and switch-model.sh run patch-template.py with no --patches and no + # environment of their own, or this check would render a template they do not write (code review) + for script in ("install.sh", "switch-model.sh"): + calls = [ln.strip() for ln in re.sub(r"\\\n", " ", (repo_dir / script).read_text()).splitlines() + if "patch-template.py" in re.sub(r"(^|\s)#.*$", "", ln)] + if not calls or any("--patches" in c or not c.startswith('python3 "$REPO_DIR/patch-template.py"') for c in calls): + raise SystemExit(f"{script} runs patch-template.py otherwise than with its four fixes: {calls}") specs = [(t, *pin(install, p), {}) for t, p in targets] installers = sorted(f.name for f in repo_dir.glob("install-*.sh") if "vlane_put_unit" in f.read_text()) known = sorted({f for f, _, _ in VLLM_LANES.values()}) @@ -92,7 +120,7 @@ def lane_specs(repo_dir=REPO): raise SystemExit(f"the vLLM lanes are {installers}, this check knows {known}: add the new lane to VLLM_LANES") for name, (installer, prefix, env) in VLLM_LANES.items(): text = (repo_dir / installer).read_text() - if fixes_of(text) != env: + if fixes_of(text, installer) != env: raise SystemExit(f"{installer} serves its template otherwise than VLLM_LANES says for {name}") specs.append((name, *pin(text, prefix), env)) switch = re.search(r'^case "\$CHOICE" in ([a-z0-9|-]+)\) ;;', (repo_dir / "switch-model.sh").read_text(), re.M) @@ -123,11 +151,20 @@ def server_wait(headers): return min(int(after), WAIT_MAX) if after.isdigit() else None +# transformers reads a repo's named templates there too, beside chat_template.jinja (its +# list_repo_templates and _from_pretrained, 5.12.1): none of the targets has one on 2026-10-24 +EXTRA_TEMPLATES = "additional_chat_templates" + + def fetch(repo, rev, tries=5, sleep=time.sleep): - """(the chat template the engine reads at that revision, the file it comes from): chat_template.jinja, - else the chat_template of tokenizer_config.json, a dict of them by name when it names several.""" - def get(path): - url = f"https://huggingface.co/{repo}/resolve/{rev}/{path}" + """(the chat template the engine reads at that revision, the file it comes from), as transformers + assembles it: chat_template.jinja as the template named default, and the named templates of + additional_chat_templates/, a dict of them by name when there are more than the default; without + either, the chat_template of tokenizer_config.json, a dict by name when it names several.""" + def resolve(path): + return get(f"https://huggingface.co/{repo}/resolve/{rev}/{path}") + + def get(url): for attempt in range(tries): wait = 2 ** (attempt + 1) try: @@ -144,10 +181,19 @@ def fetch(repo, rev, tries=5, sleep=time.sleep): if attempt == tries - 1: raise sleep(wait) - tpl = get("chat_template.jinja") - if tpl is not None: - return tpl, "chat_template.jinja" - t = json.loads(get("tokenizer_config.json") or "{}").get("chat_template") + templates = {} + default = resolve("chat_template.jinja") + if default is not None: + templates["default"] = default + listing = get(f"https://huggingface.co/api/models/{repo}/tree/{rev}/{EXTRA_TEMPLATES}") + for entry in json.loads(listing) if listing else []: + path = entry.get("path") or "" + if entry.get("type") == "file" and path.endswith(".jinja"): + templates[path.rsplit("/", 1)[-1][:-len(".jinja")]] = resolve(path) + if templates: + source = "chat_template.jinja" if default is not None else EXTRA_TEMPLATES + return (templates["default"] if list(templates) == ["default"] else templates), source + t = json.loads(resolve("tokenizer_config.json") or "{}").get("chat_template") if isinstance(t, list): t = {x.get("name"): x.get("template") for x in t if isinstance(x, dict) and x.get("template")} if not t: @@ -177,54 +223,70 @@ def served(repo, rev, fetched, spec): raise SystemExit(f"{repo}@{rev[:12]}: its installer patches chat_template.jinja, which it does not have") spec = dict(spec) patches = spec.pop("patches", None) + named = template if isinstance(template, dict) else {"default": template} with tempfile.TemporaryDirectory(prefix="lane-tpl-") as d: snap = Path(d, "hub", f"models--{repo.replace('/', '--')}", "snapshots", rev) snap.mkdir(parents=True) - (snap / "chat_template.jinja").write_text(template) + (snap / "chat_template.jinja").write_text(named["default"]) out = Path(d, "served.jinja") argv = [sys.executable, str(REPO / "patch-template.py")] + ([f"--patches={patches}"] if patches else []) r = subprocess.run(argv + [d, str(out), rev, repo], capture_output=True, text=True, env={**os.environ, **spec}) if r.returncode != 0: raise SystemExit(f"patch-template.py refused {repo}@{rev[:12]}:\n{r.stdout}{r.stderr}") + # the installer patches chat_template.jinja alone and hands that file to the engine with + # --chat-template, which serves it to every request: a named template of the repo goes unused + # (second review, 2026-10-24) return out.read_text() def environment(): """A Jinja environment as transformers compiles chat templates with: sandboxed, blocks trimmed, - loop controls, raise_exception, tojson and strftime_now.""" + loop controls, its {% generation %} tag, raise_exception, tojson and strftime_now.""" import jinja2 - from jinja2.ext import loopcontrols + from jinja2.ext import Extension, loopcontrols from jinja2.sandbox import ImmutableSandboxedEnvironment + class Generation(Extension): + """transformers' AssistantTracker without its tracking: {% generation %} renders its body. A + template that marks its assistant turns so read as a refusal here (code review, 2026-10-24).""" + tags = {"generation"} + + def parse(self, parser): + lineno = next(parser.stream).lineno + body = parser.parse_statements(["name:endgeneration"], drop_needle=True) + return jinja2.nodes.CallBlock(self.call_method("_body"), [], [], body).set_lineno(lineno) + + def _body(self, caller): + return caller() + def raise_exception(message): raise jinja2.exceptions.TemplateError(message) def tojson(x, ensure_ascii=False, indent=None, separators=None, sort_keys=False): return json.dumps(x, ensure_ascii=ensure_ascii, indent=indent, separators=separators, sort_keys=sort_keys) - env = ImmutableSandboxedEnvironment(trim_blocks=True, lstrip_blocks=True, extensions=[loopcontrols]) + env = ImmutableSandboxedEnvironment(trim_blocks=True, lstrip_blocks=True, extensions=[loopcontrols, Generation]) env.filters["tojson"] = tojson env.globals["raise_exception"] = raise_exception env.globals["strftime_now"] = lambda fmt: datetime.now().strftime(fmt) return env -# How each engine hands a template a message's content (read in their sources on 2026-10-24). vLLM -# (vllm/renderers/hf.py, _detect_content_format) reads the template: one that loops over a message's -# content takes "openai" content, a list of parts, into which vLLM turns a string too; any other -# takes "string". SGLang (sglang/srt/parser/jinja_template_utils.py, -# detect_jinja_template_content_format) reads it more simply, and leaves a string a string: a list -# reaches the template only when the client sent one and the template takes "openai". So a vLLM lane -# is rendered with the content vLLM makes, and an SGLang lane with strings, and with lists too when -# its template takes them. The detectors below are those two functions, ported (Apache-2.0). +# How each engine hands a template a message's content, read in their sources on 2026-10-24: vLLM at +# the commits its lanes pin (8244d1c4 for Flash FP4-Local and Ornith, 77154ca6 for the two Nemotron +# lanes, v0.29.0 for Kolibri), SGLang at v0.5.22 (the 27B) and at the flash lane's nightly 53295c6, +# whose code for it is the same. Both read the template first. vLLM's _detect_content_format gives +# "openai" to one that loops over a message's content, and every content then reaches it as a list of +# text parts, a string included; any other gets "string", the parts joined by a newline. SGLang's +# detect_jinja_template_content_format reads it more simply, and leaves a string a string: a list +# reaches the template only when the client sent one and the template takes "openai", else its text +# joined by a space. Both make a tool's text parts one string. The detectors and the conversions below +# are theirs, ported (Apache-2.0): the check renders what a client sends, strings and lists of parts, +# as its engine hands it on (the check rendered a tool's answer as a list, which neither engine does, +# and vLLM's empty assistant content as a string: code review, 2026-10-24). def _var(node, name): import jinja2.nodes as n - if isinstance(node, n.Name): - return node.ctx == "load" and node.name == name - if isinstance(node, n.Getattr) and "." in name: - base, _, attr = name.rpartition(".") - return node.attr == attr and _var(node.node, base) - return False + return isinstance(node, n.Name) and node.ctx == "load" and node.name == name def _attr(node, name, key): @@ -247,15 +309,9 @@ def _elems(node, name, key=None): return _attr(node, name, key) if key else _var(node, name) -def _dotted(node): - import jinja2.nodes as n - if isinstance(node, n.NSRef): - return f"{node.name}.{node.attr}" - parts = [] - while isinstance(node, n.Getattr): - parts.append(node.attr) - node = node.node - return ".".join([node.name, *reversed(parts)]) if isinstance(node, n.Name) else None +class _NotAName(Exception): + """vLLM asserts that what takes the messages, or a loop's item over them, is a plain variable: its + detector stops there, and the template gets its default, "string".""" def _aliases_of(root, name): @@ -265,35 +321,36 @@ def _aliases_of(root, name): while todo: cur = todo.pop(0) for a in root.find_all(n.Assign): - lhs, rhs, found = a.target, a.node, [] - if isinstance(lhs, n.Name) and _elems(rhs, cur): - found = [lhs.name] - elif (isinstance(lhs, n.Name) and isinstance(rhs, n.Call) and isinstance(rhs.node, n.Name) - and rhs.node.name == "namespace"): - found = [f"{lhs.name}.{kw.key}" for kw in rhs.kwargs if _elems(kw.value, cur)] - elif isinstance(lhs, (n.Getattr, n.NSRef)) and _elems(rhs, cur): - found = [d for d in [_dotted(lhs)] if d] - for alias in found: - out.append(alias) - if alias not in seen: - seen.add(alias) - todo.append(alias) + if _elems(a.node, cur): + if not isinstance(a.target, n.Name): + raise _NotAName(cur) + out.append(a.target.name) + if a.target.name not in seen: + seen.add(a.target.name) + todo.append(a.target.name) return out -def vllm_takes_parts(template, env): - """vLLM's _detect_content_format: True for "openai", False for "string" (and for a template it - cannot parse, its default).""" +def vllm_takes_parts(template, env, macros=True): + """vLLM's _detect_content_format: True for "openai", False for "string". macros=True as at 8244d1c4 + and 77154ca6, which follow a message's content into a macro's parameter and leave a macro's other + loops over a variable named content alone; False as at v0.29.0, where any loop over such a variable + counts. A template it cannot parse, or one that puts its messages into anything but a plain + variable, gets the default, "string".""" import jinja2.nodes as n try: root = env.parse(template) - except Exception: # noqa: BLE001 + messages = _aliases_of(root, "messages") + except Exception: # noqa: BLE001: vLLM falls back to its default here return False - messages = _aliases_of(root, "messages") - message_vars = [loop.target.name for loop in root.find_all(n.For) - if isinstance(loop.target, n.Name) and any(_elems(loop.iter, v) for v in messages)] + message_vars = [] + for loop in root.find_all(n.For): + if any(_elems(loop.iter, v) for v in messages): + if not isinstance(loop.target, n.Name): + return False + message_vars.append(loop.target.name) params_by_loop, in_macros = {}, set() - for macro in root.find_all(n.Macro): + for macro in (root.find_all(n.Macro) if macros else ()): names, params = {a.name for a in macro.args}, set() for call in root.find_all(n.Call): if isinstance(call.node, n.Name) and call.node.name == macro.name: @@ -308,12 +365,10 @@ def vllm_takes_parts(template, env): if params: params_by_loop[id(loop)] = params for loop in root.find_all(n.For): - if any(_elems(loop.iter, v, "content") for v in message_vars): - return True - if isinstance(loop.iter, n.Name) and loop.iter.name in params_by_loop.get(id(loop), ()): - return True - if id(loop) not in in_macros and isinstance(loop.iter, n.Name) and loop.iter.name == "content": - return True + if (any(_elems(loop.iter, v, "content") for v in message_vars) + or isinstance(loop.iter, n.Name) and loop.iter.name in params_by_loop.get(id(loop), ()) + or id(loop) not in in_macros and isinstance(loop.iter, n.Name) and loop.iter.name == "content"): + return isinstance(loop.target, n.Name) return False @@ -329,11 +384,49 @@ def sglang_takes_parts(template, env): return any(_elems(loop.iter, v, "content") for loop in root.find_all(n.For) for v in ("message", "msg", "m")) -def content_forms(template, engine, env): - """The forms a message's content reaches this template in: False a string, True a list of parts.""" - if engine == "vllm": - return [vllm_takes_parts(template, env)] - return [False, True] if sglang_takes_parts(template, env) else [False] +def vllm_hands(msgs, openai): + """The messages as vLLM hands them to a template (_parse_chat_message_content): for one that takes + "openai" content, each content a list of text parts, a string made one part and none none, and a + tool's text parts joined by a newline; for any other, the text parts joined by a newline, empty ones + left out.""" + out = [] + for m in msgs: + c = m.get("content") + texts = [] if c is None else [c] if isinstance(c, str) else [p["text"] for p in c] + if not openai: + content = "\n".join(t for t in texts if t) + elif m["role"] == "tool": + content = "\n".join(texts) + else: + content = [{"type": "text", "text": t} for t in texts] + out.append({**m, "content": content}) + return out + + +def sglang_hands(msgs, openai): + """The messages as SGLang hands them to a template (serving_chat.py): no content is "", a string + stays a string, a list stays a list for a template that takes "openai" content, else its text + joined by a space (process_content_for_template_format), and a tool's text parts are one string, + joined by a space (normalize_tool_content).""" + out = [] + for m in msgs: + c = "" if m.get("content") is None else m["content"] + if isinstance(c, list) and (not openai or m["role"] == "tool"): + c = " ".join(p["text"] for p in c) + out.append({k: v for k, v in {**m, "content": c}.items() if v is not None}) + return out + + +# vLLM's detector as at each vLLM lane's pin: the Kolibri lane's image is vLLM v0.29.0 (install-kolibri.sh, +# its LOCAL_IMAGE), which reads no macro's parameter; the others are later. +VLLM_WITHOUT_MACROS = {"kolibri", "kolibri-nvfp4"} + + +def engine_reads(name, template, env): + """(the engine, True when it takes "openai" content) for this target's template.""" + if name in VLLM_LANES: + return "vllm", vllm_takes_parts(template, env, macros=name not in VLLM_WITHOUT_MACROS) + return "sglang", sglang_takes_parts(template, env) TOOLS = [{"type": "function", "function": { @@ -342,13 +435,14 @@ TOOLS = [{"type": "function", "function": { def messages(roles, parts=False): - """A conversation of these roles, with a tool call where the shape has one; each content a string, - or with parts, a list of text parts, as vLLM hands a template that takes OpenAI's content format.""" + """A conversation of these roles as a client sends it, with a tool call where the shape has one: + each content a string, or with parts, a list of text parts, and a tool call's own content null, as + the OpenAI API returns it and an agent on its SDK sends it back.""" text = (lambda t: [{"type": "text", "text": t}]) if parts else (lambda t: t) out = [] for i, role in enumerate(roles): if role == "assistant_tool_call": - out.append({"role": "assistant", "content": "", "tool_calls": [{ + out.append({"role": "assistant", "content": None if parts else "", "tool_calls": [{ "id": f"call_{i}", "type": "function", "function": {"name": "read", "arguments": {"path": "hello.txt"}}}]}) elif role == "tool": @@ -358,10 +452,12 @@ def messages(roles, parts=False): return out -def render(env, template, roles, tools, parts=False): - """None when the template renders this conversation, else why it does not.""" +def render(env, template, roles, tools, parts=False, hands=None): + """None when the template renders this conversation, as the engine hands it on, else why it does not.""" + msgs = messages(roles, parts) + msgs = hands(msgs) if hands else msgs # outside the try: a fault of the check is not the template's refusal try: - env.from_string(pick(template, tools)).render(messages=messages(roles, parts), tools=tools, + env.from_string(pick(template, tools)).render(messages=msgs, tools=tools, add_generation_prompt=True, bos_token="", eos_token="") return None except Exception as e: # noqa: BLE001: any refusal of the template is the finding @@ -377,25 +473,32 @@ CANARY = ("{%- for m in messages %}{%- if m.role == 'system' and not loop.first def main(): shapes = json.loads(SHAPES.read_text())["shapes"] env = environment() - if render(env, CANARY, ["system", "system", "user"], None) is None: - raise SystemExit("the renderer did not see the canary's refusal: this check would pass on anything") + # through each engine's conversion of the messages too, in each of its readings: a conversion that lost + # them would pass anything (code review, 2026-10-24) + for hands in (None, *[lambda m, h=h, o=o: h(m, o) for h in (vllm_hands, sglang_hands) for o in (False, True)]): + for parts in (False, True): + if render(env, CANARY, ["system", "system", "user"], None, parts, hands) is None: + raise SystemExit("the renderer did not see the canary's refusal: this check would pass on anything") failed = renders = 0 for name, repo, rev, patch in lane_specs(): template = served(repo, rev, fetch(repo, rev), patch) - engine = "vllm" if name in VLLM_LANES else "sglang" how = "as published" if patch is None else f"patched ({patch.get('patches', 'all four fixes')})" - forms = sorted({p for tools in (None, TOOLS) for p in content_forms(pick(template, tools), engine, env)}) - print(f"{name}: {repo}@{rev[:12]}, {how}, {engine}, content as " - + " and ".join("parts" if p else "a string" for p in forms)) + reads = {tools is not None: engine_reads(name, pick(template, tools), env) for tools in (None, TOOLS)} + engine = reads[False][0] + said = {("vllm", True): "lists of parts", ("sglang", True): "what the client sends"} + takes = " and ".join(sorted({said.get(r, "strings") for r in reads.values()})) + print(f"{name}: {repo}@{rev[:12]}, {how}, {engine}, which hands it {takes}") + hands_of = vllm_hands if engine == "vllm" else sglang_hands for shape in shapes: for tools in (None, TOOLS): - for parts in content_forms(pick(template, tools), engine, env): + openai = reads[tools is not None][1] + for parts in (False, True): renders += 1 - why = render(env, template, shape["roles"], tools, parts) + why = render(env, template, shape["roles"], tools, parts, lambda m: hands_of(m, openai)) if why: failed += 1 print(f" REFUSED {shape['client']}{' with tools' if tools else ''}" - f"{', content as parts' if parts else ''}: {why}") + f"{', sent as parts' if parts else ''}: {why}") print(f"{renders} renders, {failed} refusal(s)") return 1 if failed else 0 diff --git a/tests/test_lane_templates_check.py b/tests/test_lane_templates_check.py index 8061f40a..3396ddaa 100644 --- a/tests/test_lane_templates_check.py +++ b/tests/test_lane_templates_check.py @@ -61,6 +61,62 @@ class TheLanesItKnows(unittest.TestCase): with self.assertRaisesRegex(SystemExit, "install-ornith-122b.sh serves its template otherwise"): ltc.lane_specs(d) + def edit(self, old, new): + d = self.copy() + f = d / "install-ornith-122b.sh" + text = f.read_text() + self.assertIn(old, text) + f.write_text(text.replace(old, new)) + return d + + def test_an_installer_that_runs_the_patcher_itself_stops_it(self): + # it would read as serving its template as published, however the call is written (code + # review, 2026-10-24) + calls = ['python3 "$HERE/patch-template.py" "$HF_CACHE" "$TEMPLATE" "$MODEL_REV" "$MODEL"', + 'python3 "${HERE}/patch-template.py" "$HF_CACHE" "$TEMPLATE"', + 'python3 -I "$HERE/patch-template.py" "$HF_CACHE" "$TEMPLATE"', + '"$HERE/patch-template.py" "$HF_CACHE" "$TEMPLATE"', + 'python3 "$HERE"/patch-template.py "$HF_CACHE" "$TEMPLATE"', + 'python3 \\\n "$HERE/patch-template.py" "$HF_CACHE" "$TEMPLATE"'] + for call in calls: + with self.subTest(call=call): + d = self.edit('TEMPLATE_FIXES=(--patches=system-reminder)\n', call + "\n") + with self.assertRaisesRegex(SystemExit, "runs patch-template.py itself"): + ltc.lane_specs(d) + + def test_fixes_set_twice_stop_it(self): + d = self.edit("TEMPLATE_FIXES=(--patches=system-reminder)\n", + "TEMPLATE_FIXES=(--patches=system-reminder)\nTEMPLATE_FIXES+=(LEAN_DEFAULT=0)\n") + with self.assertRaisesRegex(SystemExit, "sets TEMPLATE_FIXES more than once"): + ltc.lane_specs(d) + + def test_the_27b_and_flash_patcher_calls_are_read_too(self): + # the check gives their targets the four fixes: a call of install.sh or switch-model.sh with fixes + # of its own would pass it unseen, as the first push of this release did (code review, 2026-10-24) + for script in ("install.sh", "switch-model.sh"): + with self.subTest(script=script): + d = self.copy() + f = d / script + text = f.read_text() + self.assertIn('python3 "$REPO_DIR/patch-template.py"', text) + f.write_text(text.replace('python3 "$REPO_DIR/patch-template.py"', + 'python3 "$REPO_DIR/patch-template.py" --patches=system-reminder', 1)) + with self.assertRaisesRegex(SystemExit, f"{script} runs patch-template.py otherwise"): + ltc.lane_specs(d) + + def test_the_patcher_in_a_preflight_list_is_no_call(self): + self.assertEqual({name for name, _, _, env in ltc.lane_specs() if env and "patches" in env}, {"ornith-122b"}) + + def test_fixes_left_out_of_a_call_stop_it(self): + d = self.edit('vlane_template_if_cached "$TEMPLATE" "${TEMPLATE_FIXES[@]}"', 'vlane_template_if_cached "$TEMPLATE"') + with self.assertRaisesRegex(SystemExit, "does not pass them all"): + ltc.lane_specs(d) + + def test_an_option_it_cannot_pass_on_stops_it(self): + d = self.edit("TEMPLATE_FIXES=(--patches=system-reminder)", "TEMPLATE_FIXES=(--patches=system-reminder --keep=x)") + with self.assertRaisesRegex(SystemExit, "holds --keep=x"): + ltc.lane_specs(d) + class WhatItRendersAsTheEnginesDo(unittest.TestCase): # three ways the check rendered otherwise than the engines and the installers (code review, 2026-10-24) @@ -102,7 +158,9 @@ class WhatItRendersAsTheEnginesDo(unittest.TestCase): self.assertEqual(ltc.fetch("org/x", "a" * 40, sleep=slept.append), ("TEMPLATE", "chat_template.jinja")) finally: ltc.urllib.request.urlopen = real - self.assertEqual((len(calls), slept), (3, [7, 7])) + # chat_template.jinja three times, then the listing of additional_chat_templates/, which is not there + self.assertEqual((len(calls), slept), (4, [7, 7])) + self.assertTrue(calls[3].endswith("/tree/" + "a" * 40 + "/additional_chat_templates"), calls[3]) def test_a_429_waits_for_the_end_of_hugging_faces_window(self): # its quotas count over windows of five minutes and its 429 says when the window ends, in its @@ -130,29 +188,143 @@ class WhatItRendersAsTheEnginesDo(unittest.TestCase): self.assertEqual(slept, [121, 121]) +class TheNamedTemplatesOfARepo(unittest.TestCase): + # transformers reads additional_chat_templates/ beside chat_template.jinja (second review, 2026-10-24) + def fetched(self, files): + import io + import json as js + import urllib.error + base = "https://huggingface.co/org/x/resolve/" + "a" * 40 + "/" + + def urlopen(url, timeout=60): + if url.endswith("/tree/" + "a" * 40 + "/additional_chat_templates"): + listing = [{"type": "file", "path": p} for p in files if p.startswith("additional_chat_templates/")] + if listing: + return io.BytesIO(js.dumps(listing + [{"type": "directory", "path": "x"}]).encode()) + elif url.startswith(base) and url[len(base):] in files: + return io.BytesIO(files[url[len(base):]].encode()) + raise urllib.error.HTTPError(url, 404, "no", {}, None) + real = ltc.urllib.request.urlopen + ltc.urllib.request.urlopen = urlopen + try: + return ltc.fetch("org/x", "a" * 40, sleep=lambda s: None) + finally: + ltc.urllib.request.urlopen = real + + def test_named_templates_join_the_default(self): + got = self.fetched({"chat_template.jinja": "D", "additional_chat_templates/tool_use.jinja": "T"}) + self.assertEqual(got, ({"default": "D", "tool_use": "T"}, "chat_template.jinja")) + self.assertEqual(ltc.pick(got[0], ltc.TOOLS), "T") + + def test_a_default_jinja_among_the_named_ones_wins_as_in_transformers(self): + got = self.fetched({"chat_template.jinja": "D", "additional_chat_templates/default.jinja": "X"}) + self.assertEqual(got, ("X", "chat_template.jinja")) + + def test_named_ones_alone(self): + got = self.fetched({"additional_chat_templates/tool_use.jinja": "T"}) + self.assertEqual(got, ({"tool_use": "T"}, "additional_chat_templates")) + + def test_a_default_alone_stays_a_string(self): + self.assertEqual(self.fetched({"chat_template.jinja": "D"}), ("D", "chat_template.jinja")) + + def test_a_patched_lane_serves_its_patched_file_alone(self): + # its installer hands the engine that one file with --chat-template, for every request: a named + # template of the repo is never used there (second review, 2026-10-24) + pts = importlib.util.spec_from_file_location("pt_for_named", REPO / "patch-template.py") + pt = importlib.util.module_from_spec(pts) + pts.loader.exec_module(pt) + body = "HEAD\n" + pt.SYSTEM_ANCHOR + "\nTAIL\n" + got = ltc.served("org/x", "a" * 40, ({"default": body, "tool_use": "T"}, "chat_template.jinja"), + {"patches": "system-reminder"}) + self.assertEqual(got, body.replace(pt.SYSTEM_ANCHOR, pt.SYSTEM_PATCHED)) + self.assertEqual(ltc.pick(got, ltc.TOOLS), got) + + class TheContentFormEachEngineHands(unittest.TestCase): - # vLLM turns a string into a list of parts for a template that loops over a message's content, - # SGLang leaves strings alone: rendering lists everywhere refused Kolibri's templates, which - # neither engine hands a list (2026-10-24) + # Each engine reads the template, then hands it the messages its own way, read in their sources: + # rendering lists everywhere refused Kolibri's templates, which neither engine hands a list, and the + # check rendered a tool's answer as a list, which neither engine does (2026-10-24) def setUp(self): self.env = ltc.environment() - def test_vllm_hands_parts_to_a_template_that_loops_over_the_content(self): + def test_vllm_reads_openai_from_a_template_that_loops_over_the_content(self): loops = "{% for m in messages %}{% for c in m['content'] %}{{ c.text }}{% endfor %}{% endfor %}" concat = "{% for m in messages %}{{ m['content'] + '!' }}{% endfor %}" - self.assertEqual(ltc.content_forms(loops, "vllm", self.env), [True]) - self.assertEqual(ltc.content_forms(concat, "vllm", self.env), [False]) + self.assertTrue(ltc.vllm_takes_parts(loops, self.env)) + self.assertFalse(ltc.vllm_takes_parts(concat, self.env)) - def test_vllm_follows_the_content_into_a_macro(self): + def test_vllm_follows_the_content_into_a_macro_after_v0_29(self): macro = ("{% macro show(body) %}{% for part in body %}{{ part.text }}{% endfor %}{% endmacro %}" "{% for m in messages %}{{ show(m.content) }}{% endfor %}") - self.assertEqual(ltc.content_forms(macro, "vllm", self.env), [True]) + self.assertTrue(ltc.vllm_takes_parts(macro, self.env)) + self.assertFalse(ltc.vllm_takes_parts(macro, self.env, macros=False)) + in_macro = ("{% macro show(content) %}{% for part in content %}{{ part }}{% endfor %}{% endmacro %}" + "{% for m in messages %}{{ m.content }}{% endfor %}") + self.assertFalse(ltc.vllm_takes_parts(in_macro, self.env)) + self.assertTrue(ltc.vllm_takes_parts(in_macro, self.env, macros=False)) - def test_sglang_keeps_strings_and_takes_lists_only_where_the_template_does(self): + def test_vllm_gives_its_default_where_its_assertions_fail(self): + # messages put into a namespace, or a loop over them with two targets: vLLM's assert fails and + # its detector falls back to "string", where a loop over the content would have said "openai" + ns = ("{% set ns = namespace(msgs=[]) %}{% set ns.msgs = messages %}" + "{% for m in messages %}{% for c in m.content %}{{ c.text }}{% endfor %}{% endfor %}") + two = "{% for i, m in messages %}{% for c in m.content %}{{ c.text }}{% endfor %}{% endfor %}" + self.assertFalse(ltc.vllm_takes_parts(ns, self.env)) + self.assertFalse(ltc.vllm_takes_parts(two, self.env)) + + def test_sglang_reads_openai_more_simply(self): loops = "{% for message in messages %}{% for c in message.content %}{{ c.text }}{% endfor %}{% endfor %}" - self.assertEqual(ltc.content_forms(loops, "sglang", self.env), [False, True]) - self.assertEqual(ltc.content_forms("{{ messages[0].content }}", "sglang", self.env), [False]) - self.assertEqual(ltc.content_forms("{# image #}{{ messages[0].content }}", "sglang", self.env), [False, True]) + self.assertTrue(ltc.sglang_takes_parts(loops, self.env)) + self.assertFalse(ltc.sglang_takes_parts("{{ messages[0].content }}", self.env)) + self.assertTrue(ltc.sglang_takes_parts("{# image #}{{ messages[0].content }}", self.env)) + + def test_what_vllm_hands_a_template(self): + sent = [{"role": "user", "content": "hi"}, {"role": "assistant", "content": ""}, + {"role": "assistant", "content": None}, {"role": "tool", "content": [{"type": "text", "text": "a"}, + {"type": "text", "text": "b"}]}] + self.assertEqual([m["content"] for m in ltc.vllm_hands(sent, True)], + [[{"type": "text", "text": "hi"}], [{"type": "text", "text": ""}], [], "a\nb"]) + self.assertEqual([m["content"] for m in ltc.vllm_hands(sent, False)], ["hi", "", "", "a\nb"]) + + def test_what_sglang_hands_a_template(self): + parts = [{"type": "text", "text": "a"}, {"type": "text", "text": "b"}] + sent = [{"role": "user", "content": "hi"}, {"role": "user", "content": parts}, + {"role": "assistant", "content": None, "name": None}, {"role": "tool", "content": parts}] + self.assertEqual(ltc.sglang_hands(sent, True), [{"role": "user", "content": "hi"}, {"role": "user", "content": parts}, + {"role": "assistant", "content": ""}, {"role": "tool", "content": "a b"}]) + self.assertEqual([m["content"] for m in ltc.sglang_hands(sent, False)], ["hi", "a b", "", "a b"]) + + def test_kolibris_vllm_reads_no_macro(self): + self.assertEqual(ltc.VLLM_WITHOUT_MACROS, {"kolibri", "kolibri-nvfp4"}) + self.assertIn("vllm0.29.0", (ltc.REPO / "install-kolibri.sh").read_text()) + + def test_the_generation_tag_of_transformers_renders_its_body(self): + tpl = "{% for m in messages %}{% generation %}{{ m.content }}{% endgeneration %}{% endfor %}" + self.assertEqual(self.env.from_string(tpl).render(messages=[{"content": "ok"}]), "ok") + + +class ItsOwnFaults(unittest.TestCase): + # its conversion of the messages stood outside the canary, and a fault in it read as the template's + # refusal (code review, 2026-10-24) + def test_a_conversion_that_loses_the_messages_stops_it_at_the_canary(self): + real = ltc.vllm_hands + ltc.vllm_hands = lambda msgs, openai: [] + try: + with self.assertRaisesRegex(SystemExit, "canary"): + ltc.main() + finally: + ltc.vllm_hands = real + + def test_a_fault_of_the_conversion_is_no_refusal(self): + env = ltc.environment() + with self.assertRaises(KeyError): + ltc.render(env, "{{ messages }}", ["user"], None, False, lambda msgs: {}["missing"]) + + def test_a_tool_call_sent_as_parts_has_null_content(self): + m = ltc.messages(["user", "assistant_tool_call", "tool"], parts=True) + self.assertIsNone(m[1]["content"]) + self.assertEqual(ltc.vllm_hands(m, True)[1]["content"], []) + self.assertEqual(ltc.sglang_hands(m, True)[1]["content"], "") class TheShapesItRenders(unittest.TestCase):