Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

42.2 KB
Raw Blame
"""Tests for function batching and runner support."""

import asyncio
from collections.abc import Iterator
from typing import Any

import cocoindex as coco
from cocoindex._internal.runner import Runner
from cocoindex.resources.rate_limit import RateLimiter
import pytest


# ============================================================================
# Test utilities for event-based synchronization
# ============================================================================


async def wait_for_condition(
    condition: Any, timeout: float = 2.0, interval: float = 0.01
) -> None:
    """Wait until condition() returns True, with timeout."""
    elapsed = 0.0
    while elapsed < timeout:
        if condition():
            return
        await asyncio.sleep(interval)
        elapsed += interval
    raise TimeoutError(f"Condition not met within {timeout}s")


# ============================================================================
# Basic batching tests
# ============================================================================


@coco.fn.as_async(batching=True)
def _double_sync(inputs: list[int]) -> list[int]:
    """Sync batched function that doubles inputs.

    Note: With batching=True via coco.fn.as_async, this becomes an async function externally,
    even though the underlying implementation is sync.
    """
    return [x * 2 for x in inputs]


@pytest.mark.asyncio
async def test_batching_basic_sync() -> None:
    """Test basic sync batching - single call (now async externally)."""
    result = await _double_sync(5)
    assert result == 10


@coco.fn.as_async(batching=True)
async def _double_async(inputs: list[int]) -> list[int]:
    """Async batched function that doubles inputs."""
    await asyncio.sleep(0.01)  # Simulate async work
    return [x * 2 for x in inputs]


@pytest.mark.asyncio
async def test_batching_basic_async() -> None:
    """Test basic async batching - single call."""
    result = await _double_async(5)
    assert result == 10


# ============================================================================
# Concurrent calls get batched together
# ============================================================================


class TrackedBatcher:
    """Helper class for tracking batch calls with event-based synchronization.

    Uses pre-created events keyed by input value, similar to the Rust test pattern
    where each input has its own oneshot receiver.
    """

    def __init__(self) -> None:
        self.batch_call_count = 0
        self.batch_inputs: list[list[int]] = []
        # Pre-created events keyed by input value
        self.input_events: dict[int, asyncio.Event] = {}

    def create_event(self, value: int) -> asyncio.Event:
        """Create an event for a specific input value."""
        event = asyncio.Event()
        self.input_events[value] = event
        return event

    def create_function(self) -> Any:
        """Create a tracked batched function."""
        tracker = self

        @coco.fn.as_async(batching=True)
        async def tracked_double(inputs: list[int]) -> list[int]:
            """Async batched function that tracks calls and waits for signals."""
            tracker.batch_call_count += 1
            tracker.batch_inputs.append(sorted(inputs))
            # Wait for all input events before returning
            for v in inputs:
                await tracker.input_events[v].wait()
            return [x * 2 for x in inputs]

        return tracked_double


@pytest.mark.asyncio
async def test_batching_concurrent_calls() -> None:
    """Test that concurrent calls get batched together."""
    tracker = TrackedBatcher()
    tracked_double = tracker.create_function()

    # Pre-create events for each input
    for v in [1, 2, 3, 4, 5]:
        tracker.create_event(v)

    # Submit first call - it should execute inline
    task1 = asyncio.create_task(tracked_double(1))

    # Wait for first batch (inline call) to be recorded
    await wait_for_condition(lambda: len(tracker.batch_inputs) >= 1)

    # Now submit remaining calls - they should batch together
    # since the first call is still ongoing
    task2 = asyncio.create_task(tracked_double(2))
    task3 = asyncio.create_task(tracked_double(3))
    task4 = asyncio.create_task(tracked_double(4))
    task5 = asyncio.create_task(tracked_double(5))

    # Verify first batch is recorded, others are waiting
    assert tracker.batch_inputs == [[1]]

    # Unblock first call - this should trigger batch for 2-5
    tracker.input_events[1].set()

    # Wait for second batch to be recorded
    await wait_for_condition(lambda: len(tracker.batch_inputs) >= 2)

    # First call should be done
    result1 = await task1
    assert result1 == 2

    # Unblock remaining calls
    for v in [2, 3, 4, 5]:
        tracker.input_events[v].set()

    results = await asyncio.gather(task2, task3, task4, task5)

    # Results should be correct
    assert list(results) == [4, 6, 8, 10]


# ============================================================================
# max_batch_size is respected
# ============================================================================


class MaxBatchTracker:
    """Helper for testing max_batch_size with event-based synchronization."""

    def __init__(self, max_batch_size: int) -> None:
        self.max_batch_size = max_batch_size
        self.batch_sizes: list[int] = []

    def create_function(self) -> Any:
        """Create a batched function with max_batch_size."""
        tracker = self

        @coco.fn.as_async(batching=True, max_batch_size=tracker.max_batch_size)
        async def limited_double(inputs: list[int]) -> list[int]:
            """Batched function that tracks sizes and waits for signal."""
            tracker.batch_sizes.append(len(inputs))
            return [x * 2 for x in inputs]

        return limited_double


@pytest.mark.asyncio
async def test_batching_max_batch_size() -> None:
    """Test that max_batch_size is respected."""
    tracker = MaxBatchTracker(max_batch_size=2)
    limited_double = tracker.create_function()

    # Submit 5 items concurrently
    task1 = asyncio.create_task(limited_double(1))
    task2 = asyncio.create_task(limited_double(2))
    task3 = asyncio.create_task(limited_double(3))
    task4 = asyncio.create_task(limited_double(4))
    task5 = asyncio.create_task(limited_double(5))

    results = await asyncio.gather(task1, task2, task3, task4, task5)

    # Results should be correct
    assert sorted(results) == [2, 4, 6, 8, 10]

    # All batch sizes should be <= 2
    for size in tracker.batch_sizes:
        assert size <= 2, f"Batch size {size} exceeds max_batch_size=2"


# ============================================================================
# Method batching (with self)
# ============================================================================


class BatchedProcessor:
    """Class with batched method using event-based synchronization.

    Uses pre-created events keyed by input value.
    """

    def __init__(self, multiplier: int):
        self.multiplier = multiplier
        self.call_count = 0
        self.batch_inputs: list[list[int]] = []
        self.input_events: dict[int, asyncio.Event] = {}

    def create_event(self, value: int) -> asyncio.Event:
        """Create an event for a specific input value."""
        event = asyncio.Event()
        self.input_events[value] = event
        return event

    @coco.fn.as_async(batching=True)
    async def multiply(self, inputs: list[int]) -> list[int]:
        """Batched method that multiplies inputs, waits for signals."""
        self.call_count += 1
        self.batch_inputs.append(sorted(inputs))
        # Wait for all input events
        for v in inputs:
            await self.input_events[v].wait()
        return [x * self.multiplier for x in inputs]


@pytest.mark.asyncio
async def test_batching_method() -> None:
    """Test batching with methods."""
    proc = BatchedProcessor(3)
    proc.create_event(5)

    # Create task and wait for batch to be recorded
    task = asyncio.create_task(proc.multiply(5))
    await wait_for_condition(lambda: len(proc.batch_inputs) >= 1)

    # Signal completion
    proc.input_events[5].set()

    result = await task
    assert result == 15


@pytest.mark.asyncio
async def test_batching_method_concurrent() -> None:
    """Test concurrent calls to batched method."""
    proc = BatchedProcessor(3)

    # Pre-create events
    for v in [1, 2, 3]:
        proc.create_event(v)

    # Submit first call - it should execute inline
    task1 = asyncio.create_task(proc.multiply(1))

    # Wait for first batch to be recorded
    await wait_for_condition(lambda: len(proc.batch_inputs) >= 1)

    # Submit remaining calls - they should batch together
    task2 = asyncio.create_task(proc.multiply(2))
    task3 = asyncio.create_task(proc.multiply(3))

    # Unblock first call - triggers batch for 2,3
    proc.input_events[1].set()

    # Wait for second batch
    await wait_for_condition(lambda: len(proc.batch_inputs) >= 2)

    result1 = await task1
    assert result1 == 3

    # Unblock remaining calls
    proc.input_events[2].set()
    proc.input_events[3].set()

    results = await asyncio.gather(task2, task3)

    assert sorted(results) == [6, 9]


# ============================================================================
# Out of component context
# ============================================================================


@pytest.mark.asyncio
async def test_batching_out_of_component() -> None:
    """Test that batched functions work outside of CocoIndex app."""
    # This should work without any component context

    @coco.fn.as_async(batching=True)
    def standalone_double(inputs: list[int]) -> list[int]:
        return [x * 2 for x in inputs]

    result = await standalone_double(42)
    assert result == 84


# ============================================================================
# Error propagation: exception type + traceback survive for all callers
# ============================================================================


class _CustomBatchError(Exception):
    """Distinct type so we can assert it survives the batch round-trip."""


@pytest.mark.asyncio
async def test_batching_error_preserves_type_for_all_callers() -> None:
    """A raising batched impl propagates the *same* exception type to every
    concurrent caller β€” including the residual recipients the batcher fans
    the failure out to β€” not a flattened RuntimeError.

    Regression for the PyErr-through-residuals fix: residuals used to come
    back as RuntimeError with the original type and traceback lost. Only the
    first caller in a batch ever saw the real exception.
    """
    started = asyncio.Event()
    release = asyncio.Event()

    @coco.fn.as_async(batching=True)
    async def failing(inputs: list[int]) -> list[int]:
        started.set()
        await release.wait()
        raise _CustomBatchError("boom")

    # First call runs inline and blocks inside the impl, keeping the queue
    # busy so the next two calls queue into a single pending batch.
    task1 = asyncio.create_task(failing(1))
    await started.wait()

    task2 = asyncio.create_task(failing(2))
    task3 = asyncio.create_task(failing(3))
    await asyncio.sleep(0.05)  # let task2/task3 enqueue behind the inline call

    release.set()

    results = await asyncio.gather(task1, task2, task3, return_exceptions=True)

    # Every caller β€” inline (task1), first batch recipient (task2), and
    # residual recipient (task3) β€” sees the original exception type, with
    # its message intact.
    for r in results:
        assert isinstance(r, _CustomBatchError), (
            f"expected _CustomBatchError, got {type(r).__name__}: {r!r}"
        )
        assert str(r) == "boom"
        # Traceback is preserved (clone_ref keeps the original exception).
        assert r.__traceback__ is not None


# ============================================================================
# Async batching tests
# ============================================================================


_async_batch_count = 0


@coco.fn.as_async(batching=True)
async def _async_tracked_double(inputs: list[int]) -> list[int]:
    """Async batched function that tracks calls."""
    global _async_batch_count
    _async_batch_count += 1
    await asyncio.sleep(0.05)
    return [x * 2 for x in inputs]


@pytest.mark.asyncio
async def test_batching_async_concurrent() -> None:
    """Test concurrent async calls get batched."""
    global _async_batch_count
    _async_batch_count = 0

    # Submit multiple async calls concurrently
    results = await asyncio.gather(
        _async_tracked_double(1),
        _async_tracked_double(2),
        _async_tracked_double(3),
    )

    assert sorted(results) == [2, 4, 6]


# ============================================================================
# Runner tests (without subprocess to avoid test complexity)
# ============================================================================


class MockRunner(Runner):
    """Mock runner for testing.

    Extends the Runner base class with tracking for calls.
    """

    def __init__(self) -> None:
        super().__init__()
        self.call_count = 0
        self.last_args: tuple[Any, ...] = ()

    async def run(self, fn: Any, *args: Any, **kwargs: Any) -> Any:
        """Execute an async function."""
        self.call_count += 1
        self.last_args = args
        return await fn(*args, **kwargs)

    async def run_sync_fn(self, fn: Any, *args: Any, **kwargs: Any) -> Any:
        """Execute a sync function (async wrapper)."""
        self.call_count += 1
        self.last_args = args
        # Wrap sync function execution in to_thread to simulate async behavior
        return await asyncio.to_thread(fn, *args, **kwargs)


@pytest.mark.asyncio
async def test_runner_basic() -> None:
    """Test basic runner functionality."""
    runner = MockRunner()

    @coco.fn.as_async(runner=runner)
    def add_one(x: int) -> int:
        return x + 1

    result = await add_one(5)
    assert result == 6
    assert runner.call_count == 1


@pytest.mark.asyncio
async def test_runner_with_batching() -> None:
    """Test runner combined with batching."""
    runner = MockRunner()

    @coco.fn.as_async(batching=True, runner=runner)
    def double_batch(inputs: list[int]) -> list[int]:
        return [x * 2 for x in inputs]

    result = await double_batch(5)
    assert result == 10
    assert runner.call_count >= 1


# ============================================================================
# Queue sharing tests
# ============================================================================


@pytest.mark.asyncio
async def test_runner_queue_sharing() -> None:
    """Test that functions with the same runner share a queue."""
    runner = MockRunner()
    execution_order: list[str] = []
    fn_events: list[asyncio.Event] = []

    @coco.fn.as_async(runner=runner)
    async def fn_a(x: int) -> int:
        execution_order.append("a")
        event = asyncio.Event()
        fn_events.append(event)
        await event.wait()
        return x + 1

    @coco.fn.as_async(runner=runner)
    async def fn_b(x: int) -> int:
        execution_order.append("b")
        event = asyncio.Event()
        fn_events.append(event)
        await event.wait()
        return x + 2

    # Run both concurrently
    task1 = asyncio.create_task(fn_a(1))
    task2 = asyncio.create_task(fn_b(2))

    # Wait for events to be registered
    await wait_for_condition(lambda: len(fn_events) >= 2)

    # Signal completion
    for event in fn_events:
        event.set()

    r1, r2 = await asyncio.gather(task1, task2)

    assert r1 == 2
    assert r2 == 4

    # Both should have gone through the runner
    assert runner.call_count == 2


# ============================================================================
# Runner with multiple arguments tests
# ============================================================================


@pytest.mark.asyncio
async def test_runner_multiple_args() -> None:
    """Test runner with multiple positional arguments."""
    runner = MockRunner()

    @coco.fn.as_async(runner=runner)
    def add(a: int, b: int, c: int) -> int:
        return a + b + c

    result = await add(1, 2, 3)
    assert result == 6
    assert runner.call_count == 1


@pytest.mark.asyncio
async def test_runner_with_kwargs() -> None:
    """Test runner with keyword arguments."""
    runner = MockRunner()

    @coco.fn.as_async(runner=runner)
    def greet(name: str, greeting: str = "Hello") -> str:
        return f"{greeting}, {name}!"

    result1 = await greet("Alice")
    assert result1 == "Hello, Alice!"

    result2 = await greet("Bob", greeting="Hi")
    assert result2 == "Hi, Bob!"

    assert runner.call_count == 2


@pytest.mark.asyncio
async def test_runner_mixed_args_kwargs() -> None:
    """Test runner with both positional and keyword arguments."""
    runner = MockRunner()

    @coco.fn.as_async(runner=runner)
    def format_message(
        template: str, *values: int, prefix: str = "", suffix: str = ""
    ) -> str:
        formatted = template.format(*values)
        return f"{prefix}{formatted}{suffix}"

    result = await format_message("{} + {} = {}", 1, 2, 3, prefix="[", suffix="]")
    assert result == "[1 + 2 = 3]"
    assert runner.call_count == 1


@pytest.mark.asyncio
async def test_runner_multiple_args_async() -> None:
    """Test async runner with multiple arguments."""
    runner = MockRunner()

    @coco.fn.as_async(runner=runner)
    async def async_add(a: int, b: int, c: int) -> int:
        return a + b + c

    result = await async_add(10, 20, 30)
    assert result == 60
    assert runner.call_count == 1


@pytest.mark.asyncio
async def test_runner_with_kwargs_async() -> None:
    """Test async runner with keyword arguments."""
    runner = MockRunner()

    @coco.fn.as_async(runner=runner)
    async def async_greet(name: str, greeting: str = "Hello") -> str:
        return f"{greeting}, {name}!"

    result = await async_greet("World", greeting="Hi")
    assert result == "Hi, World!"
    assert runner.call_count == 1


# ============================================================================
# Runner with methods (no batching) tests
# ============================================================================


class RunnerProcessor:
    """Class with methods that use runner (no batching)."""

    def __init__(self, multiplier: int):
        self.multiplier = multiplier

    @coco.fn.as_async(runner=coco.GPU)
    def multiply_sync(self, x: int) -> int:
        """Sync method with runner."""
        return x * self.multiplier

    @coco.fn.as_async(runner=coco.GPU)
    async def multiply_async(self, x: int) -> int:
        """Async method with runner."""
        return x * self.multiplier


@pytest.mark.asyncio
async def test_runner_method_sync() -> None:
    """Test runner with sync method (no batching)."""
    proc = RunnerProcessor(3)

    result = await proc.multiply_sync(5)
    assert result == 15


@pytest.mark.asyncio
async def test_runner_method_async() -> None:
    """Test runner with async method (no batching)."""
    proc = RunnerProcessor(3)

    result = await proc.multiply_async(5)
    assert result == 15


@pytest.mark.asyncio
async def test_runner_method_concurrent() -> None:
    """Test concurrent calls to runner method (no batching)."""
    proc = RunnerProcessor(3)

    results = await asyncio.gather(
        proc.multiply_sync(1),
        proc.multiply_sync(2),
        proc.multiply_sync(3),
    )

    assert sorted(results) == [3, 6, 9]


# ============================================================================
# Memo with batching/runner tests
# ============================================================================


@pytest.mark.asyncio
async def test_memo_with_batching() -> None:
    """Test that memo=True works with batching (no warning, memo is supported)."""

    # This should not raise any warnings - memo is now supported with batching
    @coco.fn.as_async(batching=True, memo=True)
    def batched_with_memo(inputs: list[int]) -> list[int]:
        return [x * 2 for x in inputs]

    # Works outside of component context (memo just skipped)
    result = await batched_with_memo(5)
    assert result == 10


@pytest.mark.asyncio
async def test_memo_with_runner() -> None:
    """Test that memo=True works with runner (no warning, memo is supported)."""
    runner = MockRunner()

    # This should not raise any warnings - memo is now supported with runner
    @coco.fn.as_async(runner=runner, memo=True)
    def runner_with_memo(x: int) -> int:
        return x + 1

    # Works outside of component context (memo just skipped)
    result = await runner_with_memo(5)
    assert result == 6
    assert runner.call_count == 1


# ============================================================================
# GPU Runner tests (in-process by default, subprocess with COCOINDEX_RUN_GPU_IN_SUBPROCESS=1)
#
# The @coco.fn decorator with runner=coco.GPU works with normal syntax.
# In subprocess mode, functions and methods are pickled using __reduce__ which
# stores (module, qualname) and reconstructs via __wrapped__ on unpickle.
# ============================================================================


@pytest.fixture()
def _reset_gpu_runner() -> Iterator[None]:
    """Reset GPURunner's cached subprocess mode between tests."""
    yield
    coco.GPU._use_subprocess = None


# --- In-process mode (default) tests ---


@coco.fn.as_async(runner=coco.GPU)
def _gpu_add_one(x: int) -> int:
    """GPU runner test function."""
    return x + 1


@pytest.mark.asyncio
async def test_gpu_runner_basic() -> None:
    """Test basic GPU runner functionality (in-process by default)."""
    result = await _gpu_add_one(5)
    assert result == 6


@coco.fn.as_async(batching=True, runner=coco.GPU)
def _gpu_double_batch(inputs: list[int]) -> list[int]:
    """GPU runner + batching test function."""
    return [x * 2 for x in inputs]


@pytest.mark.asyncio
async def test_gpu_runner_with_batching() -> None:
    """Test GPU runner combined with batching."""
    result = await _gpu_double_batch(5)
    assert result == 10


@coco.fn.as_async(batching=True, max_batch_size=10, runner=coco.GPU)
def _gpu_double_batch_concurrent(inputs: list[int]) -> list[int]:
    """GPU runner + batching concurrent test function."""
    return [x * 2 for x in inputs]


@pytest.mark.asyncio
async def test_gpu_runner_with_batching_concurrent() -> None:
    """Test GPU runner + batching with concurrent calls."""
    results = await asyncio.gather(
        _gpu_double_batch_concurrent(1),
        _gpu_double_batch_concurrent(2),
        _gpu_double_batch_concurrent(3),
    )

    assert sorted(results) == [2, 4, 6]


class GPUBatchedProcessor:
    """Class with batched method that runs on GPU.

    Normal @decorator syntax works - pickling uses __reduce__ with (module, qualname).
    """

    def __init__(self, multiplier: int):
        self.multiplier = multiplier

    @coco.fn.as_async(batching=True, runner=coco.GPU)
    def multiply(self, inputs: list[int]) -> list[int]:
        """Batched method that multiplies inputs."""
        return [x * self.multiplier for x in inputs]


@pytest.mark.asyncio
async def test_gpu_runner_with_batching_method() -> None:
    """Test GPU runner + batching with a method (self parameter)."""
    proc = GPUBatchedProcessor(3)

    result = await proc.multiply(5)
    assert result == 15


@pytest.mark.asyncio
async def test_gpu_runner_with_batching_method_concurrent() -> None:
    """Test GPU runner + batching with method and concurrent calls."""
    proc = GPUBatchedProcessor(3)

    results = await asyncio.gather(
        proc.multiply(1),
        proc.multiply(2),
        proc.multiply(3),
    )

    assert sorted(results) == [3, 6, 9]


@pytest.mark.asyncio
async def test_gpu_runner_inprocess_serialization() -> None:
    """Test that in-process GPU runner serializes concurrent calls."""
    execution_order: list[int] = []

    @coco.fn.as_async(runner=coco.GPU)
    async def _track_execution(task_id: int) -> int:
        execution_order.append(task_id)
        await asyncio.sleep(0.01)
        return task_id

    results = await asyncio.gather(
        _track_execution(1),
        _track_execution(2),
        _track_execution(3),
    )
    assert sorted(results) == [1, 2, 3]
    # All 3 executed (order may vary due to batching queue, but all completed)
    assert sorted(execution_order) == [1, 2, 3]


# --- Subprocess mode tests (COCOINDEX_RUN_GPU_IN_SUBPROCESS=1) ---
# These use separate function definitions to avoid stale Rust batcher caches
# from in-process tests (batcher cache is per-function and holds event loop refs).


@coco.fn.as_async(runner=coco.GPU)
def _gpu_add_one_subprocess(x: int) -> int:
    """GPU runner subprocess test function."""
    return x + 1


@coco.fn.as_async(batching=True, runner=coco.GPU)
def _gpu_double_batch_subprocess(inputs: list[int]) -> list[int]:
    """GPU runner subprocess + batching test function."""
    return [x * 2 for x in inputs]


@coco.fn.as_async(batching=True, max_batch_size=10, runner=coco.GPU)
def _gpu_double_batch_concurrent_subprocess(inputs: list[int]) -> list[int]:
    """GPU runner subprocess + batching concurrent test function."""
    return [x * 2 for x in inputs]


class GPUBatchedProcessorSubprocess:
    """Class with batched method for subprocess GPU tests."""

    def __init__(self, multiplier: int):
        self.multiplier = multiplier

    @coco.fn.as_async(batching=True, runner=coco.GPU)
    def multiply(self, inputs: list[int]) -> list[int]:
        return [x * self.multiplier for x in inputs]


@pytest.mark.asyncio
async def test_gpu_runner_subprocess_basic(
    monkeypatch: pytest.MonkeyPatch, _reset_gpu_runner: None
) -> None:
    """Test GPU runner in subprocess mode."""
    monkeypatch.setenv("COCOINDEX_RUN_GPU_IN_SUBPROCESS", "1")
    coco.GPU._use_subprocess = None  # Force re-read

    result = await _gpu_add_one_subprocess(5)
    assert result == 6


@pytest.mark.asyncio
async def test_gpu_runner_subprocess_with_batching(
    monkeypatch: pytest.MonkeyPatch, _reset_gpu_runner: None
) -> None:
    """Test GPU runner subprocess mode with batching."""
    monkeypatch.setenv("COCOINDEX_RUN_GPU_IN_SUBPROCESS", "1")
    coco.GPU._use_subprocess = None

    result = await _gpu_double_batch_subprocess(5)
    assert result == 10


@pytest.mark.asyncio
async def test_gpu_runner_subprocess_with_batching_concurrent(
    monkeypatch: pytest.MonkeyPatch, _reset_gpu_runner: None
) -> None:
    """Test GPU runner subprocess mode with batching and concurrent calls."""
    monkeypatch.setenv("COCOINDEX_RUN_GPU_IN_SUBPROCESS", "1")
    coco.GPU._use_subprocess = None

    results = await asyncio.gather(
        _gpu_double_batch_concurrent_subprocess(1),
        _gpu_double_batch_concurrent_subprocess(2),
        _gpu_double_batch_concurrent_subprocess(3),
    )
    assert sorted(results) == [2, 4, 6]


@pytest.mark.asyncio
async def test_gpu_runner_subprocess_with_method(
    monkeypatch: pytest.MonkeyPatch, _reset_gpu_runner: None
) -> None:
    """Test GPU runner subprocess mode with method."""
    monkeypatch.setenv("COCOINDEX_RUN_GPU_IN_SUBPROCESS", "1")
    coco.GPU._use_subprocess = None

    proc = GPUBatchedProcessorSubprocess(3)
    result = await proc.multiply(5)
    assert result == 15


# --- Lazy env var reading test ---


@pytest.mark.asyncio
async def test_gpu_runner_lazy_env_var(
    monkeypatch: pytest.MonkeyPatch, _reset_gpu_runner: None
) -> None:
    """Test that env var is read lazily on first call, not at init time."""
    # Initially not set β€” defaults to in-process
    coco.GPU._use_subprocess = None
    assert coco.GPU._should_use_subprocess() is False

    # Set env var after init, reset cache
    monkeypatch.setenv("COCOINDEX_RUN_GPU_IN_SUBPROCESS", "1")
    coco.GPU._use_subprocess = None
    assert coco.GPU._should_use_subprocess() is True

    # Cached β€” changing env var without reset doesn't affect it
    monkeypatch.delenv("COCOINDEX_RUN_GPU_IN_SUBPROCESS")
    assert coco.GPU._should_use_subprocess() is True  # still cached


@coco.fn.as_async(batching=True)  # type: ignore[arg-type]
def batched_with_extra_arg(inputs: list[str], prefix: str) -> list[str]:
    return [f"{prefix}:{x}" for x in inputs]


@pytest.mark.asyncio
async def test_batching_extra_arg_grouping() -> None:
    r1: str
    r2: str
    r1, r2 = await asyncio.gather(
        batched_with_extra_arg("a", "X"),  # type: ignore[call-arg]
        batched_with_extra_arg("break", "X"),  # type: ignore[call-arg]
    )
    assert r1 == "X:a" and r2 == "X:break"


@pytest.mark.asyncio
async def test_batching_extra_arg_separates_batchers() -> None:
    r1: str
    r2: str
    r1, r2 = await asyncio.gather(
        batched_with_extra_arg("a", "X"),  # type: ignore[call-arg]
        batched_with_extra_arg("a", "Y"),  # type: ignore[call-arg]
    )
    assert r1 == "X:a" and r2 == "Y:a"


@coco.fn.as_async(batching=True)  # type: ignore[arg-type]
def batched_with_extra_kwarg(inputs: list[str], *, suffix: str) -> list[str]:
    return [f"{x}:{suffix}" for x in inputs]


@pytest.mark.asyncio
async def test_batching_extra_kwarg_grouping() -> None:
    """Test that calls with the same extra kwarg are batched together."""
    r1: str
    r2: str
    r1, r2 = await asyncio.gather(
        batched_with_extra_kwarg("a", suffix="!"),  # type: ignore[call-arg]
        batched_with_extra_kwarg("b", suffix="!"),  # type: ignore[call-arg]
    )
    assert r1 == "a:!" and r2 == "b:!"


@pytest.mark.asyncio
async def test_batching_extra_kwarg_separates_batchers() -> None:
    """Test that calls with different extra kwargs go to different batchers."""
    r1: str
    r2: str
    r1, r2 = await asyncio.gather(
        batched_with_extra_kwarg("a", suffix="!"),  # type: ignore[call-arg]
        batched_with_extra_kwarg("a", suffix="?"),  # type: ignore[call-arg]
    )
    assert r1 == "a:!" and r2 == "a:?"


class BatchedProcessorWithExtraArgs:
    def __init__(self, base: int) -> None:
        self.base = base

    @coco.fn.as_async(batching=True)  # type: ignore[arg-type]
    def process(self, inputs: list[int], multiplier: int, *, offset: int) -> list[int]:
        return [self.base + x * multiplier + offset for x in inputs]


@pytest.mark.asyncio
async def test_batching_method_extra_args_grouping() -> None:
    proc = BatchedProcessorWithExtraArgs(base=10)
    r1: int
    r2: int
    r1, r2 = await asyncio.gather(
        proc.process(1, 2, offset=5),  # type: ignore[call-arg]
        proc.process(3, 2, offset=5),  # type: ignore[call-arg]
    )
    assert r1 == 17 and r2 == 21


@pytest.mark.asyncio
async def test_batching_method_extra_args_separates_batchers() -> None:
    proc = BatchedProcessorWithExtraArgs(base=10)
    r1: int
    r2: int
    r1, r2 = await asyncio.gather(
        proc.process(1, 2, offset=5),  # type: ignore[call-arg]
        proc.process(1, 2, offset=10),  # type: ignore[call-arg]
    )
    assert r1 == 17 and r2 == 22


# ============================================================================
# Idle batchers are cleared (no stale-batcher / stale batch-key accumulation)
# ============================================================================


@coco.fn.as_async(batching=True)
async def _idle_double(inputs: list[int]) -> list[int]:
    await asyncio.sleep(0.01)
    return [x * 2 for x in inputs]


@pytest.mark.asyncio
async def test_batching_clears_idle_batcher() -> None:
    """A batcher is dropped once no call is in flight against it."""
    assert _idle_double._batchers == {}  # type: ignore[attr-defined]
    assert await _idle_double(5) == 10
    # The only call has drained -> no stale batcher left behind.
    assert _idle_double._batchers == {}  # type: ignore[attr-defined]


@pytest.mark.asyncio
async def test_batching_shares_batcher_while_in_flight() -> None:
    """Concurrent calls share a single batcher slot (refcounted by in-flight
    count); the slot is removed once they all drain."""
    tracker = TrackedBatcher()
    tracked_double = tracker.create_function()
    for v in [1, 2, 3]:
        tracker.create_event(v)

    task1 = asyncio.create_task(tracked_double(1))
    await wait_for_condition(lambda: len(tracker.batch_inputs) >= 1)
    task2 = asyncio.create_task(tracked_double(2))
    task3 = asyncio.create_task(tracked_double(3))

    # All three in-flight calls share one batcher slot, refcounted to 3.
    await wait_for_condition(
        lambda: (
            len(tracked_double._batchers) == 1
            and next(iter(tracked_double._batchers.values())).in_flight == 3
        )
    )

    tracker.input_events[1].set()
    for v in [2, 3]:
        tracker.input_events[v].set()
    await asyncio.gather(task1, task2, task3)

    # Drained -> slot removed.
    assert tracked_double._batchers == {}


class _SimpleBatchedAdder:
    def __init__(self, base: int) -> None:
        self.base = base

    @coco.fn.as_async(batching=True)  # type: ignore[arg-type]
    async def add(self, inputs: list[int]) -> list[int]:
        return [self.base + x for x in inputs]


@pytest.mark.asyncio
async def test_batching_method_clears_idle_batchers_per_instance() -> None:
    """Per-instance batchers don't accumulate across short-lived objects."""
    async_fn = _SimpleBatchedAdder.add  # the underlying AsyncFunction
    assert async_fn._batchers == {}  # type: ignore[attr-defined]
    for base in range(5):
        proc = _SimpleBatchedAdder(base)
        assert await proc.add(1) == base + 1  # type: ignore[call-arg]
    # Each object's batcher was cleared when idle; no per-instance-id leak.
    assert async_fn._batchers == {}  # type: ignore[attr-defined]


# ============================================================================
# RetryWithSmallerBatch: the engine splits the batch and retries the halves
# ============================================================================


class _BatchLimitError(Exception):
    """Stands in for a provider-side 'batch too large' rejection."""


@pytest.mark.asyncio
async def test_retry_with_smaller_batch_splits_until_success() -> None:
    """A batch rejected as too large is halved until every item succeeds."""
    batch_sizes: list[int] = []
    started = asyncio.Event()
    release = asyncio.Event()

    @coco.fn.as_async(batching=True)
    async def limited(inputs: list[int]) -> list[int]:
        batch_sizes.append(len(inputs))
        if len(batch_sizes) == 1:
            started.set()
            await release.wait()
        if len(inputs) > 2:
            raise coco.RetryWithSmallerBatch() from _BatchLimitError("too big")
        return [x * 2 for x in inputs]

    # First call runs inline and blocks, so the next four queue into one batch.
    task0 = asyncio.create_task(limited(0))
    await started.wait()
    tasks = [asyncio.create_task(limited(v)) for v in [1, 2, 3, 4]]
    await asyncio.sleep(0.05)  # let them enqueue behind the inline call
    release.set()

    results = await asyncio.gather(task0, *tasks)
    assert results == [0, 2, 4, 6, 8]

    # Inline [0], then the rejected batch of 4, then its two halves.
    assert batch_sizes[:2] == [1, 4]
    assert sorted(batch_sizes[2:]) == [2, 2]


@pytest.mark.asyncio
async def test_retry_with_smaller_batch_isolates_poison_item() -> None:
    """One bad input fails only its own caller; the rest of the batch succeeds."""
    started = asyncio.Event()
    release = asyncio.Event()
    call_count = 0

    @coco.fn.as_async(batching=True)
    async def embed(inputs: list[int]) -> list[int]:
        nonlocal call_count
        call_count += 1
        if call_count == 1:
            started.set()
            await release.wait()
        if any(x < 0 for x in inputs):
            if len(inputs) == 1:
                raise ValueError(f"bad input {inputs[0]}")
            raise coco.RetryWithSmallerBatch() from _BatchLimitError("rejected")
        return [x * 2 for x in inputs]

    task0 = asyncio.create_task(embed(1))
    await started.wait()
    tasks = [asyncio.create_task(embed(v)) for v in [2, 3, -7, 4]]
    await asyncio.sleep(0.05)
    release.set()

    results = await asyncio.gather(task0, *tasks, return_exceptions=True)
    assert results[:3] == [2, 4, 6]
    assert isinstance(results[3], ValueError)
    assert str(results[3]) == "bad input -7"
    assert results[4] == 8


@pytest.mark.asyncio
async def test_retry_with_smaller_batch_single_item_raises_cause() -> None:
    """At batch size 1 the wrapped original error surfaces, not the signal."""

    @coco.fn.as_async(batching=True)
    async def always_split(inputs: list[int]) -> list[int]:
        raise coco.RetryWithSmallerBatch() from ValueError("real error")

    with pytest.raises(ValueError, match="real error"):
        await always_split(1)


@pytest.mark.asyncio
async def test_retry_with_smaller_batch_single_item_without_cause() -> None:
    """Signal raised bare (no cause) at size 1 propagates as itself."""

    @coco.fn.as_async(batching=True)
    async def always_split(inputs: list[int]) -> list[int]:
        raise coco.RetryWithSmallerBatch()

    with pytest.raises(coco.RetryWithSmallerBatch):
        await always_split(1)


def test_retry_with_smaller_batch_sync_driver() -> None:
    """The sync split driver: same halving semantics, sequential halves."""
    from cocoindex._internal.batching import BatchItemFailure, wrap_batch_fn_sync

    batch_sizes: list[int] = []

    def body(inputs: list[int]) -> list[int]:
        batch_sizes.append(len(inputs))
        if len(inputs) > 1:
            raise coco.RetryWithSmallerBatch() from _BatchLimitError("too big")
        if inputs[0] < 0:
            raise ValueError(f"bad input {inputs[0]}")
        return [x * 2 for x in inputs]

    run = wrap_batch_fn_sync(body)
    outputs = run([1, 2, -3, 4])

    assert outputs[0] == 2
    assert outputs[1] == 4
    assert isinstance(outputs[2], BatchItemFailure)
    assert isinstance(outputs[2].error, ValueError)
    assert outputs[3] == 8
    # 4 -> (2, 2) -> four singles.
    assert sorted(batch_sizes) == [1, 1, 1, 1, 2, 2, 4]


def test_retry_with_smaller_batch_pickle_preserves_cause() -> None:
    """The signal carries its cause through pickling (subprocess runners drop
    ``__cause__`` and concurrent.futures then overwrites it with a
    remote-traceback marker β€” the restored cause must win over that)."""
    import pickle

    from cocoindex._internal.batching import split_cause

    try:
        raise coco.RetryWithSmallerBatch() from ValueError("original failure")
    except coco.RetryWithSmallerBatch as e:
        signal = e

    restored = pickle.loads(pickle.dumps(signal))
    # Simulate concurrent.futures clobbering __cause__ on the parent side.
    restored.__cause__ = RuntimeError("remote traceback marker")

    cause = split_cause(restored)
    assert isinstance(cause, ValueError)
    assert str(cause) == "original failure"


@coco.fn.as_async(batching=True, runner=coco.GPU)
def _rwsb_subprocess_fn(inputs: list[int]) -> list[int]:
    """Raises the split signal unconditionally β€” including at batch size 1."""
    raise coco.RetryWithSmallerBatch() from ValueError("original failure")


@pytest.mark.asyncio
async def test_gpu_runner_subprocess_retry_with_smaller_batch(
    monkeypatch: pytest.MonkeyPatch, _reset_gpu_runner: None
) -> None:
    """The signal raised at size 1 inside a real subprocess unwraps to the
    original error on the caller side β€” no batch-size check in the body."""
    monkeypatch.setenv("COCOINDEX_RUN_GPU_IN_SUBPROCESS", "1")
    coco.GPU._use_subprocess = None

    with pytest.raises(ValueError, match="original failure"):
        await _rwsb_subprocess_fn(5)


# Note: With always-async design, functions with batching/runner are always async.
# The underlying implementation can be sync - it gets wrapped appropriately.
# Both in-process and subprocess execution work for sync underlying functions.


# ============================================================================
# rate_limiter: batches take one token each before they run
# ============================================================================


def test_rate_limiter_requires_batching() -> None:
    limiter = RateLimiter(max_rows_per_second=10.0)

    with pytest.raises(ValueError, match="rate_limiter requires batching=True"):

        @coco.fn.as_async(rate_limiter=limiter)
        async def _unbatched(x: int) -> int:
            return x

    with pytest.raises(ValueError, match="rate_limiter"):

        @coco.fn(rate_limiter=limiter)  # type: ignore[call-overload, untyped-decorator]
        async def _plain(x: int) -> int:
            return x

    with pytest.raises(TypeError, match="rate_limiter must be a RateLimiter"):

        @coco.fn.as_async(batching=True, rate_limiter=3)  # type: ignore[call-overload, untyped-decorator]
        async def _bad(inputs: list[int]) -> list[int]:
            return inputs


@pytest.mark.asyncio
async def test_rate_limiter_paces_batches() -> None:
    """Twelve concurrent calls at four per batch need three tokens; at four
    tokens a second with no burst the second and third wait 250 ms each."""
    batch_sizes: list[int] = []
    limiter = RateLimiter(max_rows_per_second=4.0, burst_window_secs=0.0)

    @coco.fn.as_async(batching=True, max_batch_size=4, rate_limiter=limiter)
    async def paced_double(inputs: list[int]) -> list[int]:
        batch_sizes.append(len(inputs))
        return [x * 2 for x in inputs]

    started = asyncio.get_running_loop().time()
    results = await asyncio.gather(*(paced_double(v) for v in range(12)))
    elapsed = asyncio.get_running_loop().time() - started

    assert list(results) == [v * 2 for v in range(12)]
    assert sum(batch_sizes) == 12
    assert all(size <= 4 for size in batch_sizes)
    assert len(batch_sizes) >= 3
    # Two token intervals at least, whatever the loop's scheduling.
    assert elapsed >= 0.45


@pytest.mark.asyncio
async def test_rate_limiter_callable_receives_self() -> None:
    """A method's limiter lives on the instance: the callable form is resolved
    with the bound ``self``, once per batcher."""
    resolved: list[object] = []

    class Client:
        def __init__(self, limiter: RateLimiter | None) -> None:
            self.limiter = limiter

        def _pick_limiter(self) -> RateLimiter | None:
            resolved.append(self)
            return self.limiter

        @coco.fn.as_async(batching=True, rate_limiter=lambda self: self._pick_limiter())
        async def double(self, inputs: list[int]) -> list[int]:
            return [x * 2 for x in inputs]

    paced = Client(RateLimiter(max_rows_per_second=100.0))
    unpaced = Client(None)
    assert list(await asyncio.gather(paced.double(1), paced.double(2))) == [2, 4]
    assert await unpaced.double(3) == 6
    assert resolved == [paced, unpaced]