|
| 1 | +"""Example function exercising the dynamic_to_string callback. |
| 2 | +
|
| 3 | +``ProfilingDemoFunction`` demonstrates the recommended persistence |
| 4 | +pattern for diagnostics that should surface under ``EXPLAIN ANALYZE``: |
| 5 | +
|
| 6 | +1. ``process()`` keeps per-stream counters in user state (rows, |
| 7 | + batches, start time), and after every tick writes a serialized |
| 8 | + snapshot via ``params.storage.put(bytes)``. |
| 9 | +2. ``dynamic_to_string()`` constructs a ``BoundStorage`` for the |
| 10 | + given ``execution_id``, calls ``collect()`` to gather every |
| 11 | + worker's last snapshot, and sums them. |
| 12 | +
|
| 13 | +``BoundStorage`` defaults to the sqlite-backed shared storage (see |
| 14 | +CLAUDE.md → ``VGI_WORKER_SHARED_STORAGE``), so the pattern works across |
| 15 | +worker processes — both subprocess transport and HTTP transport with |
| 16 | +``max_workers > 1``. No in-memory class state is involved. |
| 17 | +""" |
| 18 | + |
| 19 | +from __future__ import annotations |
| 20 | + |
| 21 | +import struct |
| 22 | +import time |
| 23 | +from collections.abc import Mapping |
| 24 | +from dataclasses import dataclass |
| 25 | +from typing import Annotated, ClassVar |
| 26 | + |
| 27 | +import numpy as np |
| 28 | +import pyarrow as pa |
| 29 | +from vgi_rpc import ArrowSerializableDataclass |
| 30 | +from vgi_rpc.rpc import OutputCollector |
| 31 | + |
| 32 | +from vgi._test_fixtures.table._common import CountBatchArgs |
| 33 | +from vgi.arguments import Arg |
| 34 | +from vgi.function_storage import BoundStorage |
| 35 | +from vgi.metadata import FunctionExample |
| 36 | +from vgi.schema_utils import schema |
| 37 | +from vgi.table_function import ( |
| 38 | + BindParams, |
| 39 | + ProcessParams, |
| 40 | + TableCardinality, |
| 41 | + TableFunctionGenerator, |
| 42 | + bind_fixed_schema, |
| 43 | + init_single_worker, |
| 44 | +) |
| 45 | + |
| 46 | + |
| 47 | +@dataclass(frozen=True) |
| 48 | +class ProfilingDemoArgs(CountBatchArgs): |
| 49 | + """Arguments for ProfilingDemoFunction.""" |
| 50 | + |
| 51 | + increment: Annotated[int, Arg("increment", default=1, doc="Step between values", ge=1)] |
| 52 | + |
| 53 | + |
| 54 | +@dataclass(kw_only=True) |
| 55 | +class ProfilingState(ArrowSerializableDataclass): |
| 56 | + """Per-stream counters.""" |
| 57 | + |
| 58 | + remaining: int |
| 59 | + current_index: int = 0 |
| 60 | + rows_emitted: int = 0 |
| 61 | + batches_emitted: int = 0 |
| 62 | + started_at_ns: int = 0 |
| 63 | + |
| 64 | + |
| 65 | +# Serialized snapshot wire format: three little-endian uint64s |
| 66 | +# (rows, batches, elapsed_us). Compact; survives multi-worker collect(). |
| 67 | +_SNAPSHOT = struct.Struct("<QQQ") |
| 68 | + |
| 69 | + |
| 70 | +def _pack_snapshot(rows: int, batches: int, elapsed_us: int) -> bytes: |
| 71 | + return _SNAPSHOT.pack(rows, batches, elapsed_us) |
| 72 | + |
| 73 | + |
| 74 | +def _unpack_snapshot(data: bytes) -> tuple[int, int, int]: |
| 75 | + return _SNAPSHOT.unpack(data) |
| 76 | + |
| 77 | + |
| 78 | +@init_single_worker |
| 79 | +@bind_fixed_schema |
| 80 | +class ProfilingDemoFunction(TableFunctionGenerator[ProfilingDemoArgs, ProfilingState]): |
| 81 | + """Sequence generator that publishes per-execution metrics under EXPLAIN ANALYZE. |
| 82 | +
|
| 83 | + Output is identical to ``sequence(count, batch_size, increment)``. |
| 84 | + Additionally tracks ``rows_produced``, ``batches_emitted``, and |
| 85 | + ``elapsed_ms`` and surfaces them via ``dynamic_to_string``. |
| 86 | + """ |
| 87 | + |
| 88 | + FunctionArguments = ProfilingDemoArgs |
| 89 | + |
| 90 | + class Meta: |
| 91 | + """Metadata for ProfilingDemoFunction.""" |
| 92 | + |
| 93 | + name = "profiling_demo" |
| 94 | + description = "Sequence generator publishing diagnostics under EXPLAIN ANALYZE" |
| 95 | + categories = ["generator", "utility"] |
| 96 | + examples = [ |
| 97 | + FunctionExample( |
| 98 | + sql="EXPLAIN ANALYZE SELECT count(*) FROM profiling_demo(500)", |
| 99 | + description="Run with diagnostics surfaced as Extra Info", |
| 100 | + ), |
| 101 | + ] |
| 102 | + |
| 103 | + FIXED_SCHEMA: ClassVar[pa.Schema] = schema(n=pa.int64()) |
| 104 | + NUMPY_DTYPE: ClassVar[type[np.generic]] = np.int64 |
| 105 | + |
| 106 | + @classmethod |
| 107 | + def cardinality(cls, params: BindParams[ProfilingDemoArgs]) -> TableCardinality: |
| 108 | + count = params.args.count |
| 109 | + return TableCardinality(estimate=count, max=count) |
| 110 | + |
| 111 | + @classmethod |
| 112 | + def initial_state(cls, params: ProcessParams[ProfilingDemoArgs]) -> ProfilingState: |
| 113 | + return ProfilingState( |
| 114 | + remaining=params.args.count, |
| 115 | + started_at_ns=time.monotonic_ns(), |
| 116 | + ) |
| 117 | + |
| 118 | + @classmethod |
| 119 | + def process( |
| 120 | + cls, |
| 121 | + params: ProcessParams[ProfilingDemoArgs], |
| 122 | + state: ProfilingState, |
| 123 | + out: OutputCollector, |
| 124 | + ) -> None: |
| 125 | + if state.remaining <= 0: |
| 126 | + # Final write so dynamic_to_string sees the totals even after |
| 127 | + # the stream finishes. |
| 128 | + elapsed_us = (time.monotonic_ns() - state.started_at_ns) // 1000 |
| 129 | + params.storage.put(_pack_snapshot(state.rows_emitted, state.batches_emitted, elapsed_us)) |
| 130 | + out.finish() |
| 131 | + return |
| 132 | + batch_size = params.args.batch_size |
| 133 | + size = min(state.remaining, batch_size) |
| 134 | + increment = params.args.increment |
| 135 | + values = np.arange( |
| 136 | + state.current_index * increment, |
| 137 | + (state.current_index + size) * increment, |
| 138 | + increment, |
| 139 | + dtype=cls.NUMPY_DTYPE, |
| 140 | + ) |
| 141 | + out.emit(pa.RecordBatch.from_arrays([pa.array(values)], schema=params.output_schema)) |
| 142 | + state.current_index += size |
| 143 | + state.remaining -= size |
| 144 | + state.rows_emitted += size |
| 145 | + state.batches_emitted += 1 |
| 146 | + |
| 147 | + # Per-tick snapshot — overwrites this worker's slot. The dispatcher's |
| 148 | + # collect() on dynamic_to_string sums one snapshot per worker pid. |
| 149 | + elapsed_us = (time.monotonic_ns() - state.started_at_ns) // 1000 |
| 150 | + params.storage.put(_pack_snapshot(state.rows_emitted, state.batches_emitted, elapsed_us)) |
| 151 | + |
| 152 | + @classmethod |
| 153 | + def dynamic_to_string( |
| 154 | + cls, |
| 155 | + params: BindParams[ProfilingDemoArgs], |
| 156 | + execution_id: bytes, |
| 157 | + ) -> Mapping[str, str]: |
| 158 | + # BindParams doesn't carry a BoundStorage (no execution_id at bind |
| 159 | + # time). Construct one with the execution_id we received. |
| 160 | + storage = BoundStorage(cls.storage, execution_id) |
| 161 | + try: |
| 162 | + snapshots = storage.collect() |
| 163 | + except Exception: |
| 164 | + return {} |
| 165 | + if not snapshots: |
| 166 | + return {} |
| 167 | + rows = 0 |
| 168 | + batches = 0 |
| 169 | + elapsed_us = 0 |
| 170 | + for blob in snapshots: |
| 171 | + r, b, e = _unpack_snapshot(blob) |
| 172 | + rows += r |
| 173 | + batches += b |
| 174 | + elapsed_us = max(elapsed_us, e) |
| 175 | + return { |
| 176 | + "rows_produced": str(rows), |
| 177 | + "batches_emitted": str(batches), |
| 178 | + "elapsed_ms": f"{elapsed_us / 1000.0:.2f}", |
| 179 | + } |
0 commit comments