vgi.metadata
Module overview
Function metadata for introspection, documentation, and DuckDB registration.
This module provides declarative metadata classes that enable functions to describe themselves. Metadata is used for:
- Documentation generation
- Worker registration (serialized to Arrow for IPC)
- DuckDB function catalog integration
- Tooling and discovery
DESIGN
Users define a nested Meta class with attributes. No inheritance required:
The system automatically:
- Resolves metadata from the class hierarchy (inheritance works)
- Extracts parameter info from
Argdescriptors - Infers function name from class name if not specified
- Uses docstring as description fallback
ARROW SERIALIZATION
For worker registration, metadata can be serialized to Arrow:
from vgi.metadata import functions_to_arrow, arrow_to_functions
# Worker sends available functions to clientbatch = functions_to_arrow([MyFunction, OtherFunction])
# Client receives and deserializesfunction_infos = arrow_to_functions(batch)function arrow_to_functions
Section titled âfunction arrow_to_functionsâarrow_to_functions(batch: pa.RecordBatch) -> list[ResolvedMetadata]
Deserialize Arrow RecordBatch to list of ResolvedMetadata.
function arrow_to_metadata
Section titled âfunction arrow_to_metadataâarrow_to_metadata(batch: pa.RecordBatch) -> ResolvedMetadata
Deserialize Arrow RecordBatch to ResolvedMetadata.
class CatalogFunctionType
Section titled âclass CatalogFunctionTypeâBases: Enum
Description
Type of function for DuckDB registration.
Attributes
attribute AGGREGATE
Section titled âattribute AGGREGATEâAggregate function: many inputs â one output.
attribute TABLE
Section titled âattribute TABLEâTable function: returns a table (streaming producer or streaming exchange).
attribute TABLE_BUFFERING
Section titled âattribute TABLE_BUFFERINGâBuffered table function: Sink+Source PhysicalOperator that sees all
input before producing output. Dispatched to the custom
PhysicalVgiTableBufferingFunction operator instead of the streaming
in_out_function registration. The class hierarchy is the dispatch
key â set automatically for TableBufferingFunction subclasses.
class DistinctDependence
Section titled âclass DistinctDependenceâBases: Enum
Description
Aggregate DISTINCT modifier sensitivity.
Maps to DuckDBâs AggregateDistinctDependent enum.
Attributes
attribute DISTINCT_DEPENDENT
Section titled âattribute DISTINCT_DEPENDENTâDISTINCT changes the result (e.g., COUNT DISTINCT).
attribute NOT_DISTINCT_DEPENDENT
Section titled âattribute NOT_DISTINCT_DEPENDENTâDISTINCT has no effect (e.g., MAX, MIN).
function extract_parameters
Section titled âfunction extract_parametersâextract_parameters(
*,
validate_table_input: bool = True,
) -> list[ParameterInfo]
Extract parameter information from Arg descriptors on a class.
Walks the class and its bases to find all Arg descriptors and converts
them to ParameterInfo objects. Also handles the new Param/ConstParam API
for ScalarFunction subclasses.
class FunctionExample
Section titled âclass FunctionExampleâDescription
An example usage of a function.
Attributes
attribute expected_output
Section titled âattribute expected_outputâstr | None
Optional expected result description.
Methods
method to_dict
Section titled âmethod to_dictâto_dict() -> dict[str, str | None]Convert to dictionary for serialization.
method from_dict
Section titled âmethod from_dictâfrom_dict(d: dict[str, Any]) -> FunctionExampleCreate from dictionary.
function functions_to_arrow
Section titled âfunction functions_to_arrowâfunctions_to_arrow(function_classes: Sequence[type]) -> pa.RecordBatch
Serialize multiple function classes to Arrow RecordBatch.
Convenience function that resolves metadata for each class, then serializes.
For pre-resolved metadata, use metadatas_to_arrow() directly.
class FunctionStability
Section titled âclass FunctionStabilityâBases: Enum
Description
Function output stability classification.
Maps to DuckDBâs FunctionStability enum.
Attributes
attribute CONSISTENT
Section titled âattribute CONSISTENTâSame input always produces same output (deterministic).
attribute VOLATILE
Section titled âattribute VOLATILEâOutput may change per row even with same input (e.g., random()).
attribute CONSISTENT_WITHIN_QUERY
Section titled âattribute CONSISTENT_WITHIN_QUERYâSame within a query, but may vary across queries (e.g., now()).
class FunctionTypeError
Section titled âclass FunctionTypeErrorâBases: TypeError
Description
Raised when a functionâs type cannot be determined from its class hierarchy.
function metadata_to_arrow
Section titled âfunction metadata_to_arrowâmetadata_to_arrow(metadata: ResolvedMetadata) -> pa.RecordBatch
Serialize a single ResolvedMetadata to Arrow RecordBatch.
class MetadataMixin
Section titled âclass MetadataMixinâDescription
Mixin that provides metadata access for function classes.
Add this to the base Function class to enable metadata resolution.
Methods
method get_metadata
Section titled âmethod get_metadataâget_metadata() -> ResolvedMetadataGet the resolved metadata for this function class.
method describe
Section titled âmethod describeâdescribe() -> dict[str, Any]Get metadata as a dictionary (for JSON serialization).
function metadatas_to_arrow
Section titled âfunction metadatas_to_arrowâmetadatas_to_arrow(
metadatas: Sequence[ResolvedMetadata],
) -> pa.RecordBatch
Serialize multiple ResolvedMetadata objects to Arrow RecordBatch.
class NullHandling
Section titled âclass NullHandlingâBases: Enum
Description
NULL input handling behavior.
Maps to DuckDBâs FunctionNullHandling enum.
Attributes
attribute DEFAULT
Section titled âattribute DEFAULTâNULL in â NULL out (standard SQL behavior).
attribute SPECIAL
Section titled âattribute SPECIALâFunction handles NULLs specially (e.g., COALESCE, IFNULL).
class OrderDependence
Section titled âclass OrderDependenceâBases: Enum
Description
Aggregate order sensitivity.
Maps to DuckDBâs AggregateOrderDependent enum.
Attributes
attribute ORDER_DEPENDENT
Section titled âattribute ORDER_DEPENDENTâResult changes based on row order (e.g., FIRST, LAST, LISTAGG).
attribute NOT_ORDER_DEPENDENT
Section titled âattribute NOT_ORDER_DEPENDENTâResult is the same regardless of order (e.g., SUM, COUNT).
class OrderPreservation
Section titled âclass OrderPreservationâBases: Enum
Description
Row order preservation behavior.
Maps to DuckDBâs OrderPreservationType enum:
PRESERVES_ORDERâOrderPreservationType::INSERTION_ORDER(DuckDB default â operator maintains child operator order).NO_ORDER_GUARANTEEâOrderPreservationType::NO_ORDER(operator may freely reorder its input/output).FIXED_ORDERâOrderPreservationType::FIXED_ORDER(operator outputs rows in a fixed, mandatory order â DuckDB serializes the pipeline so a single worker produces all rows).
Attributes
attribute PRESERVES_ORDER
Section titled âattribute PRESERVES_ORDERâOutput rows are in same order as input rows (DuckDB INSERTION_ORDER).
attribute NO_ORDER_GUARANTEE
Section titled âattribute NO_ORDER_GUARANTEEâOutput order is undefined; may be reordered (DuckDB NO_ORDER).
attribute FIXED_ORDER
Section titled âattribute FIXED_ORDERâOutput is in a fixed mandatory order; DuckDB serializes the pipeline (single worker) to preserve it (DuckDB FIXED_ORDER).
class ParameterInfo
Section titled âclass ParameterInfoâDescription
Metadata about a function parameter.
Automatically extracted from Arg descriptors.
Attributes
attribute position
Section titled âattribute positionâint | str
Positional index (int) or named key (str).
attribute type_name
Section titled âattribute type_nameâstr | None
Type name as string (e.g., âintâ, âstrâ, TableInput).
attribute constraints
Section titled âattribute constraintsâdict[str, Any]
Validation constraints as dict.
attribute is_table_input
Section titled âattribute is_table_inputâbool
True if this is the table input parameter.
attribute is_varargs
Section titled âattribute is_varargsâbool
True if this accepts multiple trailing values.
attribute is_const
Section titled âattribute is_constâbool
True if this is a constant parameter (ConstParam).
Methods
method to_dict
Section titled âmethod to_dictâto_dict() -> dict[str, str | int | bool | None]Convert to dictionary for serialization.
method from_dict
Section titled âmethod from_dictâfrom_dict(d: dict[str, Any]) -> ParameterInfoCreate from dictionary.
class PartitionKind
Section titled âclass PartitionKindâBases: Enum
Description
Partition shape declared by a table function.
Declared over its vgi.partition_column-annotated bind-schema fields.
Mirrors DuckDBâs TablePartitionInfo at
duckdb/src/include/duckdb/function/partition_stats.hpp:20.
The C++ extension returns this from TableFunction::get_partition_info;
DuckDBâs planner currently consumes only SINGLE_VALUE_PARTITIONS
(to plan PhysicalPartitionedAggregate over PhysicalHashAggregate;
see plan_aggregate.cpp:109). The other values are declarable
so the protocol is future-proof; today they fall back to
HASH_GROUP_BY.
Only set this to a non-default value when at least one field in
the bind schema is annotated with
{b"vgi.partition_column": b"true"} (use
:func:vgi.schema_utils.partition_field to construct such fields).
The reverse is also required â annotated fields without a
matching partition_kind raise at worker startup.
Attributes
attribute NOT_PARTITIONED
Section titled âattribute NOT_PARTITIONEDâFunction does not declare partitioning over the annotated columns (default; same effect as leaving fields un-annotated).
attribute SINGLE_VALUE_PARTITIONS
Section titled âattribute SINGLE_VALUE_PARTITIONSâEach emitted chunk has exactly one distinct value per partition
column. Unlocks PhysicalPartitionedAggregate for GROUP BY
over those columns.
attribute OVERLAPPING_PARTITIONS
Section titled âattribute OVERLAPPING_PARTITIONSâPartitions overlap only at boundaries (bounds = [1,2] [2,3] [3,4]).
Wire-level declarable; DuckDB has no consumer today.
attribute DISJOINT_PARTITIONS
Section titled âattribute DISJOINT_PARTITIONSâPartitions are pairwise disjoint (bounds = [1,2] [3,4] [5,6]).
Wire-level declarable; DuckDB has no consumer today.
function resolve_metadata
Section titled âfunction resolve_metadataâresolve_metadata() -> ResolvedMetadata
Resolve metadata for a function class.
Results are cached since class metadata doesnât change at runtime.
This function:
- Walks the class hierarchy to find and merge
Metaclasses - Extracts parameter info from
Argdescriptors - Infers function name from class name if not specified
- Uses docstring as description fallback
class ResolvedMetadata
Section titled âclass ResolvedMetadataâDescription
Fully resolved metadata for a function.
This is the result of resolving a Meta class hierarchy and extracting
parameter information from Arg descriptors.
Attributes
attribute class_name
Section titled âattribute class_nameâstr
The Python class name of the function.
attribute function_type
Section titled âattribute function_typeâThe CatalogFunctionType (scalar, table, aggregate,
or table-buffering).
attribute description
Section titled âattribute descriptionâstr
Human-readable description of the function.
attribute examples
Section titled âattribute examplesâlist[FunctionExample]
SQL usage examples for the function.
attribute categories
Section titled âattribute categoriesâlist[str]
Classification/category labels.
attribute parameters
Section titled âattribute parametersâlist[ParameterInfo]
Resolved per-argument information from the Arg
descriptors.
attribute stability
Section titled âattribute stabilityâScalar evaluation stability (CONSISTENT, VOLATILE, âŚ).
attribute null_handling
Section titled âattribute null_handlingâWhether NULL inputs are passed through or handled.
attribute required_settings
Section titled âattribute required_settingsâlist[str]
DuckDB settings the function needs at runtime.
attribute required_secrets
Section titled âattribute required_secretsâlist[SecretLookupEntry]
Secrets the function needs (each entry carries secret_type, optional secret_name, optional scope).
attribute projection_pushdown
Section titled âattribute projection_pushdownâbool
Whether the table function accepts projection pushdown.
attribute filter_pushdown
Section titled âattribute filter_pushdownâbool
Whether the table function accepts filter pushdown.
attribute sampling_pushdown
Section titled âattribute sampling_pushdownâbool
Whether the table function accepts TABLESAMPLE pushdown.
attribute late_materialization
Section titled âattribute late_materializationâbool
When True, the table function participates in DuckDBâs late-materialization optimizer (TOP_N/LIMIT/SAMPLE over the scan is rewritten into a SEMI join on the rowid virtual column). Requires a unique, deterministic, snapshot-stable rowid column plus projection and filter pushdown.
attribute supported_expression_filters
Section titled âattribute supported_expression_filtersâlist[str]
Names of expression-filter classes the function can accept pushed down.
attribute preserves_order
Section titled âattribute preserves_orderâWhether the function preserves input row order.
attribute max_workers
Section titled âattribute max_workersâint | None
Maximum parallel workers, or None for unbounded.
attribute supports_batch_index
Section titled âattribute supports_batch_indexâbool
Whether the function opts into per-batch
vgi_batch_index tagging for ordered parallel output.
attribute partition_kind
Section titled âattribute partition_kindâPartition shape the function declares over its partition-column bind fields.
attribute order_dependent
Section titled âattribute order_dependentâWhether the aggregate result depends on input order.
attribute distinct_dependent
Section titled âattribute distinct_dependentâWhether the aggregate result depends on DISTINCT.
attribute supports_window
Section titled âattribute supports_windowâbool
Whether the aggregate implements the window() callback.
attribute streaming_partitioned
Section titled âattribute streaming_partitionedâbool
Whether the aggregate opts into the streaming-partitioned protocol.
attribute has_finalize
Section titled âattribute has_finalizeâbool
True if the function has a meaningful finalize phase
(override of finalize()/finish()); the C++ extension uses this to
decide whether to register in_out_function_final.
attribute source_order_dependent
Section titled âattribute source_order_dependentâbool
Only meaningful for TABLE_BUFFERING â when
True the source phase is single-threaded and finalize_state_ids
drain in combine-returned order.
attribute sink_order_dependent
Section titled âattribute sink_order_dependentâbool
Only meaningful for TABLE_BUFFERING â when True
the sink phase runs single-threaded, so every process() call arrives
in source order. Mutually exclusive with
requires_input_batch_index.
attribute requires_input_batch_index
Section titled âattribute requires_input_batch_indexâbool
Only meaningful for TABLE_BUFFERING â
when True the C++ Sink declares RequiredPartitionInfo()= BatchIndex() so each process() call carries a globally-unique
monotonic batch_index for reconstructing source order under parallel
ingest. Mutually exclusive with sink_order_dependent.
attribute input_from_args
Section titled âattribute input_from_argsâbool
True for a blended RowTransformFunction â its
positional args ARE its per-row input columns, so one registration
serves the literal / column / LATERAL call shapes. Detected from
RowTransformFunction subclassing.
Methods
method to_dict
Section titled âmethod to_dictâto_dict() -> dict[str, Any]Convert to dictionary for JSON serialization.
method from_dict
Section titled âmethod from_dictâfrom_dict(d: dict[str, Any]) -> ResolvedMetadataCreate from dictionary.
class TableInputValidationError
Section titled âclass TableInputValidationErrorâBases: ValueError
Description
Raised when TableInput parameter validation fails.
class VarargsValidationError
Section titled âclass VarargsValidationErrorâBases: ValueError
Description
Raised when varargs parameter validation fails.