Skip to content

Storage — geocatalog.storage

Save, share and reopen catalogs: the schema-versioned GeoParquet format, streaming writes, STAC export, and the provenance-recording CatalogBundle.

GeoParquet round-trip

geocatalog.storage.to_geoparquet(catalog, out_path, *, schema_version=SCHEMA_VERSION_CURRENT, write_covering_bbox=True, partition_by=None)

Persist catalog as a GeoParquet file on disk.

The result is a single Parquet file readable by any GeoParquet-aware tool (DuckDB, GDAL, pandas, geopandas) — not a pickle, so it survives version bumps and crosses Python / language boundaries. DuckDBGeoCatalog reads the same artifact, so this is the canonical interchange format for both backends.

Two columns are added on write and stripped on load:

  • _backend: round-trips the catalog kind so from_geoparquet restores the right loader dispatch.
  • _schema_version: reserved for forward-compat (§10.4 of the design plan); bump on first substantive schema change.

The row-level pd.IntervalIndex is unpacked into start_time / end_time columns (Parquet has no native IntervalIndex type); from_geoparquet rebuilds the index from those columns.

Parameters:

Name Type Description Default
catalog InMemoryGeoCatalog

An InMemoryGeoCatalog to serialise. The catalog's gdf.crs is written into the GeoParquet metadata.

required
out_path str | Path

Destination path. The .parquet extension is conventional. Any parent directory must exist. The file is written to a hidden sibling and renamed into place, so a failed write never leaves a partial file or clobbers an existing one.

required
schema_version int

Value written to the reserved _schema_version column. Defaults to SCHEMA_VERSION_CURRENT (today: 1).

SCHEMA_VERSION_CURRENT
write_covering_bbox bool

Emit the per-row bbox covering struct that GeoParquet 1.1 readers (DuckDB, geopandas ≥0.14) use for predicate pushdown. Default True; turn off only if a downstream consumer chokes on 1.1.

True
partition_by tuple[str, ...] | None

Optional Hive partition columns for directory output. Built-in "year", "month", and "day" are derived from start_time. Rows are streamed via gdf.itertuples (much faster than iterrows on large catalogs) and routed through write_partitioned_rows; an existing directory keeps every entry the writer does not own (see write_partitioned_rows).

None
Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/parquet.py
@renamed_kwargs(path="out_path")
def to_geoparquet(
    catalog: InMemoryGeoCatalog,
    out_path: str | Path,
    *,
    schema_version: int = SCHEMA_VERSION_CURRENT,
    write_covering_bbox: bool = True,
    partition_by: tuple[str, ...] | None = None,
) -> None:
    """Persist ``catalog`` as a GeoParquet file on disk.

    The result is a single Parquet file readable by any GeoParquet-aware
    tool (DuckDB, GDAL, pandas, geopandas) — not a pickle, so it
    survives version bumps and crosses Python / language boundaries.
    ``DuckDBGeoCatalog`` reads the *same* artifact, so this
    is the canonical interchange format for both backends.

    Two columns are added on write and stripped on load:

    - ``_backend``: round-trips the catalog `kind` so `from_geoparquet`
      restores the right loader dispatch.
    - ``_schema_version``: reserved for forward-compat (§10.4 of the
      design plan); bump on first substantive schema change.

    The row-level ``pd.IntervalIndex`` is unpacked into ``start_time`` /
    ``end_time`` columns (Parquet has no native IntervalIndex type);
    `from_geoparquet` rebuilds the index from those columns.

    Args:
        catalog: An `InMemoryGeoCatalog` to serialise. The catalog's
            ``gdf.crs`` is written into the GeoParquet metadata.
        out_path: Destination path. The ``.parquet`` extension is
            conventional. Any parent directory must exist. The file is
            written to a hidden sibling and renamed into place, so a
            failed write never leaves a partial file or clobbers an
            existing one.
        schema_version: Value written to the reserved
            ``_schema_version`` column. Defaults to
            `SCHEMA_VERSION_CURRENT` (today: 1).
        write_covering_bbox: Emit the per-row ``bbox`` covering struct
            that GeoParquet 1.1 readers (DuckDB, geopandas ≥0.14) use
            for predicate pushdown. Default True; turn off only if a
            downstream consumer chokes on 1.1.
        partition_by: Optional Hive partition columns for directory
            output. Built-in ``"year"``, ``"month"``, and ``"day"`` are
            derived from ``start_time``. Rows are streamed via
            `gdf.itertuples` (much faster than `iterrows` on large
            catalogs) and routed through `write_partitioned_rows`; an
            existing directory keeps every entry the writer does not
            own (see `write_partitioned_rows`).
    """
    gdf = catalog.gdf.copy()
    if gdf.geometry.name != "geometry":
        # `geometry` is the catalog schema's reserved name; the DuckDB
        # backend and every reader look for it.
        gdf = gdf.rename_geometry("geometry")
    if isinstance(gdf.index, pd.IntervalIndex):
        gdf["start_time"] = gdf.index.left
        gdf["end_time"] = gdf.index.right
        gdf = gdf.reset_index(drop=True)
    if partition_by is not None:
        from geocatalog._src.storage.streaming import write_partitioned_rows

        # `itertuples(index=False)` is ~10-50x faster than `iterrows()` on
        # wide catalogs (`iterrows` materialises a `pd.Series` per row).
        # Access columns by positional index — attribute access via
        # `row.<colname>` chokes on names like ``eo:cloud_cover`` that
        # aren't valid Python identifiers (pandas would silently rename
        # them to ``_0``/etc.).
        columns = list(gdf.columns)
        rows = (
            dict(zip(columns, tup, strict=True))
            for tup in gdf.itertuples(index=False, name=None)
        )
        write_partitioned_rows(
            rows,
            out_path=out_path,
            crs=gdf.crs,
            kind=catalog.kind,
            partition_by=partition_by,
            schema_version=schema_version,
            write_bbox=write_covering_bbox,
            replace=True,
        )
        return
    gdf["_backend"] = catalog.kind
    gdf["_schema_version"] = schema_version
    with _staged_path(Path(out_path)) as tmp:
        gdf.to_parquet(tmp, write_covering_bbox=write_covering_bbox)

geocatalog.storage.from_geoparquet(source, *, kind=None, strict=False, retries=3, storage_options=None)

Load a GeoParquet file into an InMemoryGeoCatalog.

Inverse of to_geoparquet: rebuilds the IntervalIndex from start_time / end_time columns and recovers the kind from the reserved _backend column. Externally produced files (no _backend column) default to kind "raster" — adjust on the returned catalog if that's wrong.

The reserved _schema_version column drives forward migration (see SCHEMA_VERSION_CURRENT and _MIGRATIONS):

  • v_artifact == v_current: load directly.
  • v_artifact < v_current: chain forward migrations transparently.
  • v_artifact > v_current: raise CatalogSchemaError — the reader is older than the writer and needs upgrading.

Parameters:

Name Type Description Default
source str | Path

Path to a GeoParquet file produced by to_geoparquet, DuckDB's COPY ... TO, or any GeoParquet 1.x writer.

required
kind CatalogKind | None

Kind override (loader dispatch). None reads the reserved _backend column; an explicit value skips tag recovery entirely (no warning, no strict raise).

None
strict bool

If True and neither kind= nor a _backend column is available, raise CatalogMetadataError instead of defaulting to "raster" with a warning.

False
retries int

Number of retries for transient remote I/O failures. 0 disables retry/backoff.

3
storage_options dict[str, Any] | None

obstore store options for cloud/HTTP URIs (e.g. {"skip_signature": True} for a public bucket), over the credentials registered in geocloud.credentials. Remote reads go through geocloud.fs (the [cloud] extra).

None

Returns:

Type Description
InMemoryGeoCatalog

An InMemoryGeoCatalog with the same rows, CRS, and (where

InMemoryGeoCatalog

recoverable) kind as the source.

Raises:

Type Description
CatalogSchemaError

If the artifact's _schema_version exceeds SCHEMA_VERSION_CURRENT.

CatalogMetadataError

strict=True and the artifact has no _backend column (and no kind= override).

Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/parquet.py
@renamed_kwargs(path="source", backend="kind")
def from_geoparquet(
    source: str | Path,
    *,
    kind: CatalogKind | None = None,
    strict: bool = False,
    retries: int = 3,
    storage_options: dict[str, Any] | None = None,
) -> InMemoryGeoCatalog:
    """Load a GeoParquet file into an `InMemoryGeoCatalog`.

    Inverse of `to_geoparquet`: rebuilds the `IntervalIndex` from
    ``start_time`` / ``end_time`` columns and recovers the `kind` from
    the reserved ``_backend`` column. Externally produced files (no
    ``_backend`` column) default to kind ``"raster"`` — adjust
    on the returned catalog if that's wrong.

    The reserved ``_schema_version`` column drives forward migration
    (see `SCHEMA_VERSION_CURRENT` and `_MIGRATIONS`):

    - ``v_artifact == v_current``: load directly.
    - ``v_artifact <  v_current``: chain forward migrations transparently.
    - ``v_artifact >  v_current``: raise `CatalogSchemaError` — the
      reader is older than the writer and needs upgrading.

    Args:
        source: Path to a GeoParquet file produced by `to_geoparquet`,
            DuckDB's ``COPY ... TO``, or any GeoParquet 1.x writer.
        kind: Kind override (loader dispatch). ``None`` reads the
            reserved ``_backend`` column; an explicit value skips tag
            recovery entirely (no warning, no strict raise).
        strict: If ``True`` and neither ``kind=`` nor a ``_backend``
            column is available, raise `CatalogMetadataError` instead of
            defaulting to ``"raster"`` with a warning.
        retries: Number of retries for transient remote I/O failures.
            ``0`` disables retry/backoff.
        storage_options: obstore store options for cloud/HTTP URIs
            (e.g. ``{"skip_signature": True}`` for a public bucket), over
            the credentials registered in `geocloud.credentials`. Remote
            reads go through `geocloud.fs` (the ``[cloud]`` extra).

    Returns:
        An `InMemoryGeoCatalog` with the same rows, CRS, and (where
        recoverable) kind as the source.

    Raises:
        CatalogSchemaError: If the artifact's `_schema_version` exceeds
            `SCHEMA_VERSION_CURRENT`.
        CatalogMetadataError: ``strict=True`` and the artifact has no
            ``_backend`` column (and no ``kind=`` override).
    """
    # Read the version *first* via a column-selective parquet load so
    # we can reject a v_future / multi-version artifact before paying
    # for the full read.
    v_artifact = retry_transient_io(
        _read_schema_version,
        source,
        storage_options=storage_options,
        retries=retries,
    )
    resolved = _resolve_uri(source, storage_options=storage_options)
    try:
        gdf = retry_transient_io(gpd.read_parquet, resolved, retries=retries)
    finally:
        _close_resolved_uri(resolved)
    backend_col = gdf.pop("_backend") if "_backend" in gdf.columns else None
    if "_schema_version" in gdf.columns:
        gdf = gdf.drop(columns=["_schema_version"])
    check_schema_versions(
        Path(source),
        v_artifact,
        v_artifact,
        reader=SCHEMA_VERSION_CURRENT,
        can_migrate=True,
    )
    if v_artifact < SCHEMA_VERSION_CURRENT:
        gdf = _apply_migrations(gdf, from_version=v_artifact)
    # Parquet hands `list<string>` back as numpy arrays; the state columns
    # get the same Python types every builder writes.
    gdf = coerce_state_columns(gdf)
    if "start_time" in gdf.columns and "end_time" in gdf.columns:
        idx = pd.IntervalIndex.from_arrays(
            gdf.pop("start_time"),
            gdf.pop("end_time"),
            closed="both",
            name="datetime",
        )
        gdf = gdf.set_index(idx)
    if kind is None:
        if backend_col is not None and len(backend_col) > 0:
            kind = backend_col.iloc[0]
        elif strict:
            raise CatalogMetadataError(
                f"{Path(source)} is missing the reserved '_backend' column. "
                "Pass kind=... explicitly, or write the catalog via "
                "geocatalog's to_geoparquet first."
            )
        else:
            log.warning(
                "opened {!r}: no _backend column found; defaulting to "
                "kind='raster'. Pass kind=... explicitly to silence.",
                str(source),
            )
            kind = "raster"
    return InMemoryGeoCatalog(gdf, kind=kind)

Schema migration

geocatalog.storage.SCHEMA_VERSION_CURRENT = 1 module-attribute

The reader's schema version. Bump on every substantive schema change and register the previous → this migration in parquet._MIGRATIONS.

v1 reserves STATE_COLUMNS.

geocatalog.storage.migrate_geoparquet(source, *, to_version)

Read source, migrate it to to_version, write back in-place.

A thin file-level wrapper over from_geoparquet + to_geoparquet used by the geocatalog migrate CLI. The new version is written to a sibling temp file and renamed over source, so a crash mid-migration leaves the original intact. The artifact is rewritten only if the migration actually changed the version, so calling twice is idempotent.

Parameters:

Name Type Description Default
source str | Path

GeoParquet file to migrate. Rewritten in-place.

required
to_version int

Target version. Must equal SCHEMA_VERSION_CURRENT today (forward-only migrations); kept as an explicit parameter so future versions can target a pinned schema.

required

Returns:

Type Description
int

The artifact's _schema_version before the migration. Equal

int

to to_version for already-current files.

Raises:

Type Description
CatalogSchemaError

If to_version differs from SCHEMA_VERSION_CURRENT.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/parquet.py
def migrate_geoparquet(source: str | Path, *, to_version: int) -> int:
    """Read ``source``, migrate it to ``to_version``, write back in-place.

    A thin file-level wrapper over `from_geoparquet` + `to_geoparquet`
    used by the ``geocatalog migrate`` CLI. The new version is written
    to a sibling temp file and renamed over ``source``, so a crash
    mid-migration leaves the original intact. The artifact is rewritten
    only if the migration actually changed the version, so calling
    twice is idempotent.

    Args:
        source: GeoParquet file to migrate. Rewritten in-place.
        to_version: Target version. Must equal `SCHEMA_VERSION_CURRENT`
            today (forward-only migrations); kept as an explicit
            parameter so future versions can target a pinned schema.

    Returns:
        The artifact's `_schema_version` *before* the migration. Equal
        to ``to_version`` for already-current files.

    Raises:
        CatalogSchemaError: If ``to_version`` differs from
            `SCHEMA_VERSION_CURRENT`.
    """
    if to_version != SCHEMA_VERSION_CURRENT:
        raise CatalogSchemaError(
            f"migrate target v{to_version} differs from reader "
            f"v{SCHEMA_VERSION_CURRENT}; only forward migrations to the "
            "current version are supported."
        )
    path = Path(source)
    # Cheap version probe via column-selective parquet read — avoids
    # materialising the full gdf just to decide we don't need to.
    from_version = _read_schema_version(path)
    if from_version == to_version:
        return from_version
    cat = from_geoparquet(path)
    to_geoparquet(cat, path, schema_version=to_version)
    return from_version

Streaming writes

geocatalog.storage.StreamingParquetWriter

Append-only GeoParquet 1.1 writer over a row iterator.

Buffers rows into Arrow record batches of batch_size, writes each batch via pyarrow.parquet.ParquetWriter, and on close() injects the aggregate GeoParquet geo key-value metadata (PROJJSON CRS, observed geometry types, total bbox, and the bbox-covering struct pointer). Geometries are encoded as WKB on the fly; the per-row bbox column (xmin/ymin/xmax/ymax struct) is computed per batch when write_bbox=True.

Rows go to a hidden sibling temp file that close renames onto path; abort (or leaving the with block on an exception) discards it. path therefore only ever holds a complete artifact — a failed write leaves any existing file there untouched.

Parameters:

Name Type Description Default
path str | Path

Destination GeoParquet file. Parent directory must exist.

required
crs Any

CRS of every input geometry. Written into geo.columns.geometry.crs as PROJJSON. Callers must canonicalise before writing — this class does not reproject.

required
kind CatalogKind

The catalog kind, copied to the reserved _backend column on every row (preserves loader-dispatch on reopen).

required
schema_version int

Value for the reserved _schema_version column. Defaults to SCHEMA_VERSION_CURRENT.

SCHEMA_VERSION_CURRENT
write_bbox bool

Emit the GeoParquet 1.1 bbox covering struct. Default True; turn off only if a downstream consumer chokes on 1.1.

True
batch_size int

Rows per Arrow record batch. Default 10 000 → peak memory ≈ 10 MB for ~1 KB-per-row catalogs (design §4.6).

10000
schema Schema | None

Arrow types for the extras columns. Fields named like a reserved or internal column are ignored (the writer owns those). None infers the extras schema from the whole first batch: the union of keys in first-seen order, each column typed by pyarrow.array over all its values (numpy scalars, pandas.Timestamp, dicts and lists included). Rows missing a key get a null. The schema is sealed after the first batch, so a key first seen later — or a column that was all-null in the first batch and gains values — raises rather than being dropped; pass schema= for such streams. In a state catalog (rows with run_time) the state columns are never inferred: they keep their v1 Arrow types.

None

start_time / end_time are stored as timestamp("ns") in naive UTC — the catalog's time-axis contract (tz-aware inputs are converted, naive inputs are taken as UTC).

Usage::

with StreamingParquetWriter(path, crs=crs, kind="raster") as w:
    for row in row_iter:
        w.write_row(row)
Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/streaming.py
class StreamingParquetWriter:
    """Append-only GeoParquet 1.1 writer over a row iterator.

    Buffers rows into Arrow record batches of `batch_size`, writes each
    batch via `pyarrow.parquet.ParquetWriter`, and on `close()` injects the
    aggregate GeoParquet ``geo`` key-value metadata (PROJJSON CRS, observed
    geometry types, total bbox, and the bbox-covering struct pointer).
    Geometries are encoded as WKB on the fly; the per-row bbox column
    (`xmin`/`ymin`/`xmax`/`ymax` struct) is computed per batch when
    `write_bbox=True`.

    Rows go to a hidden sibling temp file that `close` renames onto
    ``path``; `abort` (or leaving the ``with`` block on an exception)
    discards it. ``path`` therefore only ever holds a complete artifact —
    a failed write leaves any existing file there untouched.

    Args:
        path: Destination GeoParquet file. Parent directory must exist.
        crs: CRS of every input geometry. Written into ``geo.columns.geometry.crs``
            as PROJJSON. Callers must canonicalise *before* writing — this
            class does not reproject.
        kind: The catalog kind, copied to the reserved ``_backend``
            column on every row (preserves loader-dispatch on reopen).
        schema_version: Value for the reserved ``_schema_version`` column.
            Defaults to `SCHEMA_VERSION_CURRENT`.
        write_bbox: Emit the GeoParquet 1.1 ``bbox`` covering struct. Default
            True; turn off only if a downstream consumer chokes on 1.1.
        batch_size: Rows per Arrow record batch. Default 10 000 → peak
            memory ≈ 10 MB for ~1 KB-per-row catalogs (design §4.6).
        schema: Arrow types for the extras columns. Fields named like a
            reserved or internal column are ignored (the writer owns
            those). ``None`` infers the extras schema from the whole
            first batch: the union of keys in first-seen order, each
            column typed by `pyarrow.array` over all its values (numpy
            scalars, `pandas.Timestamp`, dicts and lists included). Rows
            missing a key get a null. The schema is sealed after the
            first batch, so a key first seen later — or a column that
            was all-null in the first batch and gains values — raises
            rather than being dropped; pass ``schema=`` for such streams.
            In a state catalog (rows with ``run_time``) the state
            columns are never inferred: they keep their v1 Arrow types.

    ``start_time`` / ``end_time`` are stored as ``timestamp("ns")`` in
    naive UTC — the catalog's time-axis contract (tz-aware inputs are
    converted, naive inputs are taken as UTC).

    Usage::

        with StreamingParquetWriter(path, crs=crs, kind="raster") as w:
            for row in row_iter:
                w.write_row(row)
    """

    @renamed_kwargs(backend="kind")
    def __init__(
        self,
        path: str | Path,
        *,
        crs: Any,
        kind: CatalogKind,
        schema_version: int = _SCHEMA_VERSION,
        write_bbox: bool = True,
        batch_size: int = 10_000,
        schema: pa.Schema | None = None,
    ) -> None:
        if batch_size < 1:
            raise ValueError(f"batch_size must be >= 1; got {batch_size}")
        self._path = Path(path)
        self._tmp_path = _staging_name(self._path)
        self._extras_schema = schema
        self._crs = pyproj.CRS.from_user_input(crs)
        self._kind: CatalogKind = kind
        self._schema_version = schema_version
        self._write_bbox = write_bbox
        self._batch_size = batch_size

        self._buffer: list[dict[str, Any]] = []
        self._writer: pq.ParquetWriter | None = None
        self._schema: pa.Schema | None = None
        self._geometry_types: set[str] = set()
        self._total_bbox: list[float] | None = None  # [xmin, ymin, xmax, ymax]
        self._closed = False

    def __enter__(self) -> StreamingParquetWriter:
        return self

    def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
        # Commit only a clean block; on an exception discard the partial
        # file so `path` keeps whatever it held before.
        if exc is None:
            self.close()
        else:
            self.abort()

    def write_row(self, row: dict[str, Any]) -> None:
        """Buffer one row; flush when the batch fills."""
        if self._closed:
            raise RuntimeError("StreamingParquetWriter: write_row after close")
        self._buffer.append(row)
        if len(self._buffer) >= self._batch_size:
            self._flush_batch()

    def close(self) -> None:
        """Flush remaining rows, finalise the metadata, move the file into place."""
        if self._closed:
            return
        self._closed = True
        try:
            if self._buffer:
                self._flush_batch()
            if self._writer is None:
                # No rows were written. Build an empty file so the artifact
                # path exists with valid metadata — downstream code can still
                # open it.
                schema = self._seal_schema([])
                self._writer = pq.ParquetWriter(self._tmp_path, schema=schema)
            self._writer.add_key_value_metadata(
                {"geo": json.dumps(self._build_geo_metadata())}
            )
            self._writer.close()
        except BaseException:
            self._discard()
            raise
        os.replace(self._tmp_path, self._path)

    def abort(self) -> None:
        """Discard everything written so far; ``path`` is left untouched."""
        if self._closed:
            return
        self._closed = True
        self._discard()

    def _discard(self) -> None:
        self._buffer = []
        if self._writer is not None:
            try:
                self._writer.close()
            except Exception:
                log.exception(
                    "StreamingParquetWriter: close failed while discarding "
                    "a partial file"
                )
        self._tmp_path.unlink(missing_ok=True)

    # -- internals -----------------------------------------------------------

    def _flush_batch(self) -> None:
        rows = self._buffer
        self._buffer = []
        if self._schema is None:
            self._schema = self._seal_schema(rows)
            self._writer = pq.ParquetWriter(self._tmp_path, schema=self._schema)
        table = self._rows_to_table(rows, schema=self._schema)
        assert self._writer is not None  # for ty
        self._writer.write_table(table)

    def _seal_schema(self, rows: list[dict[str, Any]]) -> pa.Schema:
        """Build the file schema from ``schema=`` or the first batch.

        Reserved columns come first in a fixed order (matching what
        `to_geoparquet` writes for the InMemory backend), then the
        extras, then the internal ``_backend`` / ``_schema_version``.
        """
        fields: list[pa.Field] = [
            pa.field("filepath", pa.string()),
            pa.field("start_time", _TIME_TYPE),
            pa.field("end_time", _TIME_TYPE),
            pa.field("geometry", pa.binary()),
        ]
        if self._write_bbox:
            fields.append(pa.field("bbox", _BBOX_TYPE))
        if self._extras_schema is not None:
            fields.extend(f for f in self._extras_schema if f.name not in _WRITER_OWNED)
        else:
            keys: dict[str, None] = {}
            for row in rows:
                keys.update(dict.fromkeys(k for k in row if k not in _WRITER_OWNED))
            # A state catalog's columns have fixed types: an all-null
            # `member` in the first batch (analyses) must not seal as null.
            # Elsewhere (no `run_time`) the names are ordinary extras.
            state_types = state_arrow_types() if is_state_frame(keys) else {}
            for key in keys:
                if key in state_types:
                    fields.append(pa.field(key, state_types[key]))
                    continue
                values = [row.get(key) for row in rows]
                fields.append(pa.field(key, _column_array(key, values).type))
        fields.append(pa.field("_backend", pa.string()))
        fields.append(pa.field("_schema_version", pa.int32()))
        return pa.schema(fields)

    def _rows_to_table(
        self,
        rows: list[dict[str, Any]],
        *,
        schema: pa.Schema,
    ) -> pa.Table:
        """Convert a list of row dicts into an Arrow table matching `schema`."""
        known = set(schema.names)
        wkbs: list[bytes] = []
        boxes: list[dict[str, float]] = []
        for row in rows:
            unknown = [k for k in row if k not in known and k not in _WRITER_OWNED]
            if unknown:
                raise ValueError(
                    f"StreamingParquetWriter: row has columns {unknown} that are "
                    "not in the sealed schema (inferred from the first batch). "
                    "Pass schema= covering every extras column."
                )
            geom = row.get("geometry")
            if not isinstance(geom, shapely.geometry.base.BaseGeometry):
                raise TypeError(
                    f"StreamingParquetWriter: 'geometry' must be a shapely "
                    f"geometry; got {type(geom).__name__}"
                )
            self._geometry_types.add(geom.geom_type)
            xmin, ymin, xmax, ymax = geom.bounds
            if self._total_bbox is None:
                self._total_bbox = [xmin, ymin, xmax, ymax]
            else:
                self._total_bbox[0] = min(self._total_bbox[0], xmin)
                self._total_bbox[1] = min(self._total_bbox[1], ymin)
                self._total_bbox[2] = max(self._total_bbox[2], xmax)
                self._total_bbox[3] = max(self._total_bbox[3], ymax)
            wkbs.append(shapely.wkb.dumps(geom))
            boxes.append({"xmin": xmin, "ymin": ymin, "xmax": xmax, "ymax": ymax})

        n = len(rows)
        arrays: list[pa.Array] = []
        for field in schema:
            name = field.name
            if name == "geometry":
                arrays.append(pa.array(wkbs, type=field.type))
            elif name == "bbox":
                arrays.append(pa.array(boxes, type=field.type))
            elif name == "_backend":
                arrays.append(pa.array([self._kind] * n, type=field.type))
            elif name == "_schema_version":
                arrays.append(pa.array([self._schema_version] * n, type=field.type))
            elif name in ("start_time", "end_time"):
                times = [_naive_utc_or_none(row.get(name)) for row in rows]
                arrays.append(_column_array(name, times, field.type))
            else:
                values = [row.get(name) for row in rows]
                arrays.append(_column_array(name, values, field.type))
        return pa.Table.from_arrays(arrays, schema=schema)

    def _build_geo_metadata(self) -> dict[str, Any]:
        column_meta: dict[str, Any] = {
            "encoding": "WKB",
            "geometry_types": sorted(self._geometry_types) or ["Polygon"],
            "crs": self._crs.to_json_dict(),
        }
        if self._total_bbox is not None:
            column_meta["bbox"] = list(self._total_bbox)
        if self._write_bbox:
            column_meta["covering"] = {
                "bbox": {
                    "xmin": ["bbox", "xmin"],
                    "ymin": ["bbox", "ymin"],
                    "xmax": ["bbox", "xmax"],
                    "ymax": ["bbox", "ymax"],
                }
            }
        return {
            "version": _GEOPARQUET_VERSION,
            "primary_column": "geometry",
            "columns": {"geometry": column_meta},
        }

abort()

Discard everything written so far; path is left untouched.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/streaming.py
def abort(self) -> None:
    """Discard everything written so far; ``path`` is left untouched."""
    if self._closed:
        return
    self._closed = True
    self._discard()

close()

Flush remaining rows, finalise the metadata, move the file into place.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/streaming.py
def close(self) -> None:
    """Flush remaining rows, finalise the metadata, move the file into place."""
    if self._closed:
        return
    self._closed = True
    try:
        if self._buffer:
            self._flush_batch()
        if self._writer is None:
            # No rows were written. Build an empty file so the artifact
            # path exists with valid metadata — downstream code can still
            # open it.
            schema = self._seal_schema([])
            self._writer = pq.ParquetWriter(self._tmp_path, schema=schema)
        self._writer.add_key_value_metadata(
            {"geo": json.dumps(self._build_geo_metadata())}
        )
        self._writer.close()
    except BaseException:
        self._discard()
        raise
    os.replace(self._tmp_path, self._path)

write_row(row)

Buffer one row; flush when the batch fills.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/streaming.py
def write_row(self, row: dict[str, Any]) -> None:
    """Buffer one row; flush when the batch fills."""
    if self._closed:
        raise RuntimeError("StreamingParquetWriter: write_row after close")
    self._buffer.append(row)
    if len(self._buffer) >= self._batch_size:
        self._flush_batch()

geocatalog.storage.sort_geoparquet(source, out_path, *, sort_by, crs, kind, schema_version=_SCHEMA_VERSION, write_bbox=True, batch_size=10000)

Rewrite a streamed GeoParquet file in sort_by order via DuckDB.

Opens source as a DuckDB relation, sorts by the given keys (the literal token "geometry_hilbert" expands to ST_Hilbert(ST_Centroid(geometry))), and streams the sorted relation back through pyarrow.parquet.ParquetWriter so the final file carries the same GeoParquet 1.1 geo metadata + bbox covering struct as the streamed input.

Parameters:

Name Type Description Default
source str | Path

Path to the unsorted GeoParquet (written by StreamingParquetWriter).

required
out_path str | Path

Path to write the sorted result. Overwrites if it exists.

required
sort_by Sequence[str]

Sort keys. Plain column names pass through; the literal token "geometry_hilbert" expands to ST_Hilbert(ST_Centroid(geometry)).

required
crs Any

CRS to encode in the destination's GeoParquet metadata.

required
kind CatalogKind

Catalog kind for the destination's metadata.

required
schema_version int

Schema version for the destination.

SCHEMA_VERSION_CURRENT
write_bbox bool

Emit the GeoParquet 1.1 covering bbox struct.

True
batch_size int

Pyarrow batch size for the streamed rewrite.

10000

Raises:

Type Description
ImportError

[duckdb] extra missing.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/streaming.py
@renamed_kwargs(src="source", dst="out_path", backend="kind")
def sort_geoparquet(
    source: str | Path,
    out_path: str | Path,
    *,
    sort_by: Sequence[str],
    crs: Any,
    kind: CatalogKind,
    schema_version: int = _SCHEMA_VERSION,
    write_bbox: bool = True,
    batch_size: int = 10_000,
) -> None:
    """Rewrite a streamed GeoParquet file in `sort_by` order via DuckDB.

    Opens ``source`` as a DuckDB relation, sorts by the given keys (the
    literal token ``"geometry_hilbert"`` expands to
    ``ST_Hilbert(ST_Centroid(geometry))``), and streams the sorted
    relation back through `pyarrow.parquet.ParquetWriter` so the final
    file carries the same GeoParquet 1.1 ``geo`` metadata + bbox covering
    struct as the streamed input.

    Args:
        source: Path to the unsorted GeoParquet (written by
            `StreamingParquetWriter`).
        out_path: Path to write the sorted result. Overwrites if it exists.
        sort_by: Sort keys. Plain column names pass through; the literal
            token ``"geometry_hilbert"`` expands to
            ``ST_Hilbert(ST_Centroid(geometry))``.
        crs: CRS to encode in the destination's GeoParquet metadata.
        kind: Catalog kind for the destination's metadata.
        schema_version: Schema version for the destination.
        write_bbox: Emit the GeoParquet 1.1 covering bbox struct.
        batch_size: Pyarrow batch size for the streamed rewrite.

    Raises:
        ImportError: ``[duckdb]`` extra missing.
    """
    from geocatalog._src.backends.duckdb_backend import _require_duckdb

    duckdb_mod = _require_duckdb()
    src_str = str(source)
    dst_path = Path(out_path)

    # Build the sort SQL. Underlying assumption: `start_time` / `geometry`
    # exist as columns (every streamed builder produces them).
    order_exprs: list[str] = []
    needs_hilbert = False
    for key in sort_by:
        if key == "geometry_hilbert":
            order_exprs.append("ST_Hilbert(ST_Centroid(geometry))")
            needs_hilbert = True
        else:
            order_exprs.append(_quote_ident(key))
    if not order_exprs:
        raise ValueError("sort_by must contain at least one key")

    con = duckdb_mod.connect(":memory:")
    try:
        con.install_extension("spatial")
        con.load_extension("spatial")
        order_sql = ", ".join(order_exprs)
        sql = f"""
            SELECT *
            FROM read_parquet($src)
            ORDER BY {order_sql}
        """
        relation = con.sql(sql, params={"src": src_str})

        # Stream the sorted relation back through pyarrow. We re-encode via
        # `StreamingParquetWriter` so the destination carries the canonical
        # GeoParquet 1.1 metadata + bbox struct, regardless of what DuckDB's
        # arrow output looks like.
        # `to_arrow_reader` since duckdb 1.1; `fetch_arrow_reader` deprecated.
        reader = relation.to_arrow_reader(batch_size=batch_size)
        # Carry the input's extras types through: re-inferring from the
        # first *sorted* batch would retype a column whose leading values
        # happen to be missing.
        with StreamingParquetWriter(
            dst_path,
            crs=crs,
            kind=kind,
            schema_version=schema_version,
            write_bbox=write_bbox,
            batch_size=batch_size,
            schema=pq.read_schema(src_str),
        ) as writer:
            for batch in reader:
                _write_arrow_batch(writer, batch)
    finally:
        con.close()
    if needs_hilbert:
        log.debug(
            "sort_geoparquet: rewrote {} with Hilbert sort -> {}", source, dst_path
        )

STAC export (extras: [stac])

geocatalog.storage.to_stac_collection(catalog, *, collection_id, description='', asset_key='data')

Convert a catalog into a STAC collection.

Rows are grouped into one item per scene: rows sharing a source stac_collection and a stac_item_id (or, failing that, an id — the CatalogBundle primary key) become one item whose assets are keyed by each row's asset_key. An id that occurs in more than one source collection is exported as "<source collection>:<id>" so the output ids stay unique. A row with neither id gets its own item, "<collection_id>-<row>". The item's geometry, time and properties come from its first row.

Properties are made JSON-safe: numpy scalars become Python numbers, timestamps RFC 3339 strings, and missing values (None, NaN, NaT, non-finite floats) are omitted, so json.dumps(collection.to_dict()) always works.

Parameters:

Name Type Description Default
catalog GeoCatalog

Catalog to export.

required
collection_id str

The collection id; also stamped on every item.

required
description str

Collection description.

''
asset_key str

Asset key for rows without an asset_key column.

'data'

Returns:

Type Description
Collection

A pystac.Collection holding the items.

Raises:

Type Description
ValueError

Two rows of the same item carry the same asset key.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/stac.py
def to_stac_collection(
    catalog: GeoCatalog,
    *,
    collection_id: str,
    description: str = "",
    asset_key: str = "data",
) -> pystac.Collection:
    """Convert a catalog into a STAC collection.

    Rows are grouped into one item per scene: rows sharing a source
    ``stac_collection`` and a ``stac_item_id`` (or, failing that, an
    ``id`` — the `CatalogBundle` primary key) become one item whose
    assets are keyed by each row's ``asset_key``. An id that occurs in
    more than one source collection is exported as
    ``"<source collection>:<id>"`` so the output ids stay unique. A row
    with neither id gets its own item, ``"<collection_id>-<row>"``. The
    item's geometry, time and properties come from its first row.

    Properties are made JSON-safe: numpy scalars become Python numbers,
    timestamps RFC 3339 strings, and missing values (``None``, ``NaN``,
    ``NaT``, non-finite floats) are omitted, so
    ``json.dumps(collection.to_dict())`` always works.

    Args:
        catalog: Catalog to export.
        collection_id: The collection id; also stamped on every item.
        description: Collection description.
        asset_key: Asset key for rows without an ``asset_key`` column.

    Returns:
        A `pystac.Collection` holding the items.

    Raises:
        ValueError: Two rows of the same item carry the same asset key.
    """
    pystac = _require_pystac()
    extent = _collection_extent(catalog, pystac)
    collection = pystac.Collection(
        id=collection_id,
        description=description,
        extent=extent,
    )

    groups = _group_scenes(catalog, collection_id)
    for item_id, rows in groups.items():
        first = rows[0]
        geom = _geometry_to_stac_crs(first.geometry, first.crs)
        props = {
            key: value for key, value in first.extras.items() if key not in _EXPORT_SKIP
        }
        # An item-level CRS is inherited by every asset without its own,
        # so it is only written when all the item's assets share it.
        # Without a resolved `crs` column the carried `proj:*` properties
        # are the only CRS record, so they are kept as they are.
        has_crs_column = any("crs" in row.extras for row in rows)
        crs_values = [row.extras.get("crs") for row in rows]
        shared_crs = _same_crs(crs_values)
        if has_crs_column and not shared_crs:
            props.pop("crs", None)
            for field in _PROJ_CRS_FIELDS:
                props.pop(field, None)
        _normalize_crs_property(props)
        props = _json_safe_mapping(props)
        start = _datetime_or_none(first.interval.left)
        end = _datetime_or_none(first.interval.right)
        # STAC / RFC3339 require tz-aware ISO 8601 with `Z` (or offset)
        # for `start_datetime` / `end_datetime` and the item-level
        # `datetime`. Naive timestamps from the catalog time-axis are
        # treated as UTC.
        item_datetime = _to_utc_datetime(start) if _same_instant(start, end) else None
        if item_datetime is None:
            props["start_datetime"] = _to_rfc3339(start)
            props["end_datetime"] = _to_rfc3339(end)

        item = pystac.Item(
            id=item_id,
            geometry=shapely.geometry.mapping(geom),
            bbox=tuple(geom.bounds),
            datetime=item_datetime,
            properties=props,
            collection=collection_id,
        )
        for row in rows:
            key = row.extras.get("asset_key")
            key = str(key) if _present(key) else asset_key
            if key in item.assets:
                raise ValueError(
                    f"to_stac_collection: item {item_id!r} has more than one "
                    f"row for asset {key!r}"
                )
            fields: dict[str, Any] = {}
            crs = row.extras.get("crs")
            if _present(crs) and not shared_crs:
                # Per the projection extension, an asset-level CRS
                # overrides the item's.
                fields = {"crs": crs}
                _normalize_crs_property(fields)
            item.add_asset(key, pystac.Asset(href=row.filepath, extra_fields=fields))
        collection.add_item(item)
    return collection

Provenance bundles

geocatalog.storage.CatalogBundle

Wraps an InMemoryGeoCatalog + queries + matchups + persistence.

See module docstring for the directory layout and lifecycle.

Attributes:

Name Type Description
catalog

The items table as an InMemoryGeoCatalog. Updated in place when ingest() adds new rows.

crs

Authoritative CRS for the items table's geometry column. Set at construction; reprojection happens on ingest, never on lookup. (target_crs is the deprecated name.)

kind

The catalog kind forwarded to the items table. (backend is the deprecated name.)

queries list[QueryRecord]

In-memory list of QueryRecords. Persisted to queries.parquet on to_directory.

matchups list[MatchupRow]

In-memory list of MatchupRows. Persisted to matchups.parquet.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/bundle.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
class CatalogBundle:
    """Wraps an `InMemoryGeoCatalog` + queries + matchups + persistence.

    See module docstring for the directory layout and lifecycle.

    Attributes:
        catalog: The items table as an `InMemoryGeoCatalog`. Updated
            in place when `ingest()` adds new rows.
        crs: Authoritative CRS for the items table's geometry column.
            Set at construction; reprojection happens on ingest, never
            on lookup. (``target_crs`` is the deprecated name.)
        kind: The catalog kind forwarded to the items table.
            (``backend`` is the deprecated name.)
        queries: In-memory list of `QueryRecord`s. Persisted to
            ``queries.parquet`` on `to_directory`.
        matchups: In-memory list of `MatchupRow`s. Persisted to
            ``matchups.parquet``.
    """

    target_crs = deprecated_alias("crs")
    backend = deprecated_alias("kind")

    @renamed_kwargs(target_crs="crs", backend="kind")
    def __init__(
        self,
        catalog: InMemoryGeoCatalog,
        *,
        crs: pyproj.CRS,
        kind: CatalogKind = "raster",
        queries: list[QueryRecord] | None = None,
        matchups: list[MatchupRow] | None = None,
    ) -> None:
        self.catalog = catalog
        self.crs = pyproj.CRS.from_user_input(crs)
        self.kind = kind
        self.queries: list[QueryRecord] = list(queries) if queries else []
        self.matchups: list[MatchupRow] = list(matchups) if matchups else []
        # When the bundle was first written; kept across re-saves.
        self.created_at: str | None = None

    @classmethod
    @renamed_kwargs(target_crs="crs", backend="kind")
    def empty(
        cls,
        *,
        crs: str | pyproj.CRS = "EPSG:4326",
        kind: CatalogKind = "raster",
    ) -> CatalogBundle:
        """Create a fresh bundle with an empty items table.

        Use this as the starting point when ingesting from a `Source`:

            >>> bundle = CatalogBundle.empty(crs="EPSG:4326")
            >>> bundle.ingest(STACSource.planetary_computer(), ...)
            >>> bundle.to_directory("my_catalog/")
        """
        dst_crs = pyproj.CRS.from_user_input(crs)
        # The same columns `source_row_to_gdf_row` writes, so an empty
        # bundle has the schema of an ingested one.
        empty_gdf = empty_frame(
            dst_crs,
            {
                "filepath": "object",
                "crs": "object",
                "href_signed": "bool",
                "id": "object",
                "source": "object",
                "collection": "object",
                "assets": "object",
                "properties": "object",
                "provenance": "object",
            },
        )
        catalog = InMemoryGeoCatalog(empty_gdf, kind=kind)
        return cls(catalog, crs=dst_crs, kind=kind)

    @classmethod
    @renamed_kwargs(backend="kind")
    def from_catalog(
        cls,
        catalog: InMemoryGeoCatalog,
        *,
        kind: CatalogKind | None = None,
    ) -> CatalogBundle:
        """Wrap an already-built `InMemoryGeoCatalog`.

        Useful when the user constructed a catalog via
        ``build_raster_catalog`` / ``build_vector_catalog`` and now
        wants to add queries/matchups state.
        """
        return cls(
            catalog,
            crs=pyproj.CRS.from_user_input(catalog.gdf.crs),
            kind=kind if kind is not None else catalog.kind,
        )

    def ingest(
        self,
        source: Source,
        *,
        bounds: tuple[float, float, float, float],
        interval: pd.Interval | None = None,
        collection: str | None = None,
        filters: Mapping[str, Any] | None = None,
        limit: int | None = None,
        primary_asset: str | None = None,
        tag: str | None = None,
        notes: str | None = None,
        on_duplicate: Literal["error", "skip", "replace"] = "error",
    ) -> str:
        """Query a `Source` and append matching rows to the items table.

        Records the call in ``self.queries`` with a fresh UUID so
        every row can be traced back to the call that produced it.

        Args:
            source: Any `Source` Protocol implementer (STACSource,
                EarthAccessSource, ...).
            bounds: ``(xmin, ymin, xmax, ymax)`` in EPSG:4326.
            interval: Optional time window.
            collection: Upstream collection id (passed through to
                ``Source.query``).
            filters: Adapter-specific filter dict.
            limit: Cap on the number of rows returned. ``0`` ingests
                nothing (no request); ``None`` means no cap.
            primary_asset: Asset key to promote to the catalog's
                ``filepath`` column. ``None`` uses the first asset
                key (dict insertion order).
            tag: User label persisted in ``QueryRecord.tag`` and
                propagated to every row via
                ``provenance['query_tag']``.
            notes: Free-form notes recorded in ``QueryRecord.notes``.
            on_duplicate: What to do with a row whose
                ``(source, collection, id)`` — the items table's primary
                key; upstream ids are only unique within a collection —
                is already in the bundle or repeats within this ingest.
                ``"error"`` raises before anything is changed; ``"skip"``
                keeps the existing row (so re-running an ingest is a
                no-op) and never inspects the discarded one;
                ``"replace"`` keeps the newest one and drops the
                matchups that referenced the replaced item, since they
                describe the old data.

        Returns:
            The query_id (uuid4 hex) of this ingest call.

        Raises:
            ValueError: A duplicate ``id`` with ``on_duplicate="error"``,
                or an unknown ``on_duplicate``.
            KeyError: ``primary_asset`` is missing from a row.
        """
        if on_duplicate not in ("error", "skip", "replace"):
            raise ValueError(
                "on_duplicate must be 'error', 'skip' or 'replace'; "
                f"got {on_duplicate!r}"
            )
        from shapely.geometry import box as _shapely_box

        query_id = uuid.uuid4().hex
        created_at = datetime.now(tz=UTC)
        stamped_rows: list[SourceRow] = []
        for row in source.query(
            bounds,
            interval,
            collection=collection,
            filters=filters,
            limit=limit,
        ):
            # Stamp the bundle's query_id onto the row's provenance so
            # downstream tooling can join items ↔ queries without an
            # extra DataFrame merge. We preserve any provenance the
            # adapter already set (e.g. earthaccess might add its own
            # granule UR or doi).
            prov = dict(row.provenance)
            prov.setdefault("query_id", query_id)
            # Use setdefault so an adapter that already set
            # `query_tag` on the row's provenance wins (consistent
            # with the documented "do not overwrite" contract for
            # query_id). If the user's tag and the adapter's
            # disagree, prefer the more-specific (adapter-set) one.
            if tag is not None:
                prov.setdefault("query_tag", tag)
            stamped_rows.append(dataclasses.replace(row, provenance=prov))
        n = len(stamped_rows)

        # Resolve duplicates before mapping, so rows the policy discards
        # are never validated (a skipped row may lack `primary_asset`).
        existing = _item_keys(self.catalog.gdf)
        stamped_rows = _resolve_duplicates(stamped_rows, existing, on_duplicate)
        new_rows = [
            source_row_to_gdf_row(row, crs=self.crs, primary_asset=primary_asset)
            for row in stamped_rows
        ]
        base = self.catalog.gdf
        if on_duplicate == "replace":
            replaced = {_row_key(r) for r in stamped_rows} & existing
            if replaced:
                keep = [k not in replaced for k in _gdf_keys(base)]
                base = base[keep]
                self._drop_matchups_of(replaced)

        if new_rows:
            new_gdf = gpd.GeoDataFrame(new_rows, crs=self.crs)
            new_gdf.index = pd.IntervalIndex.from_arrays(
                new_gdf.pop("start_time"),
                new_gdf.pop("end_time"),
                closed="both",
                name="datetime",
            )
            merged = pd.concat([base, new_gdf], axis=0)
            self.catalog = InMemoryGeoCatalog(
                gpd.GeoDataFrame(merged, crs=self.crs),
                kind=self.kind,
            )

        self.queries.append(
            QueryRecord(
                query_id=query_id,
                source=getattr(source, "name", "unknown"),
                collection=collection,
                bounds_wkt=_shapely_box(*bounds).wkt,
                time_start=(
                    pd.Timestamp(interval.left) if interval is not None else None
                ),
                time_end=(
                    pd.Timestamp(interval.right) if interval is not None else None
                ),
                filters_json=json.dumps(dict(filters), default=str) if filters else "",
                created_at=created_at,
                n_returned=n,
                tag=tag,
                notes=notes,
            )
        )
        return query_id

    def _drop_matchups_of(self, items: set[tuple[str, str, str]]) -> None:
        """Drop matchups with a member in ``items`` ((source, collection, id)).

        A matchup that records its members' collections is matched on
        the full key, so replacing one collection's item keeps the
        matchups of a same-id item in another collection. Older rows
        without collections can only be matched on ``(source, id)``
        and are dropped whenever that pair is replaced.
        """
        pairs = {(src, rid) for src, _, rid in items}

        def stale(m: MatchupRow) -> bool:
            if len(m.member_collections) == len(m.member_ids):
                return any(
                    (str(s), str(c), str(i)) in items
                    for s, c, i in zip(
                        m.member_sources,
                        m.member_collections,
                        m.member_ids,
                        strict=True,
                    )
                )
            return any(
                (str(s), str(i)) in pairs
                for s, i in zip(m.member_sources, m.member_ids, strict=True)
            )

        kept = [m for m in self.matchups if not stale(m)]
        if len(kept) < len(self.matchups):
            logger.warning(
                "ingest: dropped {} matchup(s) referencing replaced items",
                len(self.matchups) - len(kept),
            )
        self.matchups = kept

    def write_matchups(
        self,
        rows: Iterable[MatchupRow],
        *,
        tag: str | None = None,
    ) -> int:
        """Persist a stream of `MatchupRow`s into the bundle.

        Args:
            rows: Iterable of `MatchupRow` (typically the output of
                ``geocatalog.matchup.matchup(...)``).
            tag: Optional ``query_set`` override applied to every
                row. When ``None``, each row keeps its own
                ``query_set``.

        ``matchup_id`` is the table's key: a row whose id is already in
        the bundle replaces the stored one in place (so re-running a
        deterministic matchup does not duplicate it, and a re-run under
        another ``tag`` moves it to that ``query_set``).

        Returns:
            How many rows were written (added or replaced).
        """
        position = {m.matchup_id: i for i, m in enumerate(self.matchups)}
        written = 0
        for row in rows:
            mr = dataclasses.replace(row, query_set=tag) if tag is not None else row
            if mr.matchup_id in position:
                self.matchups[position[mr.matchup_id]] = mr
            else:
                position[mr.matchup_id] = len(self.matchups)
                self.matchups.append(mr)
            written += 1
        return written

    # ------------------------------------------------------------------
    # Persistence
    # ------------------------------------------------------------------

    def to_directory(self, path: str | Path) -> None:
        """Persist the bundle as a directory of Parquet files + metadata.

        Layout::

            <path>/
              items.parquet
              queries.parquet     (omitted when empty)
              matchups.parquet    (omitted when empty)
              _meta.json

        Existing files inside ``path`` are overwritten. Stale
        ``queries.parquet`` / ``matchups.parquet`` from a previous
        write are *removed* when the corresponding in-memory list is
        empty — otherwise `from_directory()` would silently
        resurrect rows that should have been dropped.

        Every component is first written to a hidden staging directory
        next to ``path``; only once all of them exist is the bundle
        published, by swapping that directory in for ``path`` (files the
        bundle does not own are moved across). A reader therefore sees
        either the previous generation or the new one — never new items
        beside old queries or metadata — and a failure while writing
        leaves the previous bundle untouched.
        ``created_at`` records the first save and survives later ones;
        ``updated_at`` is the latest.
        """
        from geocatalog._src.storage.parquet import to_geoparquet

        dest = Path(path)
        dest.parent.mkdir(parents=True, exist_ok=True)
        now = datetime.now(tz=UTC).isoformat()
        created_at = self.created_at or _existing_created_at(dest) or now
        meta = {
            "bundle_schema_version": BUNDLE_SCHEMA_VERSION,
            # On-disk keys keep their names (no bundle-schema change).
            "target_crs": crs_config_string(self.crs),
            "backend": self.kind,
            "created_at": created_at,
            "updated_at": now,
        }
        token = uuid.uuid4().hex
        staging = dest.with_name(f".{dest.name}.{token}.new")
        staging.mkdir()
        try:
            to_geoparquet(self.catalog, staging / "items.parquet")
            # Sidecar tables are written only when non-empty, so the
            # directory matches the in-memory contract (empty = omitted).
            if self.queries:
                _queries_to_parquet(self.queries, staging / "queries.parquet")
            if self.matchups:
                _matchups_to_parquet(self.matchups, staging / "matchups.parquet")
            (staging / "_meta.json").write_text(json.dumps(meta, indent=2))
        except BaseException:
            shutil.rmtree(staging, ignore_errors=True)
            raise
        _publish_directory(staging, dest, owned=_BUNDLE_FILES, token=token)
        self.created_at = created_at

    @classmethod
    def from_directory(cls, path: str | Path) -> CatalogBundle:
        """Load a bundle from disk. Inverse of `to_directory`."""
        from geocatalog._src.storage.parquet import from_geoparquet

        src = Path(path)
        if not src.is_dir():
            raise NotADirectoryError(
                f"CatalogBundle.from_directory expects a directory; got {src!r}. "
                "If the path is a single GeoParquet file, use "
                "`geocatalog.storage.from_geoparquet(path)` to get an "
                "`InMemoryGeoCatalog`, then wrap it with "
                "`CatalogBundle.from_catalog`."
            )
        meta_path = src / "_meta.json"
        if not meta_path.exists():
            raise FileNotFoundError(
                f"CatalogBundle directory {src!r} is missing `_meta.json`. "
                "Was it produced by `to_directory`?"
            )
        meta = json.loads(meta_path.read_text())
        # Schema-version gate: reject artifacts written by a newer
        # bundle layout we don't understand. Forward migrations live
        # alongside the catalog's `_schema_version` chain (parquet.py);
        # for now there's only one version and no migrations.
        artifact_version = meta.get("bundle_schema_version")
        if artifact_version is None:
            raise ValueError(
                f"CatalogBundle directory {src!r} `_meta.json` is missing "
                "`bundle_schema_version`; this bundle predates the version "
                "field. Inspect / rewrite via the geocatalog CLI's "
                "migration tools."
            )
        if int(artifact_version) > BUNDLE_SCHEMA_VERSION:
            raise ValueError(
                f"CatalogBundle directory {src!r} has bundle_schema_version="
                f"{artifact_version!r}, exceeds reader v{BUNDLE_SCHEMA_VERSION}. "
                "Upgrade `geocatalog` to read this bundle."
            )
        try:
            target_crs = pyproj.CRS.from_user_input(meta["target_crs"])
        except (KeyError, pyproj.exceptions.CRSError) as exc:
            raise ValueError(
                f"CatalogBundle directory {src!r} `_meta.json` has no valid "
                f"`target_crs`: {exc}"
            ) from exc
        backend = meta.get("backend", "raster")
        if backend not in ("raster", "xarray", "vector"):
            raise ValueError(
                f"CatalogBundle directory {src!r} `_meta.json` has unknown "
                f"backend {backend!r}"
            )

        catalog = from_geoparquet(src / "items.parquet", kind=backend)
        # Checked for empty bundles too: a later ingest builds rows in
        # `target_crs` and concatenates them onto this table.
        if catalog.gdf.crs is not None and not pyproj.CRS.from_user_input(
            catalog.gdf.crs
        ).equals(target_crs):
            raise ValueError(
                f"CatalogBundle directory {src!r}: items.parquet CRS "
                f"{catalog.gdf.crs} does not match `_meta.json` target_crs "
                f"{target_crs.to_string()}"
            )
        queries = (
            _queries_from_parquet(src / "queries.parquet")
            if (src / "queries.parquet").exists()
            else []
        )
        matchups = (
            _matchups_from_parquet(src / "matchups.parquet")
            if (src / "matchups.parquet").exists()
            else []
        )
        bundle = cls(
            catalog,
            crs=target_crs,
            kind=backend,
            queries=queries,
            matchups=matchups,
        )
        bundle.created_at = meta.get("created_at")
        return bundle

    # ------------------------------------------------------------------
    # Convenience accessors
    # ------------------------------------------------------------------

    @property
    def n_items(self) -> int:
        """Number of rows in the items table."""
        return len(self.catalog)

    def queries_df(self) -> pd.DataFrame:
        """Return the queries table as a `pd.DataFrame` for ad-hoc analysis."""
        if not self.queries:
            return pd.DataFrame(
                columns=[f.name for f in dataclasses.fields(QueryRecord)]
            )
        return pd.DataFrame([dataclasses.asdict(q) for q in self.queries])

    def matchups_df(self) -> pd.DataFrame:
        """Return the matchups table as a `pd.DataFrame`."""
        from geocatalog._src.matchup.engine import MatchupRow

        if not self.matchups:
            return pd.DataFrame(
                columns=[f.name for f in dataclasses.fields(MatchupRow)]
            )
        # geometry_intersect is a shapely geometry — serialize to WKT
        # for the dataframe view so the DataFrame is JSON/Parquet-friendly.
        rows = []
        for m in self.matchups:
            d = dataclasses.asdict(m)
            d["geometry_intersect"] = m.geometry_intersect.wkt
            rows.append(d)
        return pd.DataFrame(rows)

n_items property

Number of rows in the items table.

empty(*, crs='EPSG:4326', kind='raster') classmethod

Create a fresh bundle with an empty items table.

Use this as the starting point when ingesting from a Source:

>>> bundle = CatalogBundle.empty(crs="EPSG:4326")
>>> bundle.ingest(STACSource.planetary_computer(), ...)
>>> bundle.to_directory("my_catalog/")
Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/bundle.py
@classmethod
@renamed_kwargs(target_crs="crs", backend="kind")
def empty(
    cls,
    *,
    crs: str | pyproj.CRS = "EPSG:4326",
    kind: CatalogKind = "raster",
) -> CatalogBundle:
    """Create a fresh bundle with an empty items table.

    Use this as the starting point when ingesting from a `Source`:

        >>> bundle = CatalogBundle.empty(crs="EPSG:4326")
        >>> bundle.ingest(STACSource.planetary_computer(), ...)
        >>> bundle.to_directory("my_catalog/")
    """
    dst_crs = pyproj.CRS.from_user_input(crs)
    # The same columns `source_row_to_gdf_row` writes, so an empty
    # bundle has the schema of an ingested one.
    empty_gdf = empty_frame(
        dst_crs,
        {
            "filepath": "object",
            "crs": "object",
            "href_signed": "bool",
            "id": "object",
            "source": "object",
            "collection": "object",
            "assets": "object",
            "properties": "object",
            "provenance": "object",
        },
    )
    catalog = InMemoryGeoCatalog(empty_gdf, kind=kind)
    return cls(catalog, crs=dst_crs, kind=kind)

from_catalog(catalog, *, kind=None) classmethod

Wrap an already-built InMemoryGeoCatalog.

Useful when the user constructed a catalog via build_raster_catalog / build_vector_catalog and now wants to add queries/matchups state.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/bundle.py
@classmethod
@renamed_kwargs(backend="kind")
def from_catalog(
    cls,
    catalog: InMemoryGeoCatalog,
    *,
    kind: CatalogKind | None = None,
) -> CatalogBundle:
    """Wrap an already-built `InMemoryGeoCatalog`.

    Useful when the user constructed a catalog via
    ``build_raster_catalog`` / ``build_vector_catalog`` and now
    wants to add queries/matchups state.
    """
    return cls(
        catalog,
        crs=pyproj.CRS.from_user_input(catalog.gdf.crs),
        kind=kind if kind is not None else catalog.kind,
    )

from_directory(path) classmethod

Load a bundle from disk. Inverse of to_directory.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/bundle.py
@classmethod
def from_directory(cls, path: str | Path) -> CatalogBundle:
    """Load a bundle from disk. Inverse of `to_directory`."""
    from geocatalog._src.storage.parquet import from_geoparquet

    src = Path(path)
    if not src.is_dir():
        raise NotADirectoryError(
            f"CatalogBundle.from_directory expects a directory; got {src!r}. "
            "If the path is a single GeoParquet file, use "
            "`geocatalog.storage.from_geoparquet(path)` to get an "
            "`InMemoryGeoCatalog`, then wrap it with "
            "`CatalogBundle.from_catalog`."
        )
    meta_path = src / "_meta.json"
    if not meta_path.exists():
        raise FileNotFoundError(
            f"CatalogBundle directory {src!r} is missing `_meta.json`. "
            "Was it produced by `to_directory`?"
        )
    meta = json.loads(meta_path.read_text())
    # Schema-version gate: reject artifacts written by a newer
    # bundle layout we don't understand. Forward migrations live
    # alongside the catalog's `_schema_version` chain (parquet.py);
    # for now there's only one version and no migrations.
    artifact_version = meta.get("bundle_schema_version")
    if artifact_version is None:
        raise ValueError(
            f"CatalogBundle directory {src!r} `_meta.json` is missing "
            "`bundle_schema_version`; this bundle predates the version "
            "field. Inspect / rewrite via the geocatalog CLI's "
            "migration tools."
        )
    if int(artifact_version) > BUNDLE_SCHEMA_VERSION:
        raise ValueError(
            f"CatalogBundle directory {src!r} has bundle_schema_version="
            f"{artifact_version!r}, exceeds reader v{BUNDLE_SCHEMA_VERSION}. "
            "Upgrade `geocatalog` to read this bundle."
        )
    try:
        target_crs = pyproj.CRS.from_user_input(meta["target_crs"])
    except (KeyError, pyproj.exceptions.CRSError) as exc:
        raise ValueError(
            f"CatalogBundle directory {src!r} `_meta.json` has no valid "
            f"`target_crs`: {exc}"
        ) from exc
    backend = meta.get("backend", "raster")
    if backend not in ("raster", "xarray", "vector"):
        raise ValueError(
            f"CatalogBundle directory {src!r} `_meta.json` has unknown "
            f"backend {backend!r}"
        )

    catalog = from_geoparquet(src / "items.parquet", kind=backend)
    # Checked for empty bundles too: a later ingest builds rows in
    # `target_crs` and concatenates them onto this table.
    if catalog.gdf.crs is not None and not pyproj.CRS.from_user_input(
        catalog.gdf.crs
    ).equals(target_crs):
        raise ValueError(
            f"CatalogBundle directory {src!r}: items.parquet CRS "
            f"{catalog.gdf.crs} does not match `_meta.json` target_crs "
            f"{target_crs.to_string()}"
        )
    queries = (
        _queries_from_parquet(src / "queries.parquet")
        if (src / "queries.parquet").exists()
        else []
    )
    matchups = (
        _matchups_from_parquet(src / "matchups.parquet")
        if (src / "matchups.parquet").exists()
        else []
    )
    bundle = cls(
        catalog,
        crs=target_crs,
        kind=backend,
        queries=queries,
        matchups=matchups,
    )
    bundle.created_at = meta.get("created_at")
    return bundle

ingest(source, *, bounds, interval=None, collection=None, filters=None, limit=None, primary_asset=None, tag=None, notes=None, on_duplicate='error')

Query a Source and append matching rows to the items table.

Records the call in self.queries with a fresh UUID so every row can be traced back to the call that produced it.

Parameters:

Name Type Description Default
source Source

Any Source Protocol implementer (STACSource, EarthAccessSource, ...).

required
bounds tuple[float, float, float, float]

(xmin, ymin, xmax, ymax) in EPSG:4326.

required
interval Interval | None

Optional time window.

None
collection str | None

Upstream collection id (passed through to Source.query).

None
filters Mapping[str, Any] | None

Adapter-specific filter dict.

None
limit int | None

Cap on the number of rows returned. 0 ingests nothing (no request); None means no cap.

None
primary_asset str | None

Asset key to promote to the catalog's filepath column. None uses the first asset key (dict insertion order).

None
tag str | None

User label persisted in QueryRecord.tag and propagated to every row via provenance['query_tag'].

None
notes str | None

Free-form notes recorded in QueryRecord.notes.

None
on_duplicate Literal['error', 'skip', 'replace']

What to do with a row whose (source, collection, id) — the items table's primary key; upstream ids are only unique within a collection — is already in the bundle or repeats within this ingest. "error" raises before anything is changed; "skip" keeps the existing row (so re-running an ingest is a no-op) and never inspects the discarded one; "replace" keeps the newest one and drops the matchups that referenced the replaced item, since they describe the old data.

'error'

Returns:

Type Description
str

The query_id (uuid4 hex) of this ingest call.

Raises:

Type Description
ValueError

A duplicate id with on_duplicate="error", or an unknown on_duplicate.

KeyError

primary_asset is missing from a row.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/bundle.py
def ingest(
    self,
    source: Source,
    *,
    bounds: tuple[float, float, float, float],
    interval: pd.Interval | None = None,
    collection: str | None = None,
    filters: Mapping[str, Any] | None = None,
    limit: int | None = None,
    primary_asset: str | None = None,
    tag: str | None = None,
    notes: str | None = None,
    on_duplicate: Literal["error", "skip", "replace"] = "error",
) -> str:
    """Query a `Source` and append matching rows to the items table.

    Records the call in ``self.queries`` with a fresh UUID so
    every row can be traced back to the call that produced it.

    Args:
        source: Any `Source` Protocol implementer (STACSource,
            EarthAccessSource, ...).
        bounds: ``(xmin, ymin, xmax, ymax)`` in EPSG:4326.
        interval: Optional time window.
        collection: Upstream collection id (passed through to
            ``Source.query``).
        filters: Adapter-specific filter dict.
        limit: Cap on the number of rows returned. ``0`` ingests
            nothing (no request); ``None`` means no cap.
        primary_asset: Asset key to promote to the catalog's
            ``filepath`` column. ``None`` uses the first asset
            key (dict insertion order).
        tag: User label persisted in ``QueryRecord.tag`` and
            propagated to every row via
            ``provenance['query_tag']``.
        notes: Free-form notes recorded in ``QueryRecord.notes``.
        on_duplicate: What to do with a row whose
            ``(source, collection, id)`` — the items table's primary
            key; upstream ids are only unique within a collection —
            is already in the bundle or repeats within this ingest.
            ``"error"`` raises before anything is changed; ``"skip"``
            keeps the existing row (so re-running an ingest is a
            no-op) and never inspects the discarded one;
            ``"replace"`` keeps the newest one and drops the
            matchups that referenced the replaced item, since they
            describe the old data.

    Returns:
        The query_id (uuid4 hex) of this ingest call.

    Raises:
        ValueError: A duplicate ``id`` with ``on_duplicate="error"``,
            or an unknown ``on_duplicate``.
        KeyError: ``primary_asset`` is missing from a row.
    """
    if on_duplicate not in ("error", "skip", "replace"):
        raise ValueError(
            "on_duplicate must be 'error', 'skip' or 'replace'; "
            f"got {on_duplicate!r}"
        )
    from shapely.geometry import box as _shapely_box

    query_id = uuid.uuid4().hex
    created_at = datetime.now(tz=UTC)
    stamped_rows: list[SourceRow] = []
    for row in source.query(
        bounds,
        interval,
        collection=collection,
        filters=filters,
        limit=limit,
    ):
        # Stamp the bundle's query_id onto the row's provenance so
        # downstream tooling can join items ↔ queries without an
        # extra DataFrame merge. We preserve any provenance the
        # adapter already set (e.g. earthaccess might add its own
        # granule UR or doi).
        prov = dict(row.provenance)
        prov.setdefault("query_id", query_id)
        # Use setdefault so an adapter that already set
        # `query_tag` on the row's provenance wins (consistent
        # with the documented "do not overwrite" contract for
        # query_id). If the user's tag and the adapter's
        # disagree, prefer the more-specific (adapter-set) one.
        if tag is not None:
            prov.setdefault("query_tag", tag)
        stamped_rows.append(dataclasses.replace(row, provenance=prov))
    n = len(stamped_rows)

    # Resolve duplicates before mapping, so rows the policy discards
    # are never validated (a skipped row may lack `primary_asset`).
    existing = _item_keys(self.catalog.gdf)
    stamped_rows = _resolve_duplicates(stamped_rows, existing, on_duplicate)
    new_rows = [
        source_row_to_gdf_row(row, crs=self.crs, primary_asset=primary_asset)
        for row in stamped_rows
    ]
    base = self.catalog.gdf
    if on_duplicate == "replace":
        replaced = {_row_key(r) for r in stamped_rows} & existing
        if replaced:
            keep = [k not in replaced for k in _gdf_keys(base)]
            base = base[keep]
            self._drop_matchups_of(replaced)

    if new_rows:
        new_gdf = gpd.GeoDataFrame(new_rows, crs=self.crs)
        new_gdf.index = pd.IntervalIndex.from_arrays(
            new_gdf.pop("start_time"),
            new_gdf.pop("end_time"),
            closed="both",
            name="datetime",
        )
        merged = pd.concat([base, new_gdf], axis=0)
        self.catalog = InMemoryGeoCatalog(
            gpd.GeoDataFrame(merged, crs=self.crs),
            kind=self.kind,
        )

    self.queries.append(
        QueryRecord(
            query_id=query_id,
            source=getattr(source, "name", "unknown"),
            collection=collection,
            bounds_wkt=_shapely_box(*bounds).wkt,
            time_start=(
                pd.Timestamp(interval.left) if interval is not None else None
            ),
            time_end=(
                pd.Timestamp(interval.right) if interval is not None else None
            ),
            filters_json=json.dumps(dict(filters), default=str) if filters else "",
            created_at=created_at,
            n_returned=n,
            tag=tag,
            notes=notes,
        )
    )
    return query_id

matchups_df()

Return the matchups table as a pd.DataFrame.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/bundle.py
def matchups_df(self) -> pd.DataFrame:
    """Return the matchups table as a `pd.DataFrame`."""
    from geocatalog._src.matchup.engine import MatchupRow

    if not self.matchups:
        return pd.DataFrame(
            columns=[f.name for f in dataclasses.fields(MatchupRow)]
        )
    # geometry_intersect is a shapely geometry — serialize to WKT
    # for the dataframe view so the DataFrame is JSON/Parquet-friendly.
    rows = []
    for m in self.matchups:
        d = dataclasses.asdict(m)
        d["geometry_intersect"] = m.geometry_intersect.wkt
        rows.append(d)
    return pd.DataFrame(rows)

queries_df()

Return the queries table as a pd.DataFrame for ad-hoc analysis.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/bundle.py
def queries_df(self) -> pd.DataFrame:
    """Return the queries table as a `pd.DataFrame` for ad-hoc analysis."""
    if not self.queries:
        return pd.DataFrame(
            columns=[f.name for f in dataclasses.fields(QueryRecord)]
        )
    return pd.DataFrame([dataclasses.asdict(q) for q in self.queries])

to_directory(path)

Persist the bundle as a directory of Parquet files + metadata.

Layout::

<path>/
  items.parquet
  queries.parquet     (omitted when empty)
  matchups.parquet    (omitted when empty)
  _meta.json

Existing files inside path are overwritten. Stale queries.parquet / matchups.parquet from a previous write are removed when the corresponding in-memory list is empty — otherwise from_directory() would silently resurrect rows that should have been dropped.

Every component is first written to a hidden staging directory next to path; only once all of them exist is the bundle published, by swapping that directory in for path (files the bundle does not own are moved across). A reader therefore sees either the previous generation or the new one — never new items beside old queries or metadata — and a failure while writing leaves the previous bundle untouched. created_at records the first save and survives later ones; updated_at is the latest.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/bundle.py
def to_directory(self, path: str | Path) -> None:
    """Persist the bundle as a directory of Parquet files + metadata.

    Layout::

        <path>/
          items.parquet
          queries.parquet     (omitted when empty)
          matchups.parquet    (omitted when empty)
          _meta.json

    Existing files inside ``path`` are overwritten. Stale
    ``queries.parquet`` / ``matchups.parquet`` from a previous
    write are *removed* when the corresponding in-memory list is
    empty — otherwise `from_directory()` would silently
    resurrect rows that should have been dropped.

    Every component is first written to a hidden staging directory
    next to ``path``; only once all of them exist is the bundle
    published, by swapping that directory in for ``path`` (files the
    bundle does not own are moved across). A reader therefore sees
    either the previous generation or the new one — never new items
    beside old queries or metadata — and a failure while writing
    leaves the previous bundle untouched.
    ``created_at`` records the first save and survives later ones;
    ``updated_at`` is the latest.
    """
    from geocatalog._src.storage.parquet import to_geoparquet

    dest = Path(path)
    dest.parent.mkdir(parents=True, exist_ok=True)
    now = datetime.now(tz=UTC).isoformat()
    created_at = self.created_at or _existing_created_at(dest) or now
    meta = {
        "bundle_schema_version": BUNDLE_SCHEMA_VERSION,
        # On-disk keys keep their names (no bundle-schema change).
        "target_crs": crs_config_string(self.crs),
        "backend": self.kind,
        "created_at": created_at,
        "updated_at": now,
    }
    token = uuid.uuid4().hex
    staging = dest.with_name(f".{dest.name}.{token}.new")
    staging.mkdir()
    try:
        to_geoparquet(self.catalog, staging / "items.parquet")
        # Sidecar tables are written only when non-empty, so the
        # directory matches the in-memory contract (empty = omitted).
        if self.queries:
            _queries_to_parquet(self.queries, staging / "queries.parquet")
        if self.matchups:
            _matchups_to_parquet(self.matchups, staging / "matchups.parquet")
        (staging / "_meta.json").write_text(json.dumps(meta, indent=2))
    except BaseException:
        shutil.rmtree(staging, ignore_errors=True)
        raise
    _publish_directory(staging, dest, owned=_BUNDLE_FILES, token=token)
    self.created_at = created_at

write_matchups(rows, *, tag=None)

Persist a stream of MatchupRows into the bundle.

Parameters:

Name Type Description Default
rows Iterable[MatchupRow]

Iterable of MatchupRow (typically the output of geocatalog.matchup.matchup(...)).

required
tag str | None

Optional query_set override applied to every row. When None, each row keeps its own query_set.

None

matchup_id is the table's key: a row whose id is already in the bundle replaces the stored one in place (so re-running a deterministic matchup does not duplicate it, and a re-run under another tag moves it to that query_set).

Returns:

Type Description
int

How many rows were written (added or replaced).

Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/bundle.py
def write_matchups(
    self,
    rows: Iterable[MatchupRow],
    *,
    tag: str | None = None,
) -> int:
    """Persist a stream of `MatchupRow`s into the bundle.

    Args:
        rows: Iterable of `MatchupRow` (typically the output of
            ``geocatalog.matchup.matchup(...)``).
        tag: Optional ``query_set`` override applied to every
            row. When ``None``, each row keeps its own
            ``query_set``.

    ``matchup_id`` is the table's key: a row whose id is already in
    the bundle replaces the stored one in place (so re-running a
    deterministic matchup does not duplicate it, and a re-run under
    another ``tag`` moves it to that ``query_set``).

    Returns:
        How many rows were written (added or replaced).
    """
    position = {m.matchup_id: i for i, m in enumerate(self.matchups)}
    written = 0
    for row in rows:
        mr = dataclasses.replace(row, query_set=tag) if tag is not None else row
        if mr.matchup_id in position:
            self.matchups[position[mr.matchup_id]] = mr
        else:
            position[mr.matchup_id] = len(self.matchups)
            self.matchups.append(mr)
        written += 1
    return written

geocatalog.storage.QueryRecord dataclass

One row of queries.parquet.

Persisted alongside the items so a user can answer "which call produced these rows?" without storing per-row provenance copies.

Attributes:

Name Type Description
query_id str

Stable identifier (uuid4 hex). Matches the _provenance['query_id'] field on every ingested SourceRow for cross-table joins.

source str

SourceRow.source value of the rows that came from this call ("earthaccess", "stac.pc", etc.).

collection str | None

Upstream collection identifier searched.

bounds_wkt str

WKT representation of the search bbox (WGS84).

time_start, time_end

Time-window endpoints; pd.NaT if the call had no temporal filter.

filters_json str

JSON-encoded filters dict; "" if empty.

created_at datetime

When the call completed (UTC).

n_returned int

How many rows the call yielded.

tag str | None

User-supplied label (e.g. "iberia_summer24"); None if the call had no tag.

notes str | None

Free-form text.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/bundle.py
@dataclasses.dataclass(frozen=True)
class QueryRecord:
    """One row of ``queries.parquet``.

    Persisted alongside the items so a user can answer "which call
    produced these rows?" without storing per-row provenance copies.

    Attributes:
        query_id: Stable identifier (uuid4 hex). Matches the
            ``_provenance['query_id']`` field on every ingested
            `SourceRow` for cross-table joins.
        source: ``SourceRow.source`` value of the rows that came
            from this call (``"earthaccess"``, ``"stac.pc"``, etc.).
        collection: Upstream collection identifier searched.
        bounds_wkt: WKT representation of the search bbox (WGS84).
        time_start, time_end: Time-window endpoints; ``pd.NaT`` if
            the call had no temporal filter.
        filters_json: JSON-encoded filters dict; ``""`` if empty.
        created_at: When the call completed (UTC).
        n_returned: How many rows the call yielded.
        tag: User-supplied label (e.g. ``"iberia_summer24"``); ``None``
            if the call had no tag.
        notes: Free-form text.
    """

    query_id: str
    source: str
    collection: str | None
    bounds_wkt: str
    time_start: datetime | pd.Timestamp | None
    time_end: datetime | pd.Timestamp | None
    filters_json: str
    created_at: datetime
    n_returned: int
    tag: str | None = None
    notes: str | None = None