#!/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.language.typing.direction import TensorDirection
from pypto_pro.runtime.compile_config import KernelTarget, get_jit_compile_config
from pypto_pro.runtime.platform import NpuArch, normalize_arch

from .._errors import (
    CommonInner,
    InvalidArgument,
    InvalidOperation,
    InvalidShape,
    InvalidType,
    InvalidVal,
    NotSupported,
    OutOfRange,
    RuntimeFailure,
    error_class_of_spec_message,
    span_of_spec_message,
    span_source,
)

# A5 PyPTO Pro mixed kernels provide 8 KiB of static user UB, keep a
# separate 8 KiB reserved region, and require at least 32 KiB for SIMT
# Data Cache. PyPTO Tiles use absolute UB addresses via TASSIGN.
_A5_STATIC_UB_SIZE = 8 * 1024
_A5_MAX_USER_UB_SIZE = (256 - 8 - 32) * 1024
_A5_MAX_DYNAMIC_UB_SIZE = _A5_MAX_USER_UB_SIZE - _A5_STATIC_UB_SIZE
_A5_UB_ALIGNMENT = 32

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"] = {}

# Sanitizer GM log budget for one launch (~1GB, split across all regions).
# Each executing core owns one region laid out as [ctr u32, records...] and is
# the region's single writer, so no atomics are needed. The per-region record
# capacity is derived from the budget at launch time; with hundreds of
# thousands of record slots per core the capacity is effectively unlimited
# for debugging use. Allocation stays lazy-cost: only the per-region ctr word
# is zeroed and only the written part of each region is copied back to the
# host. KSANITIZER_SUB_BLOCKS mirrors the device-side region layout (an A5
# vector section addresses each AIV sub-block by its own get_block_idx, so
# each gets an independent region).
KSANITIZER_LOG_BUDGET_BYTES = 1 * 1024**3
KSANITIZER_SUB_BLOCKS = 4


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
    # Data direction of tensor params; non-tensor params leave it unset.
    direction: TensorDirection | None = 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 its native block budget comes from the vector core count alone.
    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 = ""
    # Kernel source path: supplies the report locations (records carry lines).
    source_file: str = ""
    has_cube: bool = False
    has_vector: bool = True
    target: KernelTarget | None = None
    needs_print_debug: bool = False
    # 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
    target: KernelTarget


@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
    sanitizer: bool = False
    # Kernel source path (report locations; set by _codegen).
    source_file: str = ""
    # Per-variant launch configuration consumed while generating call_kernel.cpp;
    # it is intentionally not part of CompiledKernel or the runtime ctypes ABI.
    required_dynamic_ub_size: int = 0


# 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*\(")
PYPTO_PRINTF_CALL_PATTERN = re.compile(r"\bpypto_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 _current_device_id() -> str | None:
    """The NPU device id this process is bound to, or None if the NPU is not initialized."""
    try:
        if not torch.npu.is_initialized():
            return None
        return str(torch.npu.current_device())
    except Exception:
        return None


def _current_rank() -> str | None:
    """This process's rank in its process group, or None outside a distributed job."""
    try:
        dist = torch.distributed
        if dist.is_available() and dist.is_initialized():
            return str(dist.get_rank())
    except Exception:
        return None
    return None


def _process_identity_tag() -> str:
    """The build dir name segment identifying this process: ``__d<device>_r<rank>``.

    Either component is omitted when unavailable (``__d0`` outside a distributed job); with
    both unavailable the tag is empty.
    """
    parts = []
    device = _current_device_id()
    if device:
        parts.append(f"d{device}")
    rank = _current_rank()
    if rank:
        parts.append(f"r{rank}")
    return f"__{'_'.join(parts)}" if parts else ""


def _make_artifact_build_dir(
    prog, arch: NpuArch, 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
    work_path = os.environ.get("ASCEND_WORK_PATH", "").strip()
    root = os.path.join(os.path.expanduser(work_path), "PYPTO_PRO") if work_path else "."
    return os.path.join(
        root,
        "build",
        f"{readable_prefix}__{arch}{tilingkey_suffix}{_process_identity_tag()}")


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 InvalidType("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 InvalidArgument(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 InvalidType(
                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 InvalidArgument(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 InvalidOperation(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 InvalidOperation(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 InvalidArgument("datatype dict was provided but this kernel has no datatype schema")
        return None
    if not isinstance(dtype_key, dict):
        raise InvalidType("datatype kernel launch requires a dtype dict")

    expected = set(spec)
    actual = set(dtype_key)
    if actual != expected:
        raise InvalidArgument(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 InvalidType(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 InvalidType(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 _atomic_write_text(path: Path, content: str) -> None:
    """Write ``content`` to ``path`` so concurrent readers never see a partial file.

    Unlike ``Path.write_text``, which truncates the target to zero bytes before writing, this
    writes a sibling temp file and renames it over the target: a reader gets either the complete
    old content or the complete new content. Readers holding an open descriptor keep reading the
    old content until they close it.

    The temp file is a sibling because rename is only atomic within one filesystem, is named
    with pid and a uuid so two writers never share it, and carries a leading dot to stay out of
    the ``*.h`` directory scans in pypto_compile.
    """
    tmp = path.with_name(f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp")
    try:
        tmp.write_text(content, encoding="utf-8")
        os.replace(tmp, path)
    finally:
        if tmp.exists():
            tmp.unlink()


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)
    _atomic_write_text(
        Path(output_dir, "datatype.json"),
        json.dumps(metadata, indent=2, sort_keys=True) + "\n",
    )


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 CommonInner(
        f"No Opaque kernel entry function found in program '{prog.name}' "
        f"(functions: {list(prog.functions)})"
    )


def _align_up(value: int, alignment: int) -> int:
    return (value + alignment - 1) // alignment * alignment


def _infer_dynamic_ub_size(requires_simt: bool, tile_high_water: int) -> int:
    """Infer A5 launch dynamic UB from parser-collected mixed-kernel facts."""
    if not requires_simt:
        return 0
    required = _align_up(max(0, tile_high_water - _A5_STATIC_UB_SIZE), _A5_UB_ALIGNMENT)
    if _A5_STATIC_UB_SIZE + required > _A5_MAX_USER_UB_SIZE:
        raise OutOfRange(
            f"SIMT kernel Vec Tile high-water mark {tile_high_water} bytes requires "
            f"static_ub_size={_A5_STATIC_UB_SIZE} and dynamic_ub_size={required}, but A5 allows at most "
            f"{_A5_MAX_USER_UB_SIZE} bytes of combined static and dynamic UB "
            f"(dynamic UB limit {_A5_MAX_DYNAMIC_UB_SIZE} bytes)"
        )
    return required


def _extract_param_specs(
    prog,
    declared_directions: dict[int, TensorDirection] | None = None,
) -> list[ParamSpec]:
    """Extract parameter descriptions from the kernel function in an ir.Program.

    Tensor directions are keyed by parameter index because codegen may rename
    parameters while preserving their order. Unspecified tensors default to
    TensorDirection.INPUT.
    """
    func = _get_kernel_ir_function(prog)
    declared_directions = declared_directions or {}
    specs: list[ParamSpec] = []
    for parameter_index, var in enumerate(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]
            direction = declared_directions.get(parameter_index, TensorDirection.INPUT)
            specs.append(ParamSpec(var.name, ParamKind.TENSOR, t.dtype, shape, direction))
        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 InvalidType(f"Parameter '{param_name}' has no dtype")
    cpp_type = dtype.to_c_type_string()
    if not cpp_type or cpp_type == "unknown":
        raise InvalidType(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(("int64_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 InvalidType(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 InvalidType(
                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 InvalidType(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 InvalidType(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 InvalidType(
                        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 CommonInner(
                "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
    ``int64_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.
    # Dynamic dimensions use int64_t in both the generated entry and the IR.
    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_int64] * plan.dyn_count
    )
    # Positive results are the actual block count; negative results carry native
    # resource-query errors. int64_t preserves the error tag above its 32-bit detail.
    call_kernel.restype = ctypes.c_int64
    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

    def entry(args: tuple, block_dim: int, stream):
        if has_tiling:
            args = _pack_tiling_arg(args)
        if len(args) != n_params:
            raise InvalidType(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 InvalidType(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 InvalidType(
                        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 InvalidType(
                        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 InvalidShape(
                        f"arg[{index}] '{name}': runtime dimensions must be positive, got {tuple(shape)}"
                    )
                for dim, expected in consts:
                    if shape[dim] != expected:
                        raise InvalidType(
                            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 InvalidShape(
                        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()
        # Python integers can exceed the uint32_t launch ABI. Saturate the request
        # before ctypes conversion so a large request cannot wrap to zero (0 is the
        # native auto sentinel) and is rejected by the native limit check instead.
        if block_dim > 0xFFFFFFFF:
            block_dim = 0xFFFFFFFF
        _set_dump_info(compiled, args, block_dim)
        # Resolve limits and launch in one C call, avoiding two torch_npu C-extension
        # calls and Python dict/loop work. Errors return before any device launch.
        actual_block_dim = call_kernel(block_dim, stream._as_parameter_, *abi_args)
        if actual_block_dim < 0:
            raise RuntimeFailure(_launch_error_message(actual_block_dim, block_dim, compiled))
        # 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)", actual_block_dim
                    )
                else:
                    logging.debug("Capture status [0], kernel launching in eager mode (block_dim=%d)", actual_block_dim)
            except (ImportError, AttributeError):
                pass

    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())


# aclDataType ids (acl_base.h) for the aclprofTensor.dataType field; keyed by str(DataType).
_ACL_DTYPE_MAP = {
    "fp32": 0,
    "fp16": 1,
    "int8": 2,
    "int32": 3,
    "uint8": 4,
    "int16": 6,
    "uint16": 7,
    "uint32": 8,
    "int64": 9,
    "uint64": 10,
    "float64": 11,
    "double": 11,
    "bool": 12,
    "bf16": 27,
    "bfloat16": 27,
    "fp8": 28,
    "hf8": 34,
    "fp8e5m2": 35,
    "fp8e4m3": 36,
    "fp8e8m0": 37,
    "fp4e2m1": 40,
    "fp4e1m2": 41,
}

_ACL_FORMAT_ND = 2  # aclFormat::ACL_FORMAT_ND


def _prof_shape_token(dim, dims_in_scope: set) -> str:
    """C++ expression for one tensor dim inside the generated launcher.

    Static dims become literals; named dynamic dims reference the matching
    int64_t dim parameter the launcher already receives; unknown dynamics
    (``-1``) degrade to 0.
    """
    if isinstance(dim, int) and dim > 0:
        return str(dim)
    if isinstance(dim, str) and dim in dims_in_scope:
        return f"static_cast<uint32_t>({dim})"
    return "0"


def _generate_prof_range_snippet(
    kernel_name: str,
    param_specs: list[ParamSpec],
    dims_in_scope: set,
    *,
    target: KernelTarget,
    launch_stmt: str,
) -> tuple[str, str, str]:
    """Generate tensor metadata for live profiling and cached graph replay.

    The helper reports msprof node records while collecting, and independently
    caches op/tensor info on captured tasks, including before collection starts.
    Both paths use the same concrete launch shapes, directions and core layout.
    String registration uses ``aclprofStr2Id`` from libmsprofiler; the
    ``ProfStr2Id`` alias in libprofapi must not be used (it can crash).
    Metadata failures must never break a launch.
    """
    tensors = [s for s in param_specs if s.kind == ParamKind.TENSOR]
    if not tensors:
        return "", "", ""

    block_nums = "blockDim"
    if target.aic_per_block and target.aiv_per_block:
        # CANN stores the AIV:AIC ratio in the upper 16 bits, as the ASC node
        # reporter does. Keep cached graph metadata consistent with that node.
        block_nums = f"(blockDim & 0xffffU) | ({target.aiv_per_block}U << 16)"

    tensor_inits = []
    for spec in tensors:
        dims = list(spec.shape or [])
        shape_tokens = [_prof_shape_token(d, dims_in_scope) for d in dims]
        padded = shape_tokens[:8] + ["0"] * (8 - min(len(shape_tokens), 8))
        direction = spec.direction if spec.direction is not None else TensorDirection.INPUT
        tensor_type = direction.value
        acl_dtype = _ACL_DTYPE_MAP.get(str(spec.dtype), 0)
        shape_str = "{" + ", ".join(padded) + "}"
        tensor_inits.append(
            f"        {{{tensor_type}, {_ACL_FORMAT_ND}, {acl_dtype}, "
            f"{min(len(dims), 8)}, {shape_str}}},"
        )

    op_name = f"PYPTO_{kernel_name}"
    # Keep tensors alive through the post-launch report/cache call. Outside
    # collection and capture, skip tensor initialization and string registration.
    return (
        '#include "acl/acl_prof.h"\n'
        '#include "pypto_profiler.h"\n',
        "    {\n"
        "        // Collection and graph metadata caching independently need tensors.\n"
        "        const bool pyptoProfOn = pypto::GetProfStatus();\n"
        "        aclrtStreamAttrValue pyptoCaptureAttr{};\n"
        "        const bool pyptoCaptureOn =\n"
        "            aclrtGetStreamAttribute(stream, ACL_STREAM_ATTR_CACHE_OP_INFO, &pyptoCaptureAttr) "
        "== ACL_SUCCESS &&\n"
        "            pyptoCaptureAttr.cacheOpInfoSwitch;\n"
        "        if (pyptoProfOn || pyptoCaptureOn) {\n"
        "        aclprofTensor pyptoProfTensors[] = {\n"
        + "\n".join(tensor_inits)
        + "\n        };\n"
        "        aclprofTensorInfo pyptoProfInfo{};\n"
        "        pyptoProfInfo.opNameId = aclprofStr2Id(\"" + op_name + "\");\n"
        "        pyptoProfInfo.opTypeId = aclprofStr2Id(\"PyPTO\");\n"
        "        pyptoProfInfo.resv = 0;\n"
        f"        pyptoProfInfo.tensorNum = {len(tensor_inits)};\n"
        f"        pyptoProfInfo.kernelType = {target.profiler_kernel_type};\n"
        f"        pyptoProfInfo.blockNums = {block_nums};\n"
        "        pyptoProfInfo.stream = stream;\n"
        "        pyptoProfInfo.tensors = pyptoProfTensors;\n"
        "        const uint64_t pyptoProfBegin = pypto::BeginCaptureTensorReport(pyptoProfOn);\n",
        "        pypto::ReportCaptureTensorInfo(pyptoProfInfo, pyptoProfBegin, pyptoCaptureOn);\n"
        "        } else {\n"
        + "    " + launch_stmt
        + "        }\n"
        "    }\n",
    )


def _scalar_launch_abi(typ: str, name: str) -> tuple[str, str, str]:
    """Return the physical entry type, host encoding and device decoding for a scalar.

    ASC launch metadata can place an int64 dimension four bytes after a narrow
    scalar, while the device loads it at an eight-byte boundary. Give every
    physical argument an eight-byte slot (pointers already have that size).
    The ctypes caller and the device impl retain their original DSL types.
    FP32 travels as bits, preserving signed zero and NaN payloads without FP64
    arithmetic on the device.
    """
    if typ in ("int64_t", "uint64_t"):
        return typ, name, name
    if typ == "float":
        return (
            "uint64_t",
            f"static_cast<uint64_t>(__builtin_bit_cast(uint32_t, {name}))",
            f"__builtin_bit_cast(float, static_cast<uint32_t>({name}))",
        )
    if typ in ("int8_t", "int16_t", "int32_t"):
        entry_type = "int64_t"
    elif typ in ("bool", "uint8_t", "uint16_t", "uint32_t"):
        entry_type = "uint64_t"
    else:
        raise InvalidType(f"Unsupported scalar launch type '{typ}' for parameter '{name}'")
    return entry_type, f"static_cast<{entry_type}>({name})", f"static_cast<{typ}>({name})"


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 = "",
    *,
    target: KernelTarget,
    prof_param_specs: list[ParamSpec] | None = None,
    required_dynamic_ub_size: int = 0,
) -> str:
    """Generate extern "C" wrapper that calls the __global__ kernel.

    Args:
        kernel_params: 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.
        target: The same resolved compiler target used to build the shared library.
        prof_param_specs:
            IR param specs (with tensor direction/shape) used to emit the
            aclprof tensor-info range around the launch; None disables it.
        required_dynamic_ub_size:
            Compile-time dynamic UB bytes embedded into this compiled variant's
            device launch. Zero preserves the original null launch argument.

    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(_scalar_launch_abi(typ, name)[1])
    sig = ", ".join(["uint32_t blockDim", "void* stream"] + cpp_params)
    call_args = ", ".join(kernel_args)

    sync_include = ""
    sync_setup = ""
    if has_cross_core_sync:
        call_args = f"{call_args}, (int64_t*)ffts" if call_args else "(int64_t*)ffts"
        sync_include = '#include "runtime/rt_ffts.h"\n'
        sync_setup = (
            "    uint64_t ffts = 0;\n"
            "    uint32_t fftsLen = 0;\n"
            "    rtGetC2cCtrlAddr(&ffts, &fftsLen);\n"
        )

    dynamic_ub_arg = str(required_dynamic_ub_size) if required_dynamic_ub_size else "nullptr"
    launch_stmt = f"    {kernel_name}<<<blockDim, {dynamic_ub_arg}, stream>>>({call_args});\n"

    prof_include, prof_push, prof_pop = ("", "", "")
    if prof_param_specs:
        dims_in_scope = {name for _, name, _is_ptr in kernel_params}
        prof_include, prof_push, prof_pop = _generate_prof_range_snippet(
            kernel_name, prof_param_specs, dims_in_scope, target=target, launch_stmt=launch_stmt
        )

    return (
        '#include "pypto_launch.h"\n'
        f'{prof_include}'
        f'{sync_include}'
        f'#include "{kernel_cpp_name}"\n'
        f'{global_entry}'
        f'extern "C" int64_t call_kernel({sig})\n'
        "{\n"
        f"    const int64_t launchDim = pypto::ResolveLaunchBlockDim<{target.aic_per_block}, {target.aiv_per_block}>"
        "(blockDim, stream);\n"
        "    if (launchDim < 0) {\n"
        "        return launchDim;\n"
        "    }\n"
        "    blockDim = static_cast<uint32_t>(launchDim);\n"
        f"{sync_setup}"
        f"{prof_push}"
        f"{launch_stmt}"
        f"{prof_pop}"
        "    return launchDim;\n"
        "}\n"
    )


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 PYPTO_PRINTF_CALL_PATTERN.search(scrubbed))


def _build_bisheng_flags(
    toolkit_home: str,
    arch: NpuArch,
    target: KernelTarget,
    has_cross_sync: bool,
    enable_print_debug: bool,
) -> list[str]:
    """Build bisheng flags using the compiler target already encoded in the launcher."""
    if has_cross_sync and not (target.aic_per_block and target.aiv_per_block):
        if target.aic_per_block:
            raise InvalidOperation("Contains ffts cross sync but vector code is missing.")
        if target.aiv_per_block:
            raise InvalidOperation("Contains ffts cross sync but cube code is missing.")
    return get_jit_compile_config().build_bisheng_flags(
        toolkit_home=toolkit_home,
        arch=arch,
        target=target,
        enable_print_debug=enable_print_debug,
    )


def _build_llvm_args(arch: NpuArch) -> list[str]:
    """Build architecture-specific LLVM/CCE arguments for C++ compilation."""
    return get_jit_compile_config().build_llvm_args(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: NpuArch,
    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, arg_types, field_types = probe_kernel_facts(kernel_def, bound_signature)
        # The analysis below walks the kernel's AST from here, where the parser's
        # SpanTracker is not in scope. Publish one so its errors can point at the
        # code they are about instead of naming a line number in their text.
        from pypto_pro.language.parser._span_tracker import SpanTracker

        pipeline_spans = SpanTracker(
            kernel_def._source_file,
            kernel_def._source_lines,
            kernel_def._line_offset,
            kernel_def._col_offset,
        )
        with span_source(pipeline_spans.get_span):
            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,
                arg_types=arg_types,
                field_types=field_types,
                tilingkey_consts=kernel_def._tilingkey_consts,
                datatype_consts=kernel_def._datatype_consts,
            )
        generated_source, kernel_def._func_def = 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._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]],
    *,
    target: KernelTarget,
) -> str:
    """Decode eight-byte launch slots into the original ``<kernel_name>_impl`` types."""
    decls = []
    args = []
    for typ, name, is_ptr in entry_params:
        if is_ptr:
            decls.append(f"__gm__ {typ}* {name}")
            args.append(name)
        else:
            entry_type, _, decoded = _scalar_launch_abi(typ, name)
            decls.append(f"{entry_type} {name}")
            args.append(decoded)
    sig = ", ".join(decls)
    call_args = ", ".join(args)

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


def _codegen_target_cce(
    prog,
    arch: NpuArch,
    build_dir: str,
    target: ir.SectionKind,
    declared_directions: dict[int, TensorDirection] | None = None,
    required_dynamic_ub_size: int = 0,
) -> CodegenResult:
    """CCE codegen for one target-specific Program.

    Key-independent: produces no launcher and does not write final artifacts.
    """
    cce_codegen = CCECodegen(target)
    try:
        cpp_code = cce_codegen.generate_single(prog, arch)
    except RuntimeError as exc:
        # A C++ check states its own first line, code and DSL location. Carry it into
        # the class that code names, the way the parse path does, so the location block
        # renders its source preview rather than reaching the user as a bare
        # RuntimeError. Anything without that first line is not ours to reclassify.
        wrapper = error_class_of_spec_message(str(exc))
        if wrapper is None:
            raise
        raise wrapper(str(exc), span=span_of_spec_message(str(exc))) from None
    if "ffts_cross_core_sync" in cpp_code and arch == NpuArch.DAV_3510:
        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, declared_directions)
    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,
        required_dynamic_ub_size=required_dynamic_ub_size,
    )


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 CommonInner("Cannot assemble Cube/Vector source without a target")

    reference = results[0]
    for result in results[1:]:
        if result.kernel_name != reference.kernel_name:
            raise CommonInner("Cube/Vector kernel names do not match")
        if result.param_specs != reference.param_specs:
            raise CommonInner("Cube/Vector kernel parameter specifications do not match")
        if result.kernel_params != reference.kernel_params:
            raise CommonInner("Cube/Vector kernel ABIs do not match")
        if result.build_dir != reference.build_dir:
            raise CommonInner("Cube/Vector build directories do not match")
        if result.tiling_headers != reference.tiling_headers:
            raise CommonInner("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,
        required_dynamic_ub_size=max(result.required_dynamic_ub_size for result in results),
    )


def _parse_and_codegen_targets(
    kernel_def,
    arch: NpuArch,
    build_dir: str,
    bound_signature=None,
    sanitizer: bool = False,
) -> tuple[CodegenResult | None, CodegenResult | None]:
    """Parse both targets, treating a sectionless kernel as shared by both.

    With ``sanitizer`` enabled, each parsed target program is instrumented
    (block.sanitizer_log records injected, one per detection type and
    sanitizer_log pointer + capacity scalar appended to the kernel signature);
        the flag is carried on the returned CodegenResults."""
    programs = {}
    matched = {}
    requires_simt = False
    max_vec_tile_end = 0
    for target in (ir.SectionKind.Cube, ir.SectionKind.Vector):
        programs[target], matched[target] = kernel_def.parse_target_program(
            target=target,
            bound_signature=bound_signature,
        )
        requires_simt = requires_simt or kernel_def.requires_simt
        max_vec_tile_end = max(max_vec_tile_end, kernel_def.max_vec_tile_end)
    # Tensor directions are keyed by stable source parameter index; unspecified
    # tensor parameters default to TensorDirection.INPUT.
    declared_directions = kernel_def.last_param_directions

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

    required_dynamic_ub_size = _infer_dynamic_ub_size(requires_simt, max_vec_tile_end)

    if sanitizer:
        from pypto.pypto_impl.ir import Pass as IRPass

        sanitizer_pass = IRPass.sanitizer()
        target_list = [t for t in (ir.SectionKind.Cube, ir.SectionKind.Vector)
                       if matched.get(t) and programs.get(t) is not None]
        for target in target_list:
            programs[target] = sanitizer_pass(programs[target])

    results = {
        target: (
            _codegen_target_cce(
                programs.get(target), arch, build_dir, target=target,
                declared_directions=declared_directions,
                required_dynamic_ub_size=required_dynamic_ub_size,
            )
            if matched.get(target)
            else None
        )
        for target in (ir.SectionKind.Cube, ir.SectionKind.Vector)
    }
    for target in (ir.SectionKind.Cube, ir.SectionKind.Vector):
        if results[target] is not None:
            results[target].sanitizer = sanitizer
    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)
    _atomic_write_text(Path(result.build_dir, "kernel.cpp"), result.content)
    for header_name, header_content in result.tiling_headers.items():
        _atomic_write_text(Path(result.build_dir, header_name), header_content)


def _add_kernel_header(result: CodegenResult) -> CodegenResult:
    """Add the translation-unit header after all target sources are assembled."""
    header = KERNEL_HEADER_SINGLE
    if result.needs_print_debug:
        header += "\n#define __ENABLE_ASC_PRINTF__ 1\n"
    return dataclasses.replace(
        result,
        content=f"{header}\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 = Path(out_dir, "pipeline_generated.py")
    _atomic_write_text(path, source)
    # The parse that follows reports against this file: the reparsed function's nodes
    # carry their positions in it, and the original file has no line for a generated one.
    kernel_def._source_file = str(path)
    kernel_def._source_lines = source.split("\n")
    kernel_def._source_lines_raw = list(kernel_def._source_lines)
    kernel_def._line_offset = 0
    kernel_def._col_offset = 0


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: NpuArch,
    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: NpuArch,
    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 RuntimeFailure("ASCEND_HOME_PATH is not set")
    link_args = _runtime_link_args(ascend_home_path)
    # The generated caller references the aclprof* tensor-info range interfaces
    # (aclprofStr2Id / aclprofRangePushEx / aclprofRangePop, declared in
    # acl/acl_prof.h); they are exported by libmsprofiler.so in the runtime lib
    # dir, so make sure it is on the link line.
    if "-lmsprofiler" not in link_args:
        link_args = link_args + ["-lmsprofiler"]

    resolved_enable_print_debug = generated.needs_print_debug
    flags = _build_bisheng_flags(
        pto_lib_path,
        arch,
        generated.target,
        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: NpuArch,
    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], ...] = (),
    sanitizer: bool = False,
) -> 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 CommonInner("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,
        sanitizer,
    )
    result = _assemble_cv_source(cube, vector)
    result.sanitizer = (cube is not None and cube.sanitizer) or (vector is not None and vector.sanitizer)
    result.source_file = getattr(source, "_source_file", "")

    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,
    *,
    target: KernelTarget,
) -> 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, target=target)

    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,
        target=target,
        prof_param_specs=cg.param_specs,
        required_dynamic_ub_size=cg.required_dynamic_ub_size,
    )
    _atomic_write_text(Path(paths.final_kernel), caller_content)

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


def get_current_arch() -> NpuArch:
    """Return the arch configured in the current process environment."""
    raw = os.environ.get("PYPTOPRO_JIT_ARCH")
    return normalize_arch(raw) if raw else NpuArch.DAV_3510


def _setup_arch_env(arch: NpuArch) -> NpuArch:
    """Validate *arch* and export the env vars used by compilation."""
    if not arch:
        raise InvalidVal("arch must not be empty")
    if arch != NpuArch.DAV_3510:
        raise NotSupported(f"PyPTO Pro only supports arch '3510', got '{arch}'")
    os.environ["PYPTOPRO_JIT_ARCH"] = str(arch)
    return arch


def _launch_error_message(error_code: int, requested_block_dim: int, compiled: "CompiledKernel | None") -> str:
    """Decode the native -(kind << 32 | detail) launch error into a readable message.

    The raw code stays in the message for log grepping; the appended text explains
    the rejection in terms the caller can act on. ``requested_block_dim`` is the
    value handed to the launcher (0 only for the auto sentinel, which is never
    rejected as an over-budget request).
    """
    code = -int(error_code)
    kind, detail = code >> 32, code & 0xFFFFFFFF
    prefix = f"Kernel launch failed with error code {error_code}"
    if kind == 5:
        return f"{prefix}: requested block_dim {requested_block_dim} exceeds the stream budget of {detail} block(s)"
    if kind in (1, 2):
        engine = "cube" if kind == 1 else "vector"
        target = getattr(compiled, "target", None)
        per_block = (target.aic_per_block if kind == 1 else target.aiv_per_block) if target else 0
        if per_block:
            return (
                f"{prefix}: the stream's {engine} budget of {detail} core(s) cannot host one block "
                f"of {per_block} {engine} core(s)"
            )
        return f"{prefix}: the stream's {engine} budget of {detail} core(s) cannot host one block"
    if kind in (3, 4):
        engine = "cube" if kind == 3 else "vector"
        return f"{prefix}: querying the stream's {engine} budget failed with ACL error {detail:#x}"
    return f"{prefix} (kind={kind}, detail={detail:#x})"


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 _format_findings(findings) -> str:
    """One block of human-readable findings (or the clean-run marker).

    Multi-line findings (message + Hint) are indented to the kind column so
    the Hint lines up with the leading G of GM_OUT_OF_BOUNDS et al.
    """
    if not findings:
        return "PyPTO Sanitizer: no issues detected\n"
    lines = [f"PyPTO Sanitizer: {len(findings)} issue(s) detected\n"]
    for i, finding in enumerate(findings, 1):
        prefix = f"[{i}/{len(findings)}] "
        pad = " " * len(prefix)
        for j, line in enumerate(str(finding).split("\n")):
            lines.append(f"{prefix}{line}\n" if j == 0 else f"{pad}{line}\n")
    return "".join(lines)


def _replay_sanitizer(log_buffer, capacity_u32, block_dim, build_dir, kernel_name, source_file):
    """Wait for the launch, read the written part of the device log buffer
    back, merge it with the compile-time metadata into one
    ``sanitizer_report.bin``, scan that file with the registered detections
    and raise an aggregated report when findings exist.

    Results go to pypto_sanitizer_report.txt next to sanitizer_report.bin in
    the kernel's build dir (one file per compile instance), appended per
    launch (kernel-tagged). No terminal output; an uncaught
    SanitizerReplayError is the only on-screen signal.

    Replay failures are never swallowed: when the sanitizer is enabled the
    developer expects the detection result to be trustworthy, so a broken
    decode or check must surface instead of silently producing a "clean"
    result.
    """
    from pypto_pro.runtime.sanitizer_replay import SanitizerReplayError, build_report_file, scan_report_file

    torch.npu.synchronize()
    words_per_region = capacity_u32 + 1
    flat = log_buffer.view(torch.int32)
    # Lazy copy-back stage 1: the per-region write counters only.
    ctrs = flat[::words_per_region].cpu().tolist()
    # Stage 2: for each region copy back just the ctr word and the records
    # actually written (a region that never executed copies one word).
    region_chunks = []
    for region_idx, ctr in enumerate(ctrs):
        written = min(int(ctr), capacity_u32)
        start = region_idx * words_per_region
        region_chunks.append(flat[start:start + 1 + written].cpu().numpy().tobytes())
    report_path = os.path.join(build_dir, "sanitizer_report.bin")
    build_report_file(region_chunks, report_path)
    findings = scan_report_file(report_path, source_file)
    # Detection result file, appended per launch (kernel-tagged), next to
    # sanitizer_report.bin in the build dir.
    report_file = os.path.join(build_dir, "pypto_sanitizer_report.txt")
    with open(report_file, "a", encoding="utf-8") as f:
        f.write(f"===== kernel '{kernel_name}' ({build_dir}) =====\n")
        f.write(_format_findings(findings))
        f.write("\n")
    if findings:
        raise SanitizerReplayError(findings)


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 InvalidType(
            f"block_dim must be a positive integer, got {type(block_dim).__name__}: {block_dim}"
        )
    if block_dim <= 0:
        raise InvalidType(
            f"block_dim must be a positive integer, got {block_dim}"
        )


# block_dim handed to the native launcher when the caller did not pick a core
# count (direct kernel call); the native side resolves it to the stream's full
# block budget (kAutoBlockDim in pypto_launch.h). Bracket-launch input is
# validated positive by _validate_block_dim and saturated before the ABI, so a
# user-supplied 0 cannot reach this protocol.
_AUTO_BLOCK_DIM = 0


def _auto_block_upper_bound(compiled: "CompiledKernel") -> int:
    """Device-level upper bound on the auto-resolved block count, used to size
    host resources (the sanitizer log buffer) before the native launch resolves
    the sentinel; it can over-estimate, never under-estimate."""
    from pypto_pro.runtime.platform import get_platform_info

    info = get_platform_info()
    target = compiled.target
    if target is not None and info.core_num > 0:
        blocks = []
        if target.aic_per_block:
            blocks.append(info.cube_core_num // target.aic_per_block)
        if target.aiv_per_block:
            blocks.append(info.vector_core_num // target.aiv_per_block)
        if blocks and min(blocks) > 0:
            return min(blocks)
    raise RuntimeError(
        "Cannot size per-block host resources for an auto block_dim launch: "
        "platform core counts are unavailable for this kernel"
    )


def _build_sanitizer_entry(compiled: "CompiledKernel", build_dir: str):
    """Wrap the launch entry of an instrumented kernel with the sanitizer glue.

    Keeps the upstream entry mechanism (``_build_launch_entry``) untouched:
    the base entry performs the ABI packing / validation / call, and this
    wrapper only (a) allocates the GM log buffer and appends the two hidden
    ``sanitizer_log``/``sanitizer_log_capacity`` arguments, then (b) reads the
    buffer back, merges it with the compile-time metadata into a single
    ``sanitizer_report.bin`` and scans that file with the registered
    detections.

    Loaded lazily on the first launch via ``compiled.entry``, exactly like the
    non-sanitizer path.
    """
    base_entry = _build_launch_entry(compiled)

    def entry(args: tuple, block_dim: int, stream):
        # The sentinel cannot size the buffer (the actual count is resolved
        # natively at launch); size by the device-level upper bound instead,
        # while the launch itself still carries the sentinel.
        sized_dim = _auto_block_upper_bound(compiled) if block_dim == _AUTO_BLOCK_DIM else block_dim
        regions = KSANITIZER_SUB_BLOCKS * sized_dim
        words_per_region = KSANITIZER_LOG_BUDGET_BYTES // (4 * regions)
        nbytes = words_per_region * 4 * regions
        log_buffer = torch.empty(nbytes, dtype=torch.uint8, device="npu")
        # Only the per-region ctr word must start at zero; the record area is
        # write-before-read on the device, so zeroing it would be wasted cost.
        log_buffer.view(torch.int32)[::words_per_region] = 0
        capacity_u32 = words_per_region - 1
        full_args = (*args, log_buffer, capacity_u32)
        base_entry(full_args, block_dim, stream)
        _replay_sanitizer(log_buffer, capacity_u32, sized_dim, build_dir, compiled.kernel_name, compiled.source_file)

    return entry


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 InvalidOperation(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 InvalidOperation(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,
    sanitizer: bool = False,
    **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 ("3510" -- the __NPU_ARCH__ version; "a5" is a
            deprecated alias; or None for auto-detect).
        auto_mutex: Boolean flag to 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="3510")
        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)
    """

    if not isinstance(auto_mutex, bool):
        raise TypeError(f"auto_mutex must be a bool, got {type(auto_mutex).__name__}")

    if arch is not None:
        arch = normalize_arch(arch)

    # 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 InvalidArgument(
                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,
                sanitizer=sanitizer,
            )
        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, full core budget (auto)
    """

    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,
        sanitizer=False,
    ):
        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
        self._sanitizer = sanitizer
        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.

        ``block_dim`` is the exact worker block count and must fit the current
        stream's torch_npu resource limits, including device defaults and
        npugraph_ex scopes; a request above the limit fails the launch instead
        of being silently reduced. Kernels must partition all work using
        ``get_block_num()`` (and ``get_subblock_num()`` for mixed vector
        workers), not a fixed host core count. A captured graph retains its
        launch dimensions until recaptured.

        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)
        # get_stream_limit used to validate this on every invocation. Keep foreign
        # handles out of ACL, but validate the fixed explicit stream only once when
        # constructing the launcher. None resolves to a torch NPU stream at launch.
        if stream is not None and not isinstance(stream, torch.npu.Stream):
            raise InvalidType(f"stream must be torch.npu.Stream or None, got {type(stream).__name__}")
        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):
            self._validate_launch_arch()
            # 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: default stream, block_dim resolved to the stream's full budget."""
        if self._tilingkey_schema is not None or self._datatype_schema is not None:
            raise NotSupported(
                f"Kernel '{self.__name__}' has compile-time specialization and cannot be called directly; "
                "use bracket-launch syntax"
            )
        self._validate_launch_arch()
        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, _AUTO_BLOCK_DIM, None)

    def _validate_launch_arch(self) -> None:
        from pypto_pro.runtime.platform import get_platform_info

        platform_arch = get_platform_info().arch
        if self._arch is None:
            self._arch = platform_arch
        elif self._arch != platform_arch:
            plat = f"'{platform_arch}'" if platform_arch is not None else "unknown"
            raise NotSupported(f"JIT arch '{self._arch}' does not match current platform arch {plat}")

    @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 InvalidType(
                    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 InvalidType(
                    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
        self._arch = _setup_arch_env(self._arch)
        arch = self._arch
        logging.info(
            "Generating kernel '%s' for static shape signature %s",
            self.__name__,
            static_signature or "<dynamic-only>",
        )
        kernel_def = self.to_kernel_def(concrete_key, datatype_consts=dtype_consts)
        cg = _codegen(
            kernel_def,
            arch,
            clean_up=False,
            tilingkey_packed=tilingkey_packed,
            datatype_hash=dtype_hash,
            datatype_metadata=dtype_metadata,
            bound_signature=bound_signature,
            static_signature=static_signature,
            sanitizer=self._sanitizer,
        )
        if cg is None:
            raise RuntimeFailure(f"Failed to generate code for kernel '{self.__name__}'")

        # Resolve once for compiler flags, the native block-budget check and debug
        # recompilation. Every consumer must use this binary's same core geometry.
        target = get_jit_compile_config().resolve_kernel_target(
            arch, has_cube=cg.has_cube, has_vector=cg.has_vector,
        )
        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,
            target=target,
        )
        if lib_path is None:
            raise RuntimeFailure(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,
            target=target, source_file=cg.source_file,
            needs_print_debug=cg.needs_print_debug,
        )
        if self._sanitizer:
            # Pre-bind the sanitizer wrapper as the launch entry: it allocates
            # the GM log buffer, appends the hidden sanitizer_log arguments,
            # launches via the upstream entry, builds the single report file
            # and scans it for detections.
            compiled.entry = _build_sanitizer_entry(compiled, cg.build_dir)
        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 InvalidArgument(self._launch_key_error())
        else:
            stream = None
            block_dim = key

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