Metadata¶
base
¶
Abstract base class for metadata providers and in-memory metadata cache.
BaseMetadataProvider uses a Template Method pattern: public get_*
methods call protected _fetch_* abstract methods, wrapping them with an
optional in-memory cache layer (MetadataCache).
Concrete providers — FileProvider, DatabaseProvider, APIProvider —
implement only the _fetch_* and watermark methods.
BaseMetadataProvider
¶
BaseMetadataProvider(
*,
enable_cache: bool = True,
sql_base_path: str | Sequence[str] | None = None,
)
Bases: ABC
Abstract metadata provider with optional caching.
Subclasses implement the _fetch_* methods (I/O layer) and the
watermark methods. This base class wraps them with cache-aside logic:
check cache → miss → fetch → store → return.
sql_base_path is provider-owned configuration for SQL references in
the metadata. The provider retains the roots; Driver preparation reads
the selected file through its execution platform.
Context manager — with provider: ... calls :meth:close on exit.
is_initialized
property
¶
Whether this provider completed its startup contract.
sql_base_path
property
¶
Return the provider-declared SQL root or immutable root tuple.
clear_cache
¶
Clear the cache and invalidate readiness when caching is enabled.
configure_context
¶
configure_context(
context: MetadataProviderStartupContext,
) -> None
Apply optional runtime defaults before provider initialization.
get_connection_by_id
¶
get_connection_by_id(
connection_id: str,
) -> Optional[Connection]
Return a single connection by connection_id.
When the cache has been bulk-loaded and the id is not in it,
returns None without falling through to a remote fetch
(negative cache — bulk-load owns the full workspace).
get_connection_by_name
¶
get_connection_by_name(name: str) -> Optional[Connection]
Return a single connection by name.
Negative-cache behaviour mirrors :meth:get_connection_by_id.
get_connections
¶
get_connections(
*, active_only: bool = True
) -> List[Connection]
Return all connections, optionally filtered to active ones.
Cache-enabled providers serve this from the published snapshot; cache-disabled providers delegate to the provider fetcher.
get_dataflow_by_id
¶
get_dataflow_by_id(
dataflow_id: str, *, attach_schema_hints: bool = True
) -> Optional[DataFlow]
Return a single dataflow by dataflow_id.
When the cache has been bulk-loaded and the id is not in it,
returns None without falling through to a remote fetch
(negative cache).
get_dataflows
¶
get_dataflows(
*,
stage: Optional[Union[str, List[str]]] = None,
active_only: bool = True,
attach_schema_hints: bool = True,
) -> List[DataFlow]
Return dataflows, optionally filtered by stage.
stage may be a single name, a comma-separated string
("bronze2silver,silver2gold"), or a list of names.
When attach_schema_hints is True (default), schema hints
are fetched and attached to each dataflow's transform.schema_hints.
The first public read initializes the complete configured scope.
get_maintenance_dataflows
¶
get_maintenance_dataflows(
*,
connection: Optional[Union[str, List[str]]] = None,
active_only: bool = True,
attach_schema_hints: bool = False,
) -> List[DataFlow]
Return lakehouse-only dataflows for maintenance.
Only destinations whose format is in
CONNECTION_TYPE_FORMATS[ConnectionType.LAKEHOUSE.value]
(Delta Lake and Iceberg) are included.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
Optional[Union[str, List[str]]]
|
Filter by destination connection id or name. Accepts a single value, a comma-separated string, or a list. |
None
|
active_only
|
bool
|
Skip inactive dataflows. |
True
|
attach_schema_hints
|
bool
|
Attach schema hints from metadata. |
False
|
get_schema_hints
¶
get_schema_hints(
connection_id: str,
table_name: str,
schema_name: Optional[str] = None,
) -> List[SchemaHint]
Return schema hints for a given connection + table.
get_watermark
abstractmethod
¶
Return the raw serialised watermark string for dataflow_id, or None.
initialize
¶
Start the provider and validate its complete configured scope.
Construction only configures a provider. This method is the shared
startup boundary used by :class:DataCoolieDriver: it is idempotent,
serializes concurrent callers, and leaves the provider retryable when
a load fails. Cache-enabled providers retain the loaded snapshot;
cache-disabled providers still perform the full load for validation
but discard the result.
resolve_sql_base_path
¶
resolve_sql_base_path(
context: MetadataProviderStartupContext,
) -> str | tuple[str, ...] | None
Resolve provider roots against one Driver startup context.
The method only normalizes configuration. It never reads SQL or stores Driver fallback values on the provider.
update_watermark
abstractmethod
¶
update_watermark(
dataflow_id: str,
watermark_value: str,
*,
job_id: Optional[str] = None,
dataflow_run_id: Optional[str] = None,
) -> None
Persist a serialised watermark for dataflow_id.
validate_watermark_storage
¶
Validate provider-owned watermark configuration without I/O.
MetadataCache
¶
In-memory cache for metadata objects.
Stores connections (by id and name), dataflows (by id), and schema hints (by composite key). The cache is optional and purely additive — it never performs I/O.
get_all_connections
¶
get_all_connections() -> List[Connection]
Return a snapshot of all cached connections.
get_all_dataflows
¶
get_all_dataflows() -> List[DataFlow]
Return a snapshot of all cached dataflows.
get_all_schema_hints
¶
get_all_schema_hints() -> Dict[
SchemaHintKey, List[SchemaHint]
]
Return a shallow copy of the full schema-hint map in one lock acquire.
Callers that need to perform many hint lookups (e.g. attaching
hints to every dataflow in a batch) should use this function
instead of calling :meth:get_schema_hints in a loop — one
lock acquire vs N.
get_connection
¶
get_connection(connection_id: str) -> Optional[Connection]
Return a cached connection by connection_id, or None.
get_connection_by_name
¶
get_connection_by_name(name: str) -> Optional[Connection]
Return a cached connection by name, or None.
get_dataflow
¶
get_dataflow(dataflow_id: str) -> Optional[DataFlow]
Return a cached dataflow by dataflow_id, or None.
get_schema_hints
¶
get_schema_hints(
connection_id: str,
schema_name: Optional[str],
table_name: str,
) -> Optional[List[SchemaHint]]
Return cached schema hints for the composite key, or None.
publish_snapshot
¶
publish_snapshot(
connections: List[Connection],
dataflows: List[DataFlow],
schema_hints: Dict[SchemaHintKey, List[SchemaHint]],
) -> None
Publish one complete metadata snapshot atomically.
context
¶
Typed startup context shared with metadata providers.
The context carries defaults supplied by the runtime owner. Providers decide which values they need and retain their effective configuration themselves.
MetadataProviderStartupContext
dataclass
¶
MetadataProviderStartupContext(
platform: Optional["BasePlatform"] = None,
metadata_base_path: Optional[str] = None,
artifact_base_path: Optional[str] = None,
state_base_path: Optional[str] = None,
log_base_path: Optional[str] = None,
sql_base_path: str | Sequence[str] | None = None,
)
Optional runtime defaults offered during provider startup.
file_provider
¶
File-based metadata provider — reads connections, dataflows, and schema hints
from YAML, JSON, or Excel .xlsx configuration files.
FileProvider is the primary standalone / development metadata backend.
Watermark state is stored as JSON files on the platform's file system.
Supported formats¶
YAML / JSON — hierarchical, nested structure:
.. code-block:: yaml
connections:
- name: bronze_adls
connection_type: lakehouse
format: delta
configure:
base_path: abfss://bronze@storage/
use_schema_hint: true
- name: source_erp
connection_type: database
format: sql
database: ERP
configure:
host: erp-server.example.com
port: 1433
username: etl_reader
dataflows:
- name: orders_bronze_to_silver
stage: bronze2silver
source:
connection_name: bronze_adls
table: orders
watermark_columns: [modified_at]
destination:
connection_name: silver_lakehouse
table: dim_orders
load_type: merge_upsert
merge_keys: [order_id]
transform:
schema_hints:
- column_name: amount
data_type: DECIMAL
precision: 18
scale: 2
schema_hints:
- connection_name: bronze_adls
table_name: orders
hints:
- column_name: order_date
data_type: DATE
format: yyyy-MM-dd
Excel (.xlsx) — flat workbook with one or more of three supported sheets
(legacy .xls is not supported):
connections sheet — one row per connection:
Required: name, connection_type
Optional: connection_id, format, catalog, database, is_active
Nested configure via configure_* columns (e.g. configure_base_path, configure_host,
configure_use_schema_hint)
catalog and database are top-level columns (not configure_catalog or configure_database)
secrets_ref: JSON object mapping source identifiers to lists of
configure field names (e.g. {"env:": ["password", "api_key"]})
dataflows sheet — one row per dataflow:
Required: source_connection_name, source_table,
destination_connection_name, destination_table
Optional: dataflow_id, name, stage, description, group_number,
execution_order, processing_mode, is_active
configure: JSON column for the dataflow's own configure dict.
transform: JSON column for the full transform dict (individual transform_*
columns take precedence when both are present).
Source fields prefixed source_; destination fields prefixed destination_;
List columns (e.g. source_watermark_columns, destination_merge_keys,
destination_partition_columns) accept comma-separated values.
transform_select_columns and transform_drop_columns accept
comma-separated names. transform_schema_hints,
transform_deduplicate_columns, transform_latest_data_columns,
transform_additional_columns, transform_rename_columns,
transform_value_rules, transform_hash_columns, and
transform_masking_rules accept JSON strings.
schema_hints sheet — one row per hint (grouped internally by
connection_name or connection_id + table_name + optional
schema_name):
Columns: connection_name or connection_id, table_name,
schema_name (optional), column_name, data_type, precision,
scale, format
Separate files — each section may live in its own file instead of (or
in addition to) the primary config_path. Pass any combination of:
connections_path— file containing a{"connections": [...]}wrapper.schema_hints_path— file containing a{"schema_hints": [...]}wrapper.
Each override file can be YAML, JSON, or Excel in the same format as the corresponding section in the primary file. When a separate path is specified, its section replaces the same section from the primary file.
FileProvider
¶
FileProvider(
config_path: str | Sequence[str] | None = None,
platform: Optional[BasePlatform] = None,
*,
metadata_base_path: Optional[str] = None,
connections_path: Optional[str] = None,
schema_hints_path: Optional[str] = None,
watermark_base_path: Optional[str] = None,
sql_base_path: str | Sequence[str] | None = None,
enable_cache: bool = True,
)
Bases: BaseMetadataProvider
Metadata provider backed by YAML, JSON, or Excel configuration files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_path
|
str | Sequence[str] | None
|
Exact YAML, JSON, or Excel metadata file (or an ordered
sequence of files). May contain |
None
|
platform
|
Optional[BasePlatform]
|
Optional platform used for metadata and watermark file I/O.
It may be supplied later with :meth: |
None
|
metadata_base_path
|
Optional[str]
|
Directory containing metadata documents. All supported files below the directory are discovered recursively in deterministic path order; each file must use section wrappers. |
None
|
connections_path
|
Optional[str]
|
Optional separate file that provides the
|
None
|
schema_hints_path
|
Optional[str]
|
Optional separate file that provides the
|
None
|
watermark_base_path
|
Optional[str]
|
Optional root directory for watermark files. When omitted, a Driver may bind a runtime state/log-derived path; standalone metadata access remains valid until a watermark operation is requested. |
None
|
sql_base_path
|
str | Sequence[str] | None
|
One SQL root or a sequence of roots associated with metadata query references. Driver preparation reads the files. |
None
|
enable_cache
|
bool
|
Enable the in-memory cache. |
True
|
artifact_base_path
property
¶
Return the artifact root offered by the runtime, if any.
metadata_base_path
property
¶
Return the configured metadata directory, when artifact mode is used.
platform
property
¶
platform: Optional[BasePlatform]
Return the platform bound for file reads and watermark I/O.
watermark_base_path
property
¶
Return the effective file watermark base, if one is bound.
bind_platform
¶
bind_platform(platform: BasePlatform) -> BasePlatform
Bind a platform dependency without performing I/O.
A provider owns no platform lifecycle. Binding the exact same instance is idempotent; replacing an already-bound instance is rejected because platform instances can carry different storage roots or credentials even when their types match.
clear_cache
¶
Clear the shared cache and rebuild parsed models from raw metadata.
File-backed providers retain the normalized document snapshot so a
cache clear does not reread the platform. Parsed model memoization is
discarded here as well; callers cannot accidentally persist mutations
made to a previously returned DataFlow or Connection object.
get_watermark
¶
Return the raw watermark JSON string for dataflow_id, or None.
update_watermark
¶
update_watermark(
dataflow_id: str,
watermark_value: str,
*,
job_id: Optional[str] = None,
dataflow_run_id: Optional[str] = None,
) -> None
Write the serialised watermark JSON to a file.
validate_watermark_storage
¶
Validate that runtime watermark operations have a resolved root.
This is intentionally a side-effect-free check used by the Driver's
preparation phase. The lower-level watermark methods retain their
WatermarkError contract for standalone callers.
database_provider
¶
Database-backed metadata provider — SQLAlchemy 2.0.
DatabaseProvider reads connections, dataflows, schema hints and
watermarks from a relational database using SQLAlchemy 2.0 ORM sessions.
The database schema follows the dc_framework_* table convention
described in the architecture document (03-metadata-schema-design).
All queries are workspace-scoped and honour soft-delete
(deleted_at IS NULL).
DatabaseProvider
¶
DatabaseProvider(
*,
connection_string: Optional[str] = None,
workspace_id: str,
engine: Optional[Engine] = None,
enable_cache: bool = True,
pool_size: int = 10,
max_overflow: int = 20,
pool_pre_ping: bool = True,
pool_timeout: int = 30,
pool_recycle: int = 1800,
warm_up_retries: int = 1,
warm_up_delay: float = 15.0,
sql_base_path: str | Sequence[str] | None = None,
)
Bases: BaseMetadataProvider
Metadata provider backed by a relational database (SQLAlchemy 2.0).
Supports any SQLAlchemy-compatible backend (PostgreSQL, SQLite, SQL Server, MySQL, etc.).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection_string
|
Optional[str]
|
SQLAlchemy database URL. |
None
|
workspace_id
|
str
|
Workspace scope for all queries. |
required |
engine
|
Optional[Engine]
|
Optional pre-built |
None
|
enable_cache
|
bool
|
Enable the in-memory metadata cache. |
True
|
pool_size
|
int
|
Number of persistent connections kept in the pool. |
10
|
max_overflow
|
int
|
Extra connections allowed beyond pool_size under
load. Combined with pool_size this caps total concurrent
connections at |
20
|
pool_pre_ping
|
bool
|
When |
True
|
warm_up_retries
|
int
|
Number of extra connection attempts on the very first
session open. Defaults to |
1
|
warm_up_delay
|
float
|
Seconds to wait between warm-up retry attempts. |
15.0
|
sql_base_path
|
str | Sequence[str] | None
|
One SQL root or a sequence of roots associated with metadata query references. Driver preparation reads the files. |
None
|
The provider records connection settings in __init__. An owned
SQLAlchemy engine is created at :meth:initialize (or first direct I/O),
so construction performs no metadata or business-database I/O.
get_watermark
¶
Return the raw serialised watermark string for dataflow_id, or None.
update_watermark
¶
update_watermark(
dataflow_id: str,
watermark_value: str,
*,
job_id: Optional[str] = None,
dataflow_run_id: Optional[str] = None,
) -> None
Upsert a watermark with atomic previous_value rotation.
Strategy (avoids SELECT … FOR UPDATE gap locks which cause
deadlocks on MySQL InnoDB under parallel load):
- Issue a single
UPDATEthat rotatesprevious_valuefrom the current value in one statement (SQL evaluates all RHS expressions from pre-update values). - If
rowcount == 0, the row does not yet exist →INSERT. - If the insert races with another worker and raises
:class:
IntegrityError, rollback and re-run theUPDATE.
Transient MySQL deadlocks / lock-wait timeouts (OperationalError)
are retried up to _WATERMARK_MAX_RETRIES times.
api_provider
¶
REST API metadata provider — httpx.
APIProvider fetches connections, dataflows, schema hints and watermarks
from a remote metadata API via HTTP.
Authentication is done via an X-API-Key header. The client handles
automatic pagination, retry on transient errors (429 / 5xx), and maps
all HTTP failures to MetadataError or WatermarkError.
APIProvider
¶
APIProvider(
*,
base_url: str,
api_key: str,
workspace_id: str,
enable_cache: bool = True,
timeout: float = 30.0,
max_retries: int = 3,
retry_backoff: float = 1.0,
page_size: int = 200,
max_workers: int = 8,
sql_base_path: str | Sequence[str] | None = None,
)
Bases: BaseMetadataProvider
Metadata provider backed by a remote REST API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_url
|
str
|
Root URL of the metadata API, including any path prefix
(e.g. |
required |
api_key
|
str
|
Value for the |
required |
workspace_id
|
str
|
Workspace scope for all requests. |
required |
enable_cache
|
bool
|
Enable the in-memory metadata cache. |
True
|
timeout
|
float
|
Request timeout in seconds (default |
30.0
|
max_retries
|
int
|
Number of retries on transient failures (default |
3
|
retry_backoff
|
float
|
Base backoff in seconds for exponential retry (default |
1.0
|
sql_base_path
|
str | Sequence[str] | None
|
One SQL root or a sequence of roots associated with metadata query references. Driver preparation reads the files. |
None
|
The HTTP transport is created at :meth:initialize (or first direct
request), not during construction.
get_watermark
¶
Return the raw serialised watermark string for dataflow_id, or None.
The API may return current_value as a JSON string or as an already-parsed
dict. Either way, this method normalises the result to a JSON string so that
WatermarkManager can deserialize it uniformly.
update_watermark
¶
update_watermark(
dataflow_id: str,
watermark_value: str,
*,
job_id: Optional[str] = None,
dataflow_run_id: Optional[str] = None,
) -> None
Update the watermark via the API.
Query references¶
classify_query(...) classifies a declared Source.query by string shape and does not probe
storage. Blank values, comments, and ordinary SQL are inline queries. A relative .sql value is
the shorthand for a file under the configured SQL base path; artifact:/... is an explicit artifact
reference. Absolute paths, URI-shaped paths, and query or fragment suffixes are rejected.
query
¶
Pure classification of inline and file-backed SQL metadata.
QueryReference
dataclass
¶
QueryReference(
declared: str,
kind: Literal["inline", "file"],
relative_path: Optional[str] = None,
scheme: Optional[
Literal["shorthand", "artifact"]
] = None,
)
Classification result for a declared query value.
classify_query
¶
classify_query(query: Optional[str]) -> QueryReference
Classify query using string shape only; never probe storage.
Metadata provider extension hooks¶
Metadata provider subclasses implement the selected protected fetch hooks below. The public lookup methods normalize inputs and coordinate caching before calling these hooks; provider implementations own only the underlying store access.
_fetch_connections
abstractmethod
¶
_fetch_connections(
*, active_only: bool = True
) -> List[Connection]
Fetch all connections from the underlying store.
_fetch_connection_by_id
abstractmethod
¶
_fetch_connection_by_id(
connection_id: str,
) -> Optional[Connection]
Fetch a single connection by ID.
_fetch_connection_by_name
abstractmethod
¶
_fetch_connection_by_name(
name: str,
) -> Optional[Connection]
Fetch a single connection by name.
_fetch_dataflows
abstractmethod
¶
_fetch_dataflows(
*,
stages: Optional[List[str]] = None,
active_only: bool = True,
) -> List[DataFlow]
Fetch dataflows from the underlying store.
stages is already normalised to a list (or None) by
:meth:get_dataflows via :meth:_normalise_stages.
_fetch_dataflow_by_id
abstractmethod
¶
_fetch_dataflow_by_id(
dataflow_id: str,
) -> Optional[DataFlow]
Fetch a single dataflow by ID.
_fetch_schema_hints
abstractmethod
¶
_fetch_schema_hints(
connection_id: str,
table_name: str,
schema_name: Optional[str] = None,
) -> List[SchemaHint]
Fetch schema hints for a connection + table.
Providers may also override these lifecycle and bulk-loading hooks. The base implementation validates the complete scope and publishes one cache snapshot; overrides must preserve that lifecycle boundary and release only resources the provider created.
_bulk_load
¶
_bulk_load() -> Tuple[
List[Connection],
List[DataFlow],
Dict[Tuple[str, Optional[str], str], List[SchemaHint]],
]
Default bulk-load: serial calls to the per-resource fetchers.
Always loads the full (active + inactive) set — callers filter
downstream. Subclasses (APIProvider, DatabaseProvider,
FileProvider) override this with an optimised implementation
(e.g. concurrent paginated GETs or a single IN (...) SELECT).
_bulk_fetch_schema_hints
¶
_bulk_fetch_schema_hints(
*,
connections: List[Connection],
dataflows: List[DataFlow],
) -> Dict[Tuple[str, Optional[str], str], List[SchemaHint]]
Default fallback: walk dataflows and fetch hints per-(conn, table).
Used by the base implementation of :meth:_bulk_load when a
subclass does not override it. Most concrete providers should
override this with a bulk query.
_initialize_metadata
¶
Prepare provider-local metadata state before the bulk load.
Concrete providers may override this hook to resolve a deferred
metadata location (for example a FileProvider artifact directory).
The hook must not publish a ready snapshot; :meth:initialize
publishes readiness only after the complete scope has loaded.
_cleanup_failed_initialization
¶
Best-effort hook used after a failed startup attempt.
_close_resources
¶
Release provider-owned resources under the lifecycle lock.
Metadata cache publication¶
MetadataCache is published as a complete snapshot. Use
publish_snapshot(...), the read-only getters, and clear(); the former
partial set_connection*, set_dataflow*, and set_schema_hints* mutation
methods have been removed. Code that owns metadata loading should publish one
validated snapshot rather than update individual cache sections.