#!/usr/bin/env python3
# coding: utf-8
# Copyright (c) 2026 Huawei Technologies Co., Ltd.
# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
# CANN Open Software License Agreement Version 2.0 (the "License").
# Please refer to the License for details. You may not use this file except in compliance with the License.
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
# See LICENSE in the root of the software repository for the full text of the License.
# -----------------------------------------------------------------------------------------------------------
""" """

from __future__ import annotations

from collections import ChainMap
from collections.abc import Callable, Mapping
import ctypes
import dataclasses
from enum import Enum
import functools
import hashlib
import inspect
import json
import logging
import os
from pathlib import Path
import re
import shutil
import subprocess
import uuid

import torch

from pypto.pypto_impl import ir
from pypto.pypto_impl.codegen import CCECodegen
from pypto.pypto_impl.ir import ConstInt, PtrType, ScalarType, TensorType, TupleType, Var
from pypto_pro import DataType
from pypto_pro.runtime.compile_config import get_jit_compile_config

KERNEL_HEADER_SINGLE = """\
// Generated by PyPTO Pro JIT.
/* Dump CCE:
   bisheng -xcce -DREGISTER_BASE -E -I$ASCEND_TOOLKIT_HOME/include \
-I$ASCEND_HOME_PATH --cce-aicore-arch=dav-c310 kernel.cpp > kernel.cce.i
*/

#include <cstdint>
#include <pto/pto-inst.hpp>

using namespace pto;
"""


# pl DataType -> the torch.dtype a tensor argument for that parameter must have (used to
# validate tensor args against the kernel signature).
_PL_DTYPE_TO_TORCH: dict[str, "torch.dtype"] = {}


def _register_pl_dtype(pl_dtype: DataType, torch_name: str) -> None:
    """Map a pl dtype to the torch dtype named ``torch_name``, if this torch build has it."""
    torch_dtype = getattr(torch, torch_name, None)
    if torch_dtype is not None:
        _PL_DTYPE_TO_TORCH[str(pl_dtype)] = torch_dtype


for _pl_dtype, _torch_name in (
    (DataType.FP16, "float16"),
    (DataType.BF16, "bfloat16"),
    (DataType.FP32, "float32"),
    (DataType.INT8, "int8"),
    (DataType.INT16, "int16"),
    (DataType.INT32, "int32"),
    (DataType.INT64, "int64"),
    (DataType.UINT8, "uint8"),
    (DataType.UINT64, "uint64"),
    (DataType.BOOL, "bool"),
    (DataType.HF8, "uint8"),
):
    _register_pl_dtype(_pl_dtype, _torch_name)


_PL_DTYPE_TO_CTYPE: dict[str, type] = {
    str(DataType.FP32): ctypes.c_float,
    str(DataType.INT8): ctypes.c_int8,
    str(DataType.INT16): ctypes.c_int16,
    str(DataType.INT32): ctypes.c_int32,
    str(DataType.INT64): ctypes.c_int64,
    str(DataType.UINT8): ctypes.c_uint8,
    str(DataType.UINT16): ctypes.c_uint16,
    str(DataType.UINT32): ctypes.c_uint32,
    str(DataType.UINT64): ctypes.c_uint64,
    str(DataType.BOOL): ctypes.c_bool,
    str(DataType.INDEX): ctypes.c_int64,
}


class ParamKind(Enum):
    TENSOR = "tensor"
    PTR = "ptr"
    SCALAR = "scalar"
    TILING = "tiling"


@dataclasses.dataclass
class ParamSpec:
    """Description of a single kernel parameter extracted from the IR."""

    name: str
    kind: ParamKind
    dtype: DataType | None  # element dtype; None for tiling struct params
    # Tensor dims: positive int = static, str = named dynamic var, -1 = unnamed dynamic; None for ptr/scalar.
    shape: list[int | str] | None


@dataclasses.dataclass
class CompiledKernel:
    """Result of compile(): the .so path together with IR-derived parameter metadata."""

    lib_path: str
    param_specs: list[ParamSpec]
    # True when the generated kernel uses only vector (AIV) cores (no cube code),
    # so block_dim should be clamped against the vector core count.
    is_aiv_only: bool = False
    # Identity and artifacts of the generated kernel, forwarded to the exception-dump
    # bookkeeping on every launch.
    kernel_name: str = ""
    build_dir: str = ""
    has_cube: bool = False
    has_vector: bool = True
    # Lazily bound launch closure (see _build_launch_entry). It depends only on the
    # fields above, so it is built once instead of on every launch.
    entry: "Callable | None" = dataclasses.field(default=None, compare=False, repr=False)


@dataclasses.dataclass
class CompilePaths:
    """Filesystem paths used by one runtime compile invocation."""

    build_dir: str
    raw_cpp_path: str
    final_kernel: str


@dataclasses.dataclass
class GeneratedKernel:
    """Generated source metadata needed for the final shared-library compile."""

    content: str
    has_cross_sync: bool
    needs_print_debug: bool
    has_cube: bool
    has_vector: bool


@dataclasses.dataclass
class CodegenResult:
    """Key-independent output of the codegen phase: the kernel source (kernel.cpp +
    headers, already on disk) plus the metadata needed to build a launcher.

    This is pipeline-agnostic and contains nothing tilingkey-specific, so a
    single result is reused across every concrete tilingkey within a run and is the only
    thing future binary packaging needs — it does not require the JIT call_kernel.cpp /
    call_kernel_<digest>.so build that follows.
    """

    build_dir: str
    content: str
    kernel_name: str
    kernel_params: list
    caller_cross_core_sync: bool  # launcher needs cross-core sync wiring (ffts)
    bisheng_cross_sync: bool  # bisheng compile flag
    needs_print_debug: bool
    param_specs: list = dataclasses.field(default_factory=list)
    # kernel.cpp holds a device function `<kernel_name>_impl`; the `__global__`
    # entry that forwards to it must be generated by the launcher / binary op cpp.
    needs_global_entry: bool = False
    # Full impl param list (incl. trailing ffts_addr) used to build the __global__ entry.
    entry_params: list = dataclasses.field(default_factory=list)
    tiling_headers: dict[str, str] = dataclasses.field(default_factory=dict)
    has_cube: bool = False
    has_vector: bool = False


# Best-effort debug-print detection only. Launcher ABI metadata is derived from IR,
# not parsed from generated C++ text.
CPP_LITERAL_PATTERN = re.compile(
    r'"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'',
)
TPRINT_CALL_PATTERN = re.compile(r"\bTPRINT\s*\(")
CCE_PRINTF_CALL_PATTERN = re.compile(r"\bcce::printf\s*\(")


def _sanitize_artifact_component(value: str) -> str:
    cleaned = re.sub(r"[^0-9A-Za-z_.-]+", "_", value).strip("._")
    return cleaned or "kernel"


def _artifact_prefix_from_frame(frame) -> str | None:
    """Infer a readable artifact prefix from a Python frame."""
    filename = frame.f_code.co_filename
    return _artifact_prefix_from_filename(filename)


def _artifact_prefix_from_filename(filename: str | None) -> str | None:
    """Infer a readable artifact prefix from a Python source filename."""
    if not filename:
        return None
    stem = Path(filename).stem
    if not stem.startswith("test_"):
        return None
    suffix = stem[len("test_"):]
    return _sanitize_artifact_component(suffix or stem)


def _infer_test_artifact_prefix() -> str | None:
    frame = inspect.currentframe()
    try:
        frame = frame.f_back
        while frame is not None:
            prefix = _artifact_prefix_from_frame(frame)
            if prefix is not None:
                return prefix
            frame = frame.f_back
    finally:
        del frame
    return None


def _make_artifact_build_dir(prog, arch: str, test_prefix: str | None = None, tilingkey_suffix: str = "") -> str:
    """The per-kernel build dir. All tilingkeys of one kernel share this dir; each concrete
    key gets a ``tk_<packed>`` subdir under it (see :func:`_make_tilingkey_dir`)."""
    prog_name = getattr(prog, "name", None) or getattr(prog, "_name", None)
    prog_name = prog_name or getattr(prog, "func_name", None) or "kernel"
    safe_name = _sanitize_artifact_component(str(prog_name))
    test_prefix = test_prefix if test_prefix is not None else _infer_test_artifact_prefix()
    readable_prefix = f"{test_prefix}__{safe_name}" if test_prefix and test_prefix != safe_name else safe_name
    return os.path.join(".", "build", f"{readable_prefix}__{arch}{tilingkey_suffix}")


def _make_tilingkey_dir(build_dir: str, tilingkey_packed: int | None) -> str:
    """The per-tilingkey subdir under the kernel build dir. Holds this key's kernel.cpp,
    tiling headers, call_kernel.cpp and the compiled call_kernel_<digest>.so (bisheng
    writes to a per-call temp file, which is then renamed to embed a content hash). Keys
    without a tiling_key use ``tk_none`` so the layout is uniform."""
    suffix = "none" if tilingkey_packed is None else format(tilingkey_packed, "x")
    return os.path.join(build_dir, f"tk_{suffix}")


def _dtype_record(dtype: DataType) -> dict:
    return {"name": str(dtype)}


def _validate_datatype_schema(datatype) -> dict[str, str] | None:
    """Validate the decorator's datatype mapping without function-specific checks."""
    if datatype is None:
        return None
    if not isinstance(datatype, dict) or not datatype:
        raise ValueError("datatype must be a non-empty dict mapping param name to dtype variable name")

    for param_name, var_name in datatype.items():
        if not isinstance(param_name, str) or not param_name:
            raise ValueError(f"datatype param names must be non-empty strings, got {param_name!r}")
        if not isinstance(var_name, str) or not var_name.isidentifier():
            raise ValueError(
                f"datatype variable for param '{param_name}' must be a valid Python identifier, got {var_name!r}"
            )
    return datatype


def _validate_datatype_schema_context(spec: dict[str, str] | None, func, tilingkey_schema) -> None:
    if spec is None:
        return
    param_names = set(inspect.signature(func).parameters)
    missing = sorted(set(spec) - param_names)
    if missing:
        raise ValueError(f"datatype params {missing} do not match kernel function '{func.__name__}' parameters")
    var_names = set(spec.values())
    param_conflicts = sorted(var_names & param_names)
    if param_conflicts:
        raise ValueError(f"datatype variable names conflict with kernel params: {param_conflicts}")
    if tilingkey_schema is not None:
        tk_conflicts = sorted(var_names & set(tilingkey_schema.field_names()))
        if tk_conflicts:
            raise ValueError(f"datatype variable names conflict with tiling_key fields: {tk_conflicts}")


def _validate_datatype_key(spec: dict[str, str] | None, dtype_key: dict | None) -> dict[str, DataType] | None:
    """Validate one launch-time dtype dict and return var_name -> DataType constants."""
    if spec is None:
        if dtype_key is not None:
            raise ValueError("datatype dict was provided but this kernel has no datatype schema")
        return None
    if not isinstance(dtype_key, dict):
        raise ValueError("datatype kernel launch requires a dtype dict")

    expected = set(spec)
    actual = set(dtype_key)
    if actual != expected:
        raise ValueError(f"datatype keys {sorted(actual)} do not match schema params {sorted(expected)}")

    var_to_dtype: dict[str, DataType] = {}
    for param_name, var_name in spec.items():
        dtype = dtype_key[param_name]
        if not isinstance(dtype, DataType):
            raise TypeError(f"datatype['{param_name}'] must be a pypto_pro.DataType, got {type(dtype).__name__}")
        existing = var_to_dtype.get(var_name)
        if existing is not None and existing != dtype:
            raise ValueError(f"datatype params mapped to variable '{var_name}' disagree: {existing} vs {dtype}")
        var_to_dtype[var_name] = dtype
    return var_to_dtype


def _datatype_metadata(
    spec: dict[str, str] | None,
    dtype_key: dict[str, DataType] | None,
    dtype_consts: dict[str, DataType] | None,
) -> dict | None:
    if spec is None:
        return None
    dtype_key = dtype_key or {}
    dtype_consts = dtype_consts or {}
    return {
        "params": {
            param_name: {
                "variable": var_name,
                "dtype": _dtype_record(dtype_key[param_name]),
            }
            for param_name, var_name in sorted(spec.items())
        },
        "constants": {var_name: _dtype_record(dtype) for var_name, dtype in sorted(dtype_consts.items())},
    }


def _datatype_hash(metadata: dict | None) -> str | None:
    if metadata is None:
        return None
    payload = json.dumps(metadata, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]


def write_datatype_metadata(output_dir: str, metadata: dict | None) -> None:
    """Write datatype.json into an artifact directory when dtype specialization is active."""
    if metadata is None:
        return
    Path(output_dir).mkdir(parents=True, exist_ok=True)
    Path(output_dir, "datatype.json").write_text(
        json.dumps(metadata, indent=2, sort_keys=True) + "\n",
        encoding="utf-8",
    )


def _pack_factor(dtype: DataType | None) -> int:
    """How many elements of ``dtype`` torch reports as one storage unit along the packed axis.

    A sub-byte dtype has no torch dtype of its own, so callers pass the packed storage buffer
    (uint8, two fp4 per byte) and torch reports its shape in those storage units. pypto counts
    elements everywhere, so the packed axis -- the innermost one, the only axis a sub-byte
    element can be packed along -- has to be scaled back up before a tensor argument is
    compared against its ParamSpec or fed to the dynamic ABI tail. Whole-byte dtypes are
    already 1:1, and note that ``8 // 32`` is 0, not 1, so a wide dtype needs the clamp too.

    This depends only on the dtype, so the launch plan resolves it once per compiled kernel
    and the launch path just multiplies (see :class:`_LaunchPlan`).
    """
    if dtype is None:
        return 1
    return max(8 // dtype.get_bit(), 1)


def _pl_dtype_to_torch(dtype: DataType):
    """Return the torch.dtype an argument for this pl DataType must have, or None if unknown."""
    return _PL_DTYPE_TO_TORCH.get(str(dtype))


def _get_kernel_ir_function(prog):
    """Return the Opaque IR function that serves as the kernel entry."""
    from pypto.pypto_impl.ir import FunctionType

    for f in prog.functions.values():
        if f.func_type == FunctionType.Opaque:
            return f
    raise RuntimeError(
        f"No Opaque kernel entry function found in program '{prog.name}' "
        f"(functions: {list(prog.functions)})"
    )


def _extract_param_specs(prog) -> list[ParamSpec]:
    """Extract parameter descriptions from the kernel function in an ir.Program."""
    func = _get_kernel_ir_function(prog)
    specs: list[ParamSpec] = []
    for var in func.params:
        t = var.type
        if isinstance(t, TensorType):
            shape = [s.value if isinstance(s, ConstInt) else (s.name if isinstance(s, Var) else -1) for s in t.shape]
            specs.append(ParamSpec(var.name, ParamKind.TENSOR, t.dtype, shape))
        elif isinstance(t, PtrType):
            specs.append(ParamSpec(var.name, ParamKind.PTR, t.dtype, None))
        elif isinstance(t, TupleType):
            # Tiling struct param: passed as a single uint8 device buffer pointer.
            specs.append(ParamSpec(var.name, ParamKind.TILING, None, None))
        elif isinstance(t, ScalarType):
            specs.append(ParamSpec(var.name, ParamKind.SCALAR, t.dtype, None))
    return specs


def _cce_cpp_type_from_dtype(dtype: DataType | None, *, param_name: str) -> str:
    """Return the CCE C++ scalar/element type string for a DataType."""
    if dtype is None:
        raise TypeError(f"Parameter '{param_name}' has no dtype")
    cpp_type = dtype.to_c_type_string()
    if not cpp_type or cpp_type == "unknown":
        raise TypeError(f"Unsupported CCE ABI dtype {dtype} for parameter '{param_name}'")
    return cpp_type


def _entry_params_from_param_specs(param_specs: list[ParamSpec]) -> list[tuple[str, str, bool]]:
    """Build launcher entry params from IR metadata instead of parsing generated C++."""
    params: list[tuple[str, str, bool]] = []
    for spec in param_specs:
        if spec.kind in (ParamKind.TENSOR, ParamKind.PTR):
            params.append((_cce_cpp_type_from_dtype(spec.dtype, param_name=spec.name), spec.name, True))
        elif spec.kind == ParamKind.TILING:
            params.append(("uint8_t", spec.name, True))
        elif spec.kind == ParamKind.SCALAR:
            params.append((_cce_cpp_type_from_dtype(spec.dtype, param_name=spec.name), spec.name, False))

    params.extend(("int32_t", dim_name, False) for dim_name in _collect_dyn_vars(param_specs))
    return params


def _iter_tensor_dynamic_dims(spec: ParamSpec):
    """Yield dynamic dimension symbols from a tensor param spec."""
    if spec.kind != ParamKind.TENSOR or spec.shape is None:
        return
    for dim in spec.shape:
        if isinstance(dim, str):
            yield dim


def _collect_dyn_vars(param_specs: list[ParamSpec]) -> list[str]:
    """Return dynamic shape variable names in first-occurrence order (mirrors ptoas codegen)."""
    seen: set[str] = set()
    result: list[str] = []
    for spec in param_specs:
        for dim in _iter_tensor_dynamic_dims(spec):
            if dim not in seen:
                result.append(dim)
                seen.add(dim)
    return result


def _validate_scalar_arg(i: int, arg, spec: ParamSpec) -> None:
    """Validate one scalar arg against its ParamSpec."""
    if not isinstance(arg, (int, float, bool)):
        raise TypeError(f"arg[{i}] '{spec.name}': expected Python scalar (int/float/bool), got {type(arg).__name__}")
    # bool is a subclass of int: valid for BOOL and integer dtypes only.
    if isinstance(arg, bool):
        if not (spec.dtype == DataType.BOOL or spec.dtype.is_signed_int() or spec.dtype.is_unsigned_int()):
            raise TypeError(f"arg[{i}] '{spec.name}': bool value passed for non-boolean/non-integer dtype {spec.dtype}")
    elif isinstance(arg, float) and not spec.dtype.is_float():
        raise TypeError(f"arg[{i}] '{spec.name}': float value passed for non-float dtype {spec.dtype}")
    elif isinstance(arg, int) and not spec.dtype.is_signed_int() and not spec.dtype.is_unsigned_int():
        raise TypeError(f"arg[{i}] '{spec.name}': int value passed for non-integer dtype {spec.dtype}")


def _pack_tiling_arg(args: tuple) -> tuple:
    """If the last arg is a tiling class instance, replace it with a device buffer tensor.

    The tiling instance is serialized to its C-struct byte layout, wrapped in a uint8
    CPU tensor, and moved to the same device as the other tensor args. The kernel
    receives a single ``uint8_t*`` pointer and copies the struct in at its entry.

    The returned tuple holds the device tensor as its last element, which keeps it alive
    through the launch (the caller's ``args`` stays referenced until ``call_kernel``).

    Args:
        args: Runtime arguments tuple passed to launch.

    Returns:
        args with the tiling instance replaced by the device tensor (unchanged if no
        tiling instance is present).
    """
    from pypto_pro.language.typing._tiling import is_tiling_class, tiling_instance_to_bytes

    if not args:
        return args
    last_arg = args[-1]
    if not is_tiling_class(type(last_arg)):
        return args

    buf = tiling_instance_to_bytes(last_arg)
    # Pick the device from an existing tensor arg (inputs/outputs are already on device).
    device = None
    for a in args[:-1]:
        dev = getattr(a, "device", None)
        if dev is not None:
            device = dev
            break
    cpu_t = torch.frombuffer(bytearray(buf), dtype=torch.uint8)
    tiling_t = cpu_t.to(device) if device is not None else cpu_t
    return args[:-1] + (tiling_t,)


class _LaunchPlan:
    """Everything about a launch that depends only on the kernel's ParamSpecs.

    Which parameter is a tensor, what torch dtype it must carry, which dimensions are
    compile-time constants, which are dynamic ABI variables, and the order those variables
    are appended in: none of that can change once the kernel is compiled, so it is resolved
    here exactly once and the hot path just walks flat tuples.

    Attributes:
        n_params: Expected argument count.
        has_tiling: Whether any parameter is a tiling struct (skips _pack_tiling_arg).
        slots: Per-parameter descriptors in ABI order. Tensor slots are
            ``(True, index, name, torch_dtype | None, rank, const_dims, dyn_dims, pack)``
            where ``rank`` is -1 for parameters whose shape is not checked (PTR, or no
            declared shape), ``dyn_dims`` lists the dimensions this parameter contributes
            to the dynamic ABI tail, and ``pack`` is the sub-byte packing factor from
            :func:`_pack_factor` (1 for every whole-byte dtype). Scalar slots are
            ``(False, index, spec, ctype)``.
        dyn_checks: ``(name, ((param_index, dim_index, pack_mult), ...))`` for dynamic
            variables that appear more than once and therefore must agree across
            arguments. ``pack_mult`` is the slot's ``pack`` on the packed axis and 1
            everywhere else, so the comparison is made in elements.
        dyn_count: Total length of the dynamic ABI tail.

    Walking the slots in order and emitting each slot's ``dyn_dims`` reproduces the
    first-occurrence ordering the ABI expects, which lets the launch path read each
    tensor's ``.shape`` once instead of rebuilding the torch.Size per dynamic dimension.
    """

    __slots__ = ("n_params", "has_tiling", "slots", "dyn_checks", "dyn_count")

    def __init__(self, param_specs: list[ParamSpec]) -> None:
        self.n_params = len(param_specs)
        self.has_tiling = any(spec.kind == ParamKind.TILING for spec in param_specs)
        slots: list[tuple] = []
        occurrences: dict[str, list[tuple[int, int, int]]] = {}
        sources: dict[str, tuple[int, int]] = {}
        for index, spec in enumerate(param_specs):
            if spec.kind not in (ParamKind.TENSOR, ParamKind.PTR, ParamKind.TILING):
                ctype = _PL_DTYPE_TO_CTYPE.get(str(spec.dtype))
                if ctype is None:
                    # A property of the dtype, not of any argument: reject it once here
                    # rather than on every launch.
                    raise TypeError(
                        f"No ctypes mapping for scalar dtype {spec.dtype} "
                        f"(param '{spec.name}'). FP16/BF16 scalars are not supported."
                    )
                slots.append((False, index, spec, ctype))
                continue
            # PTR params and shapeless specs stay unchecked.
            checked = spec.kind != ParamKind.PTR and spec.shape is not None
            rank = -1
            consts: tuple = ()
            # A sub-byte dtype arrives packed into uint8 storage; spec.shape counts
            # elements, so the innermost axis is scaled by `pack` before any comparison.
            pack = _pack_factor(spec.dtype) if checked else 1
            if checked:
                rank = len(spec.shape)
                consts = tuple(
                    (d, v) for d, v in enumerate(spec.shape) if isinstance(v, int) and v != -1
                )
                for dim, value in enumerate(spec.shape):
                    if isinstance(value, str):
                        occurrences.setdefault(value, []).append(
                            (index, dim, pack if dim == rank - 1 else 1)
                        )
            # Only TENSOR params feed the dynamic ABI tail.
            own_dyn: list[int] = []
            if spec.kind == ParamKind.TENSOR and spec.shape is not None:
                for dim, value in enumerate(spec.shape):
                    if isinstance(value, str) and value not in sources:
                        sources[value] = (index, dim)
                        own_dyn.append(dim)
            dtype = _pl_dtype_to_torch(spec.dtype) if checked else None
            slots.append((True, index, spec.name, dtype, rank, consts, tuple(own_dyn), pack))
        self.slots = tuple(slots)
        # A name seen once can never disagree with itself; only repeats need checking.
        self.dyn_checks = tuple(
            (name, tuple(where)) for name, where in occurrences.items() if len(where) > 1
        )
        self.dyn_count = len(sources)
        # The generated call_kernel signature declares its dynamic dimensions in the order
        # _collect_dyn_vars produces (via _entry_params_from_param_specs); `sources` above
        # rederives that order to build the matching argument tail. Two independent
        # derivations of one ABI ordering do not fail loudly when they drift -- the
        # arguments simply land in the wrong slots and the kernel reads the wrong extents
        # off device memory. Tie them together here: once per compiled kernel, never on the
        # launch path.
        codegen_order = tuple(_collect_dyn_vars(param_specs))
        if tuple(sources) != codegen_order:
            raise RuntimeError(
                "dynamic ABI tail disagrees with the generated kernel signature: "
                f"launch order {tuple(sources)}, codegen order {codegen_order}"
            )


def _build_launch_entry(compiled: "CompiledKernel"):
    """Bind one compiled kernel to a closure that launches it with no per-call setup.

    The shared library, its ``call_kernel`` entry point and the static launch plan are
    resolved once here; the returned closure only touches the arguments themselves.

    ``call_kernel.argtypes`` is declared from the plan so the hot path can hand ctypes
    plain Python ints and let it convert them at the call boundary in C, instead of
    allocating one ctypes object per argument on every launch. The types mirror the
    generated ``extern "C"`` signature exactly (see :func:`_generate_caller_cpp` and
    :func:`_entry_params_from_param_specs`): ``uint32_t blockDim``, ``void* stream``,
    one ``uint8_t*`` per tensor/ptr/tiling parameter, the scalar's own C type, then one
    ``int32_t`` per dynamic dimension. Each compiled kernel owns its CDLL handle, so the
    declaration cannot leak between kernels.
    """
    plan = _LaunchPlan(compiled.param_specs)
    lib = ctypes.CDLL(compiled.lib_path)
    call_kernel = lib.call_kernel
    n_params = plan.n_params
    has_tiling = plan.has_tiling
    slots = plan.slots
    dyn_checks = plan.dyn_checks
    # Scalars carry their own ctype; everything else crosses as an opaque pointer. The
    # dynamic tail is int32_t on the C side and was being passed as c_int64, which worked
    # only because the callee reads the low half of the register -- declaring it correctly
    # here passes the same bits with the same wraparound and no longer relies on that.
    call_kernel.argtypes = (
        [ctypes.c_uint32, ctypes.c_void_p]
        + [ctypes.c_void_p if slot[0] else slot[3] for slot in slots]
        + [ctypes.c_int32] * plan.dyn_count
    )
    call_kernel.restype = None
    logger = logging.getLogger()
    # Exception-dump bookkeeping. The addresses and shapes it caches are per-launch, so
    # the call itself has to stay on the hot path -- but the import and the kernel's own
    # identity do not, and _load_lib used to redo both on every launch.
    from pypto_pro.runtime.exception_dump import set_dump_info as _set_dump_info

    param_specs = compiled.param_specs
    dump_name = compiled.kernel_name
    dump_dir = compiled.build_dir
    dump_has_cube = compiled.has_cube
    dump_has_vector = compiled.has_vector

    def entry(args: tuple, block_dim: int, stream):
        if has_tiling:
            args = _pack_tiling_arg(args)
        if len(args) != n_params:
            raise TypeError(f"Expected {n_params} args, got {len(args)}")

        # Plain Python values in ABI order; argtypes converts them at the call.
        abi_args = []
        append = abi_args.append
        dyn_values: list = []
        for slot in slots:
            index = slot[1]
            arg = args[index]
            if not slot[0]:
                _validate_scalar_arg(index, arg, slot[2])
                append(arg)
                continue
            _, _, name, expected_dtype, rank, consts, dyn_dims, pack = slot
            if arg is None:
                append(None)  # ctypes maps None to a null void*
                if dyn_dims:
                    dyn_values.extend([0] * len(dyn_dims))
                continue
            if not isinstance(arg, torch.Tensor):
                raise TypeError(f"arg[{index}] '{name}': expected torch.Tensor, got {type(arg).__name__}")
            if rank >= 0:
                # torch.dtype values are singletons, so identity is enough and cheaper.
                if expected_dtype is not None and arg.dtype is not expected_dtype:
                    raise TypeError(
                        f"arg[{index}] '{name}': dtype mismatch — expected {expected_dtype}, got {arg.dtype}"
                    )
                # One .shape per tensor: reused for the positivity check, the rank check,
                # the constant-dimension checks and this parameter's slice of the dynamic
                # ABI tail.
                shape = arg.shape
                if len(shape) != rank:
                    raise TypeError(
                        f"arg[{index}] '{name}': rank mismatch — expected {rank}D, got {len(shape)}D"
                    )
                # Sub-byte dtype: torch reported the packed uint8 storage, so scale the
                # innermost axis back to elements (see _pack_factor). Packing does not
                # change the rank, so the check above reads either shape the same way.
                if pack != 1 and rank:
                    shape = tuple(shape[:-1]) + (shape[-1] * pack,)
                # The compile path rejects a non-positive runtime dimension inside the
                # shape-policy bind (_validate_positive_int). A cache hit skips that bind
                # entirely, so without this a zero-sized tensor would raise on the launch
                # that compiled the kernel and be accepted by every launch after it. One
                # C-level pass over the torch.Size already in hand; `rank` guards the
                # 0-d case, where min() would see an empty sequence.
                if rank and min(shape) <= 0:
                    raise ValueError(
                        f"arg[{index}] '{name}': runtime dimensions must be positive, got {tuple(shape)}"
                    )
                for dim, expected in consts:
                    if shape[dim] != expected:
                        raise TypeError(
                            f"arg[{index}] '{name}': dim[{dim}] mismatch — "
                            f"expected {expected}, got {shape[dim]}"
                        )
                for dim in dyn_dims:
                    dyn_values.append(shape[dim])
            append(arg.data_ptr())

        for var_name, where in dyn_checks:
            first = -1
            for param_index, dim, pack_mult in where:
                other = args[param_index]
                if other is None:
                    continue
                # pack_mult is 1 unless this is a sub-byte parameter's packed axis.
                actual = other.shape[dim] * pack_mult
                if first < 0:
                    first = actual
                elif actual != first:
                    raise TypeError(
                        f"arg[{param_index}] '{slots[param_index][2]}': dynamic shape variable "
                        f"'{var_name}' mismatch — previously {first}, got {actual} at dim[{dim}]"
                    )
        abi_args.extend(dyn_values)

        if stream is None:
            stream = torch.npu.current_stream()
        # The capture probe only feeds these two log lines; skip it when neither can emit.
        if logger.isEnabledFor(logging.INFO):
            try:
                import torch_npu

                if torch_npu.npu.is_current_stream_capturing():
                    logging.info(
                        "Capture status [1], kernel launching in graph capture mode (block_dim=%d)", block_dim
                    )
                else:
                    logging.debug("Capture status [0], kernel launching in eager mode (block_dim=%d)", block_dim)
            except (ImportError, AttributeError):
                pass

        _set_dump_info(dump_name, args, param_specs, dump_dir,
                       has_cube=dump_has_cube, has_vector=dump_has_vector)
        call_kernel(block_dim, stream._as_parameter_, *abi_args)

    entry.lib = lib  # keep the library alive for as long as the closure is reachable
    return entry


def _get_mlir_code(result):
    """Normalize generate() result to MLIR string (support both str and dict)."""
    return result if isinstance(result, str) else "".join(result.values())


def _generate_caller_cpp(
    kernel_params: list[tuple[str, str, bool]],
    kernel_cpp_name: str,
    kernel_name: str,
    has_cross_core_sync: bool = False,
    enable_print_debug: bool = False,
    global_entry: str = "",
) -> str:
    """Generate extern "C" wrapper that calls the __global__ kernel.

    Args:
        param_specs: List of parameter specifications extracted from IR
        kernel_cpp_name: Name of the kernel .cpp file to include
        kernel_name: Name of the kernel function to call
        has_cross_core_sync: Whether the kernel uses cross-core sync ops
        enable_print_debug:
            Reserved compatibility switch from compile(); currently this wrapper
            does not need extra caller-side code changes for print debug.

    Returns:
        Generated caller.cpp content as string
    """
    cpp_params = []
    kernel_args = []

    for typ, name, is_ptr in kernel_params:
        if is_ptr:
            cpp_params.append(f"uint8_t* {name}")
            kernel_args.append(f"({typ} *){name}")
        else:
            cpp_params.append(f"{typ} {name}")
            kernel_args.append(name)
    sig = ", ".join(["uint32_t blockDim", "void* stream"] + cpp_params)
    call_args = ", ".join(kernel_args)

    if has_cross_core_sync:
        call_args = f"{call_args}, (int64_t*)ffts" if call_args else "(int64_t*)ffts"
        return (
            f'#include "runtime/rt_ffts.h"\n'
            f'#include "{kernel_cpp_name}"\n'
            f'{global_entry}'
            f'extern "C" void call_kernel({sig})\n'
            "{{\n"
            "    uint64_t ffts = 0;\n"
            "    uint32_t fftsLen = 0;\n"
            "    rtGetC2cCtrlAddr(&ffts, &fftsLen);\n"
            f"    {kernel_name}<<<blockDim, nullptr, stream>>>({call_args});\n"
            "}}\n"
        )

    return (
        f'#include "{kernel_cpp_name}"\n'
        f'{global_entry}'
        f'extern "C" void call_kernel({sig})\n'
        "{{\n"
        f"    {kernel_name}<<<blockDim, nullptr, stream>>>({call_args});\n"
        "}}\n"
    )


def _normalize_arch(arch: str | None) -> str:
    """Normalize and validate arch names to 'a2', 'a3', or 'a5'.

    Resolution order:
        1. Explicit arch parameter (if provided and not "auto")
        2. PYPTOPRO_JIT_ARCH environment variable
        3. Auto-detect from platform SOC version via RTS
        4. Default to "a3"
    """
    if arch and arch.strip().lower() != "auto":
        value = arch.strip().lower()
    else:
        value = os.environ.get("PYPTOPRO_JIT_ARCH", "").strip().lower()
        if not value:
            from pypto_pro.runtime.platform import get_platform_info

            info = get_platform_info()
            value = info.arch if info.arch else "a3"
    if value not in {"a2", "a3", "a5"}:
        raise ValueError(f"Unsupported arch: {arch!r}, expected one of 'a2', 'a3', 'a5'")
    return value


def _detect_print_debug_from_cpp(content: str) -> bool:
    """Best-effort detection for device-side debug print usage in generated C++."""
    scrubbed = CPP_LITERAL_PATTERN.sub(" ", content)
    return bool(TPRINT_CALL_PATTERN.search(scrubbed) or CCE_PRINTF_CALL_PATTERN.search(scrubbed))


def _build_bisheng_flags(
    toolkit_home: str,
    arch: str,
    has_cube: bool,
    has_vector: bool,
    has_cross_sync: bool,
    enable_print_debug: bool,
) -> list[str]:
    """Build bisheng flags for single-command shared-library compilation.

    Determines the npu_arch from the explicit Parser target availability.
    """
    arch = _normalize_arch(arch)

    if has_cross_sync and not (has_cube and has_vector):
        if has_cube:
            raise ValueError("Contains ffts cross sync but vector code is missing.")
        if has_vector:
            raise ValueError("Contains ffts cross sync but cube code is missing.")
    return get_jit_compile_config().build_bisheng_flags(
        toolkit_home=toolkit_home,
        arch=arch,
        has_cube=has_cube,
        has_vec=has_vector,
        enable_print_debug=enable_print_debug,
    )


def _build_llvm_args(arch: str) -> list[str]:
    """Build architecture-specific LLVM/CCE arguments for C++ compilation."""
    return get_jit_compile_config().build_llvm_args(_normalize_arch(arch))


def _static_signature_suffix(static_signature: tuple[tuple[int, int, int], ...]) -> str:
    if not static_signature:
        return ""
    digest = hashlib.sha256(repr(static_signature).encode("utf-8")).hexdigest()[:12]
    return f"__shape_{digest}"


def _prepare_codegen_inputs(
    kernel_def,
    arch: str,
    tilingkey_packed: int | None = None,
    out_dir: str | None = None,
    datatype_hash: str | None = None,
    datatype_metadata: dict | None = None,
    *,
    bound_signature=None,
    static_signature: tuple[tuple[int, int, int], ...] = (),
) -> tuple[object, str]:
    """Transform the KernelDef AST and create its per-tilingkey output directory.

    Tilingkey field values are baked into the IR as constants, so each concrete key produces
    its own ``kernel.cpp``. All keys of one kernel share the kernel build dir; this returns
    the KernelDef and the per-key subdir ``<build_dir>/tk_<packed>`` where that
    key's kernel.cpp, tiling headers, launcher and .so all live together.

    ``out_dir`` overrides the default ``<build_dir>/tk_<packed>`` location: callers that must
    keep concurrent codegen isolated (e.g. binary compile forks one process per dtype-combo, all
    sharing cwd) pass a caller-unique directory so distinct kernels never share a kernel.cpp.
    """
    artifact_prefix = _artifact_prefix_from_filename(
        getattr(kernel_def, "_source_file", None)
    )
    generated_source = None
    if kernel_def._pipeline is not None:
        from pypto_pro.runtime.pipeline import transform_pipeline
        from pypto_pro.runtime.pipeline._analyzer import probe_kernel_facts
        from pypto_pro.runtime.pipeline._dump import build_generated_file_source

        # Probe parse to learn which if-conditions are compile-time constants
        # (reuses the parser's own constant folding); drives dead-branch pruning.
        if_const_map, var_types = probe_kernel_facts(kernel_def, bound_signature)
        kernel_def._func_def = transform_pipeline(
            kernel_def._func_def,
            kernel_def._closure_vars,
            kernel_def._pipeline,
            if_const_map=if_const_map,
            var_types=var_types,
            tilingkey_consts=kernel_def._tilingkey_consts,
            datatype_consts=kernel_def._datatype_consts,
        )
        generated_source = build_generated_file_source(
            kernel_def._func_def,
            kernel_def._source_file,
            kernel_def._line_offset,
            kernel_def._col_offset,
            kernel_def._source_lines_raw,
            kernel_def._closure_vars,
        )
        kernel_def._pipeline = None

    if out_dir is None:
        build_dir = _make_artifact_build_dir(
            kernel_def, arch, test_prefix=artifact_prefix,
            tilingkey_suffix=_static_signature_suffix(static_signature))
        if datatype_hash is not None:
            build_dir = os.path.join(build_dir, f"dt_{datatype_hash}")
            write_datatype_metadata(build_dir, datatype_metadata)
        out_dir = _make_tilingkey_dir(build_dir, tilingkey_packed)
    Path(out_dir).mkdir(parents=True, exist_ok=True)
    # Dumped after out_dir exists so the transformed source lands next to the
    # kernel.cpp it produced, instead of in a cwd-relative ./build tree of its own.
    _dump_pipeline_generated_source(kernel_def, generated_source, out_dir)
    return kernel_def, out_dir


def _make_jit_paths(out_dir: str) -> CompilePaths:
    """JIT artifact paths within one tilingkey's output dir: kernel.cpp, call_kernel.cpp and
    the compiled library all live side by side in ``out_dir``. The compiled library is built
    under a process-unique temp name and renamed to call_kernel_<digest>.so
    (see :func:`_compile_shared_library`)."""
    return CompilePaths(
        build_dir=out_dir,
        raw_cpp_path=os.path.join(out_dir, "kernel.cpp"),
        final_kernel=os.path.join(out_dir, "call_kernel.cpp"),
    )


def _make_global_entry(
    kernel_name: str,
    entry_params: list[tuple[str, str, bool]],
) -> str:
    """Generate the ``__global__`` entry that forwards 1:1 to ``<kernel_name>_impl``.

    The entry mirrors the impl signature exactly (same types/names, incl. a trailing
    ffts_addr), so the forward is a plain pass-through.
    """
    decls = []
    args = []
    for typ, name, is_ptr in entry_params:
        decls.append(f"__gm__ {typ}* {name}" if is_ptr else f"{typ} {name}")
        args.append(name)
    sig = ", ".join(decls)
    call_args = ", ".join(args)

    return f"__global__ AICORE void {kernel_name}({sig})\n{{\n    {kernel_name}_impl({call_args});\n}}\n"


def _codegen_target_cce(
    prog,
    arch: str,
    build_dir: str,
    target: ir.SectionKind,
) -> CodegenResult:
    """CCE codegen for one target-specific Program.

    Key-independent: produces no launcher and does not write final artifacts.
    """
    cce_codegen = CCECodegen(target)
    cpp_code = cce_codegen.generate_single(prog, arch)
    if "ffts_cross_core_sync" in cpp_code and arch == "a5":
        extra_headers = "#include <pto/npu/a5/custom/TSyncCVID.hpp>"
        guard = {
            ir.SectionKind.Cube: "#if defined(__DAV_CUBE__)",
            ir.SectionKind.Vector: "#if defined(__DAV_VEC__)",
        }[target]
        cpp_code = cpp_code.replace(guard, guard + "\n" + extra_headers, 1)
    tiling_headers = dict(cce_codegen.get_tiling_headers())

    # CCE emits the body as `__aicore__ inline void <name>_impl(...)`; derive the launcher ABI
    # from IR metadata instead of parsing generated C++ text, so C++ formatting/decorators can
    # change without breaking JIT launch parameter discovery.
    kernel_func = _get_kernel_ir_function(prog)
    kernel_name = kernel_func.name
    param_specs = _extract_param_specs(prog)
    entry_params = _entry_params_from_param_specs(param_specs)
    has_ffts = "set_ffts_base_addr" in cpp_code
    has_cross_sync = has_ffts or "set_intra_block" in cpp_code
    if has_ffts:
        entry_params.append(("int64_t", "ffts_addr", True))
    kernel_params = entry_params[:-1] if has_ffts else entry_params

    return CodegenResult(
        build_dir=build_dir,
        content=cpp_code,
        kernel_name=kernel_name,
        kernel_params=kernel_params,
        caller_cross_core_sync=has_ffts,
        bisheng_cross_sync=has_cross_sync,
        needs_print_debug=_detect_print_debug_from_cpp(cpp_code),
        param_specs=param_specs,
        needs_global_entry=True,
        entry_params=entry_params,
        tiling_headers=tiling_headers,
        has_cube=target == ir.SectionKind.Cube,
        has_vector=target == ir.SectionKind.Vector,
    )


def _entry_param_declarations(entry_params: list[tuple[str, str, bool]]) -> str:
    return ", ".join(
        f"__gm__ {typ}* {name}" if is_ptr else f"{typ} {name}"
        for typ, name, is_ptr in entry_params
    )


def _target_call_args(result: CodegenResult) -> str:
    return ", ".join(name for _, name, _ in result.entry_params)


def _assemble_cv_source(
    cube: CodegenResult | None,
    vector: CodegenResult | None,
) -> CodegenResult:
    """Assemble independently generated target sources behind one impl entry."""
    results = [result for result in (cube, vector) if result is not None]
    if not results:
        raise RuntimeError("Cannot assemble Cube/Vector source without a target")

    reference = results[0]
    for result in results[1:]:
        if result.kernel_name != reference.kernel_name:
            raise RuntimeError("Cube/Vector kernel names do not match")
        if result.param_specs != reference.param_specs:
            raise RuntimeError("Cube/Vector kernel parameter specifications do not match")
        if result.kernel_params != reference.kernel_params:
            raise RuntimeError("Cube/Vector kernel ABIs do not match")
        if result.build_dir != reference.build_dir:
            raise RuntimeError("Cube/Vector build directories do not match")
        if result.tiling_headers != reference.tiling_headers:
            raise RuntimeError("Cube and Vector tiling headers must be identical")

    needs_ffts = any(result.caller_cross_core_sync for result in results)
    entry_params = list(reference.kernel_params)
    if needs_ffts:
        entry_params.append(("int64_t", "ffts_addr", True))

    wrapper_lines = [
        "",
        f"__aicore__ inline void {reference.kernel_name}_impl("
        f"{_entry_param_declarations(entry_params)})",
        "{",
    ]
    if cube is not None:
        wrapper_lines.extend(
            [
                "#if defined(__DAV_CUBE__)",
                f"    {reference.kernel_name}_impl_cube({_target_call_args(cube)});",
                "#endif",
            ]
        )
    if vector is not None:
        wrapper_lines.extend(
            [
                "#if defined(__DAV_VEC__)",
                f"    {reference.kernel_name}_impl_vector({_target_call_args(vector)});",
                "#endif",
            ]
        )
    wrapper_lines.extend(["}", ""])

    return CodegenResult(
        build_dir=reference.build_dir,
        content="\n".join([*(result.content for result in results), *wrapper_lines]),
        kernel_name=reference.kernel_name,
        kernel_params=list(reference.kernel_params),
        caller_cross_core_sync=needs_ffts,
        bisheng_cross_sync=any(result.bisheng_cross_sync for result in results),
        needs_print_debug=any(result.needs_print_debug for result in results),
        param_specs=list(reference.param_specs),
        needs_global_entry=True,
        entry_params=entry_params,
        tiling_headers=dict(reference.tiling_headers),
        has_cube=cube is not None,
        has_vector=vector is not None,
    )


def _parse_and_codegen_targets(
    kernel_def,
    arch: str,
    build_dir: str,
    bound_signature=None,
) -> tuple[CodegenResult | None, CodegenResult | None]:
    """Parse both targets, treating a sectionless kernel as shared by both."""
    programs = {}
    matched = {}
    for target in (ir.SectionKind.Cube, ir.SectionKind.Vector):
        programs[target], matched[target] = kernel_def.parse_target_program(
            target=target,
            bound_signature=bound_signature,
        )

    if not any(matched.values()):
        matched = {
            ir.SectionKind.Cube: True,
            ir.SectionKind.Vector: True,
        }

    results = {
        target: (
            _codegen_target_cce(programs.get(target), arch, build_dir, target=target)
            if matched.get(target)
            else None
        )
        for target in (ir.SectionKind.Cube, ir.SectionKind.Vector)
    }
    return results[ir.SectionKind.Cube], results[ir.SectionKind.Vector]


def _write_codegen_artifacts(result: CodegenResult) -> None:
    """Write the final assembled source and shared tiling headers once."""
    Path(result.build_dir).mkdir(parents=True, exist_ok=True)
    Path(result.build_dir, "kernel.cpp").write_text(result.content, encoding="utf-8")
    for header_name, header_content in result.tiling_headers.items():
        Path(result.build_dir, header_name).write_text(header_content, encoding="utf-8")


def _add_kernel_header(result: CodegenResult) -> CodegenResult:
    """Add the translation-unit header after all target sources are assembled."""
    return dataclasses.replace(
        result,
        content=f"{KERNEL_HEADER_SINGLE}\n{result.content.lstrip()}",
    )


def _dump_pipeline_generated_source(
    kernel_def,
    source: str | None,
    out_dir: str,
) -> None:
    """Preserve the transformed-pipeline debug artifact next to this key's kernel.cpp.

    ``out_dir`` is already unique per tilingkey/dtype (``tk_<packed>`` for JIT, a
    caller-supplied per-key dir for binary compile), so the dump lands beside the
    kernel.cpp it produced and needs no variant suffix to stay distinct.
    """
    if not source:
        return
    Path(out_dir, "pipeline_generated.py").write_text(source, encoding="utf-8")


def _runtime_include_flags(ascend_home_path: str) -> list[str]:
    """Build runtime include flags for bisheng."""
    return get_jit_compile_config().runtime_include_flags(ascend_home_path)


def _runtime_link_args(ascend_home_path: str) -> list[str]:
    """Build runtime link arguments for the configured JIT backend."""
    return get_jit_compile_config().runtime_link_args(ascend_home_path)


def _run_bisheng(
    bisheng_path: str,
    flags: list[str],
    arch: str,
    paths: CompilePaths,
    link_args: list[str],
    compile_timeout: int,
    output_path: str,
) -> bool:
    """Run bisheng to build the shared library at ``output_path``."""
    result = subprocess.run(
        [
            bisheng_path,
            *flags,
            *_build_llvm_args(arch),
            paths.final_kernel,
            *link_args,
            "-o",
            output_path,
        ],
        check=False,
        timeout=compile_timeout,
        capture_output=True,
    )
    if result.returncode == 0:
        return True
    logging.error("bisheng compilation failed with return code %s", result.returncode)
    logging.error("stdout: %s", result.stdout.decode())
    logging.error("stderr: %s", result.stderr.decode())
    return False


def _compile_shared_library(
    paths: CompilePaths,
    arch: str,
    generated: GeneratedKernel,
    clean_up: bool,
    compile_timeout: int,
) -> str | None:
    """Compile generated C++ and caller wrapper into a shared library.

    bisheng writes to a process-and-call-unique temp file in ``paths.build_dir`` rather
    than a shared fixed name: concurrent compiles of the same tilingkey target the same
    directory (e.g. distinct pytest-xdist workers compiling the same kernel/key), so a
    shared fixed output name would let one compile's rename race another's read. The temp
    file is renamed to call_kernel_<digest>.so, embedding a sha256 of the compiled bytes,
    and that hashed path is returned.
    """
    pto_lib_path = os.environ["ASCEND_TOOLKIT_HOME"]
    ascend_home_path = os.environ.get("ASCEND_HOME_PATH")
    if not ascend_home_path:
        raise RuntimeError("ASCEND_HOME_PATH is not set")
    link_args = _runtime_link_args(ascend_home_path)

    resolved_enable_print_debug = generated.needs_print_debug
    flags = _build_bisheng_flags(
        pto_lib_path,
        arch,
        generated.has_cube,
        generated.has_vector,
        generated.has_cross_sync,
        enable_print_debug=resolved_enable_print_debug,
    )
    flags.extend(_runtime_include_flags(ascend_home_path))
    bisheng_path = shutil.which("bisheng")
    if bisheng_path is None:
        logging.error("bisheng executable was not found")
        return None

    tmp_lib_path = os.path.join(paths.build_dir, f".call_kernel.{os.getpid()}.{uuid.uuid4().hex}.so")
    try:
        if not _run_bisheng(bisheng_path, flags, arch, paths, link_args, compile_timeout, tmp_lib_path):
            return None

        if clean_up:
            os.remove(paths.raw_cpp_path)
            os.remove(paths.final_kernel)

        lib_bytes = Path(tmp_lib_path).read_bytes()
        digest = hashlib.sha256(lib_bytes).hexdigest()[:12]
        unique_lib_path = os.path.join(paths.build_dir, f"call_kernel_{digest}.so")
        os.replace(tmp_lib_path, unique_lib_path)
        return unique_lib_path
    finally:
        if os.path.exists(tmp_lib_path):
            os.remove(tmp_lib_path)


def _codegen(
    prog,
    arch: str,
    clean_up: bool,
    tilingkey_packed: int | None = None,
    out_dir: str | None = None,
    datatype_hash: str | None = None,
    datatype_metadata: dict | None = None,
    *,
    bound_signature=None,
    static_signature: tuple[tuple[int, int, int], ...] = (),
) -> CodegenResult | None:
    """Codegen: parse + generate the kernel source for one concrete tilingkey.

    Tilingkey field values are folded into the IR as constants, so each key produces a
    distinct kernel.cpp written into that key's output dir ``<build_dir>/tk_<packed>``.

    ``out_dir`` overrides that default location (see :func:`_prepare_codegen_inputs`) — pass a
    caller-unique dir when concurrent codegen would otherwise share the default path.
    """
    from pypto_pro.runtime.kernel import KernelDef

    if not isinstance(prog, KernelDef):
        raise TypeError("CCE codegen requires a KernelDef with an explicit target section")

    source, out_dir = _prepare_codegen_inputs(
        prog, arch, tilingkey_packed, out_dir, datatype_hash, datatype_metadata,
        bound_signature=bound_signature, static_signature=static_signature)

    cube, vector = _parse_and_codegen_targets(
        source,
        arch,
        out_dir,
        bound_signature,
    )
    result = _assemble_cv_source(cube, vector)

    result = _add_kernel_header(result)
    _write_codegen_artifacts(result)
    return result


def _build_jit_so(
    cg: CodegenResult,
    arch: str,
    clean_up: bool,
    compile_timeout: int,
) -> str | None:
    """Write call_kernel.cpp next to the (already per-key) kernel.cpp in ``cg.build_dir`` and
    compile the .so. kernel.cpp, call_kernel.cpp and the resulting call_kernel_<digest>.so all
    share that one dir."""
    paths = _make_jit_paths(cg.build_dir)
    resolved_print_debug = cg.needs_print_debug

    # CCE: kernel.cpp holds only `<name>_impl`; define the __global__ entry that forwards to it.
    global_entry = ""
    if cg.needs_global_entry:
        global_entry = _make_global_entry(cg.kernel_name, cg.entry_params)

    caller_content = _generate_caller_cpp(
        kernel_params=cg.kernel_params,
        kernel_cpp_name="kernel.cpp",
        kernel_name=cg.kernel_name,
        has_cross_core_sync=cg.caller_cross_core_sync,
        enable_print_debug=resolved_print_debug,
        global_entry=global_entry,
    )
    Path(paths.final_kernel).write_text(caller_content, encoding="utf-8")

    generated = GeneratedKernel(
        content=cg.content,
        has_cross_sync=cg.bisheng_cross_sync,
        needs_print_debug=cg.needs_print_debug,
        has_cube=cg.has_cube,
        has_vector=cg.has_vector,
    )
    return _compile_shared_library(paths, arch, generated, clean_up, compile_timeout)


def _setup_arch_env(arch: str | None) -> str:
    """Normalize *arch* and export the env vars codegen/compile read. Returns the arch."""
    arch = _normalize_arch(arch)
    os.environ["PYPTOPRO_JIT_ARCH"] = arch
    os.environ["PYPTOPRO_NPU_ARCH"] = "dav-c220" if arch in ("a2", "a3") else "dav-c310"
    return arch


def _launch(compiled: "CompiledKernel", args: tuple, block_dim: int, stream):
    """Launch one compiled kernel, binding its entry closure on first use.

    Kept as a module-level function rather than inlined into the launcher so test
    infrastructure has a single seam to stub out (see the PARALLEL_COMPILE conftest,
    which replaces this to discover kernels without touching the device). ``args`` is
    passed as a tuple, not ``*args``, so the hot path does not rebuild it.
    """
    entry = compiled.entry
    if entry is None:
        entry = compiled.entry = _build_launch_entry(compiled)
    entry(args, block_dim, stream)


def _validate_block_dim(block_dim):
    """Validate that block_dim is a positive integer.

    Raises ValueError if block_dim is not an int or is <= 0.
    """
    if not isinstance(block_dim, int) or isinstance(block_dim, bool):
        raise ValueError(
            f"block_dim must be a positive integer, got {type(block_dim).__name__}: {block_dim}"
        )
    if block_dim <= 0:
        raise ValueError(
            f"block_dim must be a positive integer, got {block_dim}"
        )


def _validate_tilingkey_no_var_conflict(f, tilingkey_schema, closure_vars):
    tilingkey_names = set(tilingkey_schema.field_names())

    param_names = set(f.__code__.co_varnames[:f.__code__.co_argcount])
    conflicts = tilingkey_names & param_names
    if conflicts:
        raise ValueError(f"TilingKey field name(s) conflict with kernel parameter name(s): {conflicts}")

    non_builtin_names = set()
    for name, val in closure_vars.items():
        if name.startswith("__"):
            continue
        if callable(val) or isinstance(val, type):
            continue
        non_builtin_names.add(name)
    conflicts = tilingkey_names & non_builtin_names
    if conflicts:
        raise ValueError(f"TilingKey field name(s) conflict with module-level variable name(s): {conflicts}")


def jit(
    target=None,
    *,
    arch: str | None = None,
    auto_mutex: bool = True,
    name: str | None = None,
    pipeline=None,
    tiling_key=None,
    datatype=None,
    compile_timeout: int | None = None,
    **kwargs,
):
    """Mark a function for JIT compilation.

    When applied to a Tile-programming kernel (pl.Tensor parameters), the decorator
    performs lazy compilation on first call and supports bracket-launch syntax.

    Args:
        arch: Target architecture ("a2", "a3", "a5", or None for auto-detect).
        auto_mutex: If True, enable automatic mutex lock/unlock insertion.
        name: Custom kernel name for build artifact path isolation.
        pipeline: PipelineConfig for automatic preload pipeline transformation.
        compile_timeout: Compilation timeout in seconds (default 600).

    Usage (Tile-programming kernel with bracket-launch)::

        @pl.jit(arch="a5")
        def add_kernel(
            x: pl.Tensor[[64, 128], pl.DT_FP16],
            y: pl.Tensor[[64, 128], pl.DT_FP16],
            z: pl.Tensor[[64, 128], pl.DT_FP16]
        ) -> pl.Tensor[[64, 128], pl.DT_FP16]:
            ...

        add_kernel[stream, block_dim](x, y, z)
    """

    # Build the tilingkey schema eagerly so malformed schemas fail at decoration time.
    tilingkey_schema = None
    if tiling_key is not None:
        from pypto_pro.runtime.tilingkey import TilingKeySchema

        tilingkey_schema = TilingKeySchema(tiling_key)
    datatype_schema = _validate_datatype_schema(datatype)

    # Capture caller's scope for name resolution during lazy compilation.
    # Locals are snapshotted NOW (at decoration time) because a frame's locals
    # do not outlive the frame, but globals are kept as a LIVE reference so that
    # module-level helpers defined *below* the jit function are still resolvable
    # at compile time (compilation is lazy, on first call). Locals take priority
    # over globals, matching Python's own scoping.
    caller_frame = inspect.currentframe().f_back
    caller_closure_vars = ChainMap(dict(caller_frame.f_locals), caller_frame.f_globals)

    def decorator(f):
        if kwargs:
            raise TypeError(
                f"jit() got unexpected keyword argument(s): {', '.join(kwargs.keys())}."
            )
        if tilingkey_schema is not None:
            _validate_tilingkey_no_var_conflict(f, tilingkey_schema, caller_closure_vars)

        # Detect if this is a Tile-programming kernel (has pl.Tensor annotations)
        # by checking if annotations contain type hints with shape/dtype info.
        is_tile_kernel = _is_tile_kernel(f)

        if is_tile_kernel:
            _validate_datatype_schema_context(datatype_schema, f, tilingkey_schema)
            return _TileJitKernel(
                func=f,
                arch=arch,
                auto_mutex=auto_mutex,
                name=name,
                closure_vars=caller_closure_vars,
                pipeline=pipeline,
                tilingkey_schema=tilingkey_schema,
                datatype_schema=datatype_schema,
                compile_timeout=compile_timeout,
            )
        else:
            # Legacy path: non-Tile function, wrap as pass-through
            @functools.wraps(f)
            def wrapper(*args, **kwargs_):
                return f(*args, **kwargs_)

            return wrapper

    if callable(target):
        return decorator(target)
    else:
        return decorator


def _is_tile_kernel(func) -> bool:
    """Detect if a function is a Tile-programming kernel based on its annotations.

    A Tile kernel has pl.Tensor, pl.Ptr, or DT_* scalar annotations
    on its parameters. These are created by pl.Tensor[[shape], dtype],
    pl.Ptr[dtype], or dtype (e.g. pl.DT_INT64) syntax.
    """
    hints = getattr(func, "__annotations__", {})
    if not hints:
        return False

    # Import type classes for isinstance check
    tensor_cls = None
    ptr_cls = None
    try:
        from pypto_pro.language.typing.tensor import Tensor

        tensor_cls = Tensor
    except ImportError:
        pass

    try:
        from pypto_pro.language.typing.ptr import Ptr

        ptr_cls = Ptr
    except ImportError:
        pass

    for key, val in hints.items():
        if key == "return":
            continue
        # pl.Tensor[[64, 128], pl.DT_FP16] returns a Tensor instance at runtime
        if tensor_cls is not None and (isinstance(val, tensor_cls) or val is tensor_cls):
            return True
        # pl.Ptr[pl.DT_FP16] returns a Ptr instance at runtime
        if ptr_cls is not None and (isinstance(val, ptr_cls) or val is ptr_cls):
            return True
        # DT_* values are DataType enum members at runtime.  String annotations
        # are retained when ``from __future__ import annotations`` is active.
        if isinstance(val, DataType) or (isinstance(val, str) and val.split(".")[-1].startswith("DT_")):
            return True
    return False


# Specialization identity for a kernel launched without tilingkey/datatype keys.
# (tilingkey_packed, dtype_consts, dtype_metadata, dtype_hash)
_NO_SPEC = (None, None, None, None)


class _TileJitKernel:
    """A JIT-compiled Tile kernel that supports bracket-launch syntax.

    Supports:
        kernel[stream, block_dim](x, y, z)  — explicit stream and block_dim
        kernel[block_dim](x, y, z)          — default stream, explicit block_dim
        kernel(x, y, z)                     — default stream, block_dim=1
    """

    def __init__(
        self,
        func,
        arch: str | None,
        auto_mutex=True,
        name=None,
        closure_vars=None,
        pipeline=None,
        tilingkey_schema=None,
        datatype_schema=None,
        compile_timeout=None,
    ):
        self._func = func
        self._arch = arch

        self._auto_mutex = auto_mutex
        self._name = name
        self._closure_vars = closure_vars
        self._pipeline = pipeline
        self._tilingkey_schema = tilingkey_schema
        self._datatype_schema = datatype_schema
        self._compile_timeout = compile_timeout
        from pypto_pro.runtime.shape_policy import KernelSignatureSpec

        self._shape_signature_spec = KernelSignatureSpec.from_callable(func, closure_vars)
        self._compiled_by_signature: dict[tuple[tuple, str | None, int | None], "CompiledKernel"] = {}
        self._static_dim_slots_cache: tuple | None = None
        # Resolved bracket keys: sorted (tilingkey, datatype) items -> (tk snapshot,
        # dtype snapshot, specialization identity). Every call site in the tree writes
        # ``kernel[...](args)`` inline, so __getitem__ runs per launch and everything it
        # derives would otherwise be rederived per launch. Bounded by the number of
        # distinct specializations, which is the number of compiled variants; block_dim is
        # deliberately not part of the key, since nothing here depends on it and including
        # it would let a core-count sweep grow the memo without bound.
        self._bracket_memo: dict[tuple, tuple] = {}
        # Argument count for which _normalize_launch_args is a no-op: every parameter can
        # be filled positionally, so a full positional call already is the normalized
        # tuple. -1 when the signature rules that out (keyword-only, *args, **kwargs),
        # which never equals len(args) and therefore always takes the general path.
        signature = self._shape_signature_spec.python_signature
        positional = (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD)
        self._positional_arity = (
            len(signature.parameters)
            if signature is not None and all(p.kind in positional for p in signature.parameters.values())
            else -1
        )
        self.__name__ = func.__name__
        self.__doc__ = func.__doc__

    def __getitem__(self, key):
        """Support kernel[stream, block_dim], with optional tilingkey and datatype dicts.

        Returns a callable launcher that executes the compiled kernel.

        For tilingkey kernels the third bracket element is the concrete key dict::

            kernel[stream, block_dim, {"NeedAttnMask": 1}](...)
        """
        stream, block_dim, tk_key, dtype_key = self._parse_launch_key(key)
        # block_dim is fixed by the bracket key, so validate it here instead of
        # re-checking the same value on every launch. It is kept out of the memo key
        # because nothing the memo holds depends on it.
        _validate_block_dim(block_dim)
        try:
            memo_key = (
                None if tk_key is None else tuple(sorted(tk_key.items())),
                None if dtype_key is None else tuple(sorted(dtype_key.items())),
            )
            resolved = self._bracket_memo.get(memo_key)
        except (AttributeError, TypeError):
            # Not a dict at all, or a dict holding unhashable values. Fall through to the
            # validating branch, which rejects it with the schema's own message; a key that
            # cannot be looked up is also never stored.
            memo_key = None
            resolved = None
        if resolved is None:
            if self._tilingkey_schema is not None:
                self._tilingkey_schema.validate_concrete(tk_key)
            # Snapshot the specialization dicts. The identity below is resolved once from
            # them while codegen reads them again on a cache miss, so holding the caller's
            # objects would let a later mutation compile one variant under another's key --
            # poisoning the entry for every subsequent launch. Memoizing makes that sharper:
            # a poisoned entry would now outlive the bracket that created it. The memo key
            # is built from the dict's contents, so a mutated dict simply misses and
            # resolves afresh.
            tk_snapshot = None if tk_key is None else dict(tk_key)
            dtype_snapshot = None if dtype_key is None else dict(dtype_key)
            resolved = (tk_snapshot, dtype_snapshot, self._resolve_spec_identity(tk_snapshot, dtype_snapshot))
            if memo_key is not None:
                self._bracket_memo[memo_key] = resolved
        tk_snapshot, dtype_snapshot, spec = resolved
        arity = self._positional_arity

        def launcher(*args, **kwargs):
            # A complete positional call is already normalized; skip the bind entirely.
            if kwargs or len(args) != arity:
                args = self._normalize_launch_args(args, kwargs)
            compiled = self._ensure_compiled(
                args, concrete_key=tk_snapshot, dtype_key=dtype_snapshot, spec=spec
            )
            _launch(compiled, args, block_dim, stream)

        return launcher

    def __call__(self, *args, **kwargs_):
        """Direct call with default stream and block_dim=1."""
        if self._tilingkey_schema is not None or self._datatype_schema is not None:
            raise ValueError(
                f"Kernel '{self.__name__}' has compile-time specialization and cannot be called directly; "
                "use bracket-launch syntax"
            )
        if kwargs_ or len(args) != self._positional_arity:
            args = self._normalize_launch_args(args, kwargs_)
        compiled = self._ensure_compiled(args, spec=_NO_SPEC)
        _launch(compiled, args, 1, None)

    @property
    def arch(self):
        return self._arch

    @property
    def tilingkey_schema(self):
        return self._tilingkey_schema

    @property
    def datatype_schema(self):
        return self._datatype_schema

    def to_kernel_def(self, concrete_key: dict | None = None, datatype_consts: dict | None = None):
        """Create the KernelDef for one concrete tiling key and datatype specialization.

        ``concrete_key`` is the first positional argument for OPC compatibility.

        Shape binding is deliberately absent: the KernelDef carries the unbound function,
        and the bound signature reaches codegen through ``parse_target_program`` and
        ``probe_kernel_facts`` instead (see :func:`_codegen`).
        """
        # Create KernelDef directly with the closure captured by @pl.jit at
        # the user's decoration site.
        from pypto_pro.runtime.kernel import KernelDef, extract_func_source_info

        f = self._func
        (source_file, source_lines, source_lines_raw, line_offset, col_offset, func_def) = extract_func_source_info(f)

        return KernelDef(
            func=f,
            source_file=source_file,
            source_lines=source_lines,
            source_lines_raw=source_lines_raw,
            line_offset=line_offset,
            col_offset=col_offset,
            func_def=func_def,
            closure_vars=self._closure_vars or {},
            name=self._name,
            func_type=ir.FunctionType.Opaque,
            strict_ssa=False,
            meta_data=None,
            auto_mutex=self._auto_mutex,
            pipeline=self._pipeline,
            tilingkey_consts=concrete_key,
            datatype_consts=datatype_consts,
        )

    def _bind_runtime_args(self, args: tuple):
        """Validate tensor arguments and derive the static specialization signature."""
        bound_signature = self._shape_signature_spec.bind_runtime_args(args)
        python_args = self._shape_signature_spec.python_signature.bind(*args)
        for tensor_spec in self._shape_signature_spec.tensors:
            arg = python_args.arguments[tensor_spec.parameter_name]
            if arg is None:
                continue
            if not isinstance(arg, torch.Tensor):
                raise TypeError(
                    f"Tensor parameter '{tensor_spec.parameter_name}' expected torch.Tensor, got {type(arg).__name__}"
                )
            expected_dtype = _pl_dtype_to_torch(tensor_spec.dtype)
            if expected_dtype is not None and arg.dtype != expected_dtype:
                raise TypeError(
                    f"Tensor parameter '{tensor_spec.parameter_name}' dtype mismatch: "
                    f"expected {expected_dtype}, got {arg.dtype}"
                )
        return bound_signature

    def _bind_static_shapes(self, static_shapes):
        """Bind explicit binary-compilation shapes through the shared policy model."""
        return self._shape_signature_spec.bind_static_shapes(static_shapes)

    def _static_dim_slots(self):
        """Parameters carrying a StaticDim/StaticTail, i.e. the only ones whose runtime
        shape can contribute to ``static_signature``. Computed once; empty for a kernel
        declared entirely with ``pl.DYNAMIC`` and fixed dims, which lets _ensure_compiled
        skip binding the signature altogether."""
        slots = self._static_dim_slots_cache
        if slots is None:
            slots = self._static_dim_slots_cache = tuple(
                t.parameter_index for t in self._shape_signature_spec.tensors if t.requires_binding
            )
        return slots

    def _resolve_spec_identity(self, concrete_key, dtype_key):
        """Pack the specialization half of the cache key.

        Depends only on the bracket-launch key, never on the arguments, so callers that
        know it is fixed (``__getitem__``) resolve it once and pass it down.
        """
        tilingkey_packed = None
        if concrete_key is not None and self._tilingkey_schema is not None:
            tilingkey_packed = self._tilingkey_schema.pack(concrete_key)
        dtype_consts = _validate_datatype_key(self._datatype_schema, dtype_key)
        dtype_metadata = _datatype_metadata(self._datatype_schema, dtype_key, dtype_consts)
        return tilingkey_packed, dtype_consts, dtype_metadata, _datatype_hash(dtype_metadata)

    def _ensure_compiled(
        self, args: tuple, concrete_key: dict | None = None, dtype_key: dict | None = None,
        spec: tuple | None = None,
    ):
        """Return the compiled variant for one launch, compiling it on first use.

        This is the launch hot path: ``args`` is the runtime argument tuple in Python
        signature order. ``spec`` is the precomputed specialization identity from
        :meth:`_resolve_spec_identity`; ``__getitem__`` passes it because the bracket key
        pins it, so it is resolved here only when a caller did not.

        Ahead-of-time compilation without runtime arguments goes through
        :meth:`_compile_for_key` instead.
        """
        if spec is None:
            spec = self._resolve_spec_identity(concrete_key, dtype_key)
        tilingkey_packed, _, _, dtype_hash = spec

        # A cache hit needs only the key, so binding the full signature -- two
        # inspect.Signature.bind calls plus a BoundDimension per declared dimension -- is
        # deferred to the miss path, where codegen actually consumes it.
        if not self._static_dim_slots():
            # No parameter carries a StaticDim/StaticTail, so no dimension can ever be
            # marked static and the signature is provably empty for every launch.
            bound_signature = None
            static_signature = ()
        else:
            bound_signature = self._bind_runtime_args(args)
            static_signature = bound_signature.static_signature

        cached = self._compiled_by_signature.get((static_signature, dtype_hash, tilingkey_packed))
        if cached is not None:
            # No validation here: every caller launches immediately afterwards and the
            # launch path checks type, dtype, rank and every dimension. Doing it twice
            # per launch only duplicates the same TypeError.
            return cached

        if bound_signature is None:
            bound_signature = self._bind_runtime_args(args)
        return self._compile_variant(concrete_key, spec, bound_signature, static_signature)

    def _compile_for_key(self, concrete_key: dict | None = None, dtype_key: dict | None = None):
        """Compile one specialization ahead of any launch, without runtime arguments.

        Used by the PARALLEL_COMPILE conftest to warm the cache from a worker thread and by
        the tilingkey unit tests. Shapes come from the declared static policy
        (``_bind_static_shapes(None)``) since there are no tensors to read them from.
        """
        spec = self._resolve_spec_identity(concrete_key, dtype_key)
        tilingkey_packed, _, _, dtype_hash = spec
        bound_signature = self._bind_static_shapes(None)
        static_signature = bound_signature.static_signature
        cached = self._compiled_by_signature.get((static_signature, dtype_hash, tilingkey_packed))
        if cached is not None:
            return cached
        return self._compile_variant(concrete_key, spec, bound_signature, static_signature)

    def _compile_variant(self, concrete_key, spec, bound_signature, static_signature):
        """Codegen + build one variant and install it in the cache. Cache-miss path only.

        For tilingkey kernels, ``concrete_key`` selects the concrete field values baked into
        the IR; the packed 64-bit value keys the in-process cache and the per-key output subdir
        ``<build_dir>/tk_<packed>``. Codegen and compile are both per-key (the constants differ).
        """
        tilingkey_packed, dtype_consts, dtype_metadata, dtype_hash = spec
        arch = _setup_arch_env(self._arch)
        logging.info(
            "Generating kernel '%s' for static shape signature %s",
            self.__name__,
            static_signature or "<dynamic-only>",
        )
        cg = _codegen(
            self.to_kernel_def(concrete_key, datatype_consts=dtype_consts),
            arch,
            clean_up=False,
            tilingkey_packed=tilingkey_packed,
            datatype_hash=dtype_hash,
            datatype_metadata=dtype_metadata,
            bound_signature=bound_signature,
            static_signature=static_signature,
        )
        if cg is None:
            raise RuntimeError(f"Failed to generate code for kernel '{self.__name__}'")

        compile_timeout = self._compile_timeout
        if compile_timeout is None:
            from pypto import pypto_impl
            compile_timeout = pypto_impl.CurrentScope().GetAllConfig().get("host.compile_timeout", 600)
        lib_path = _build_jit_so(
            cg,
            arch,
            clean_up=False,
            compile_timeout=compile_timeout,
        )
        if lib_path is None:
            raise RuntimeError(f"Failed to compile kernel '{self.__name__}'")

        # An aiv-only kernel emits vector code but no cube code; its block_dim
        # is bounded by the vector core count rather than the total core count.
        is_aiv_only = cg.has_vector and not cg.has_cube
        compiled = CompiledKernel(
            lib_path=lib_path, param_specs=cg.param_specs, is_aiv_only=is_aiv_only,
            kernel_name=cg.kernel_name, build_dir=cg.build_dir,
            has_cube=cg.has_cube, has_vector=cg.has_vector,
        )
        self._compiled_by_signature[(static_signature, dtype_hash, tilingkey_packed)] = compiled
        return compiled

    def _launch_key_error(self) -> str:
        if self._tilingkey_schema is not None and self._datatype_schema is not None:
            return "Expected kernel[stream, block_dim, tilingkey, datatype]"
        if self._tilingkey_schema is not None:
            return "Expected kernel[stream, block_dim, tilingkey]"
        if self._datatype_schema is not None:
            return "Expected kernel[stream, block_dim, datatype]"
        return "Expected kernel[stream, block_dim] or kernel[block_dim]"

    def _normalize_launch_args(self, args: tuple, kwargs: Mapping[str, object]) -> tuple:
        """Return launch arguments in Python signature order, including defaults."""
        bound = self._shape_signature_spec.python_signature.bind(*args, **dict(kwargs))
        bound.apply_defaults()
        return tuple(bound.arguments[name] for name in self._shape_signature_spec.python_signature.parameters)

    def _parse_launch_key(self, key):
        """Split the bracket key into (stream, block_dim, tilingkey_dict|None, dtype_dict|None).

        Checks the *shape* of the bracket -- which dicts must be present for this kernel's
        schemas -- but not the tilingkey field values. ``validate_concrete`` walks the
        schema and is left to ``__getitem__``'s memo-miss branch, since a key that has
        already been resolved once was already validated then, and an invalid key never
        reaches the memo.
        """
        tk_key = None
        dtype_key = None
        if isinstance(key, tuple):
            if len(key) == 4:
                stream, block_dim, tk_key, dtype_key = key
            elif len(key) == 3:
                stream, block_dim, third_key = key
                if self._tilingkey_schema is not None:
                    tk_key = third_key
                elif self._datatype_schema is not None:
                    dtype_key = third_key
                else:
                    tk_key = third_key
            elif len(key) == 2:
                stream, block_dim = key
            else:
                raise ValueError(self._launch_key_error())
        else:
            stream = None
            block_dim = key

        if self._tilingkey_schema is not None:
            if tk_key is None:
                raise ValueError(self._launch_key_error())
        elif tk_key is not None:
            raise ValueError(self._launch_key_error())
        if self._datatype_schema is not None and dtype_key is None:
            raise ValueError(self._launch_key_error())
        if self._datatype_schema is None and dtype_key is not None:
            raise ValueError(self._launch_key_error())
        return stream, block_dim, tk_key, dtype_key