Skip to content

Observing a run — geopatcher.observe

Callbacks during split / merge, a resumable record of the processed patches, what a failed patch leaves behind, and strict mode. The observability guide and the on-error / journal recipes show them in use.

from geopatcher.observe import PatchJournal, PatcherHook

Hooks

geopatcher.observe.PatcherHook

Bases: Protocol

Optional callbacks emitted by patcher split and merge operations.

Hook objects may implement any subset of these methods. The patchers dispatch callbacks dynamically, in order, and convert hook exceptions into warnings so observability code cannot interrupt patch generation.

on_patch_start and on_patch_done accept an optional trailing coord_value (or None for integer geometries). _dispatch trims to the callback's actual arity, so single-arg hooks written for the pre-coord protocol still receive only anchor without warnings. See ADR-004 in docs/patcher/decisions.md ("Hook payload extension").

on_patch_skipped fires (instead of on_patch_start / on_patch_done) for each patch a journal already holds, so on_split_start's total is accounted for on a resumed run. on_error receives the original exception — whether the patcher re-raises it or its on_error policy swallows it.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/hooks.py
@runtime_checkable
class PatcherHook(Protocol):
    """Optional callbacks emitted by patcher split and merge operations.

    Hook objects may implement any subset of these methods. The patchers
    dispatch callbacks dynamically, in order, and convert hook exceptions into
    warnings so observability code cannot interrupt patch generation.

    `on_patch_start` and `on_patch_done` accept an optional trailing
    ``coord_value`` (or ``None`` for integer geometries). `_dispatch` trims
    to the callback's actual arity, so single-arg hooks written for the
    pre-coord protocol still receive only ``anchor`` without warnings.
    See ADR-004 in ``docs/patcher/decisions.md`` ("Hook payload extension").

    `on_patch_skipped` fires (instead of ``on_patch_start`` /
    ``on_patch_done``) for each patch a ``journal`` already holds, so
    ``on_split_start``'s total is accounted for on a resumed run.
    `on_error` receives the original exception — whether the patcher
    re-raises it or its ``on_error`` policy swallows it.
    """

    def on_split_start(self, n_anchors: int) -> None: ...

    def on_patch_start(self, anchor: Any, coord_value: Any = None) -> None: ...

    def on_patch_done(
        self,
        anchor: Any,
        runtime_s: float,
        bytes_: int,
        coord_value: Any = None,
    ) -> None: ...

    def on_patch_skipped(self, anchor: Any, coord_value: Any = None) -> None: ...

    def on_split_end(self) -> None: ...

    def on_merge_start(self, n_patches: int) -> None: ...

    def on_merge_end(self, output_bytes: int) -> None: ...

    def on_error(self, anchor: Any, exc: Exception) -> None: ...

geopatcher.observe.UNKNOWN_TOTAL = -1 module-attribute

Journal

geopatcher.observe.PatchJournal dataclass

Append-only local journal keyed by patch anchor.

Anchors may be tuples, lists, dictionaries (string keys), strings, numbers, booleans, numpy scalars or numpy arrays — everything the samplers emit, including spatial.sampler.Explicit(anchors_=np.argwhere(...)) rows. Every anchor goes through normalize_anchor before it is keyed or written, so (np.int64(5), np.int64(10)), np.array([5, 10]) and (5, 10) are one anchor. The journal stores one JSON record per committed patch. Re-opening the same path reconstructs the latest status for each anchor, allowing patcher.split(..., journal=journal) to skip completed work after a crash.

Durability: each commit flushes the Python buffer and calls os.fsync on the file descriptor before returning. The OS may still reorder the directory entry on a power-loss event, so treat the guarantee as "best-effort durable per row" rather than transactional. Re-running a job after a crash skips anchors that have a row with status == "ok"; partially-written trailing rows are dropped by the JSON-decode guard in _load with a warning.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/journal.py
@dataclass(eq=False)
class PatchJournal:
    """Append-only local journal keyed by patch anchor.

    Anchors may be tuples, lists, dictionaries (string keys), strings,
    numbers, booleans, numpy scalars or numpy arrays — everything the
    samplers emit, including ``spatial.sampler.Explicit(anchors_=np.argwhere(...))``
    rows. Every anchor goes through `normalize_anchor` before it is keyed
    or written, so ``(np.int64(5), np.int64(10))``, ``np.array([5, 10])``
    and ``(5, 10)`` are one anchor. The journal stores one JSON record per
    committed patch. Re-opening the same path reconstructs the latest status
    for each anchor, allowing ``patcher.split(..., journal=journal)`` to skip
    completed work after a crash.

    Durability: each ``commit`` flushes the Python buffer and calls
    ``os.fsync`` on the file descriptor before returning. The OS may still
    reorder the directory entry on a power-loss event, so treat the
    guarantee as "best-effort durable per row" rather than transactional.
    Re-running a job after a crash skips anchors that have a row with
    ``status == "ok"``; partially-written trailing rows are dropped by the
    JSON-decode guard in ``_load`` with a warning.
    """

    uri: str

    def __post_init__(self) -> None:
        self.path = Path(self.uri)
        self.path.parent.mkdir(parents=True, exist_ok=True)
        self._rows: dict[str, dict[str, Any]] = {}
        if self.path.exists():
            self._load()

    def has(self, anchor: Any) -> bool:
        """Return ``True`` when ``anchor`` has a successful journal row."""
        row = self._rows.get(_anchor_key(anchor))
        return row is not None and row["status"] == "ok"

    def commit(
        self,
        anchor: Any,
        *,
        status: str,
        runtime_s: float,
        output_uri: str | None = None,
        error: str | None = None,
    ) -> None:
        """Append a durable status row for ``anchor``.

        The row is flushed and ``fsync``-ed before the call returns so a
        process crash after ``commit()`` returns does not lose the record.
        """
        row = {
            "anchor": normalize_anchor(anchor),
            "status": status,
            "runtime_s": float(runtime_s),
            "output_uri": output_uri,
            "error": error,
        }
        key = _anchor_key(anchor)
        with self.path.open("a", encoding="utf-8") as f:
            f.write(json.dumps(row, sort_keys=True))
            f.write("\n")
            f.flush()
            # fsync isn't supported on every filesystem (e.g. some network
            # mounts, tmpfs in container CI). Fall back to the plain flush
            # in that case — the row is still in the OS page cache.
            with contextlib.suppress(OSError):
                os.fsync(f.fileno())
        self._rows[key] = row

    def pending(self, all_anchors: list[Any]) -> list[Any]:
        """Return anchors without a successful journal row."""
        return [anchor for anchor in all_anchors if not self.has(anchor)]

    def completed(self) -> list[Any]:
        """Return every anchor whose latest row has ``status == "ok"``.

        Anchors come back in their journal (JSON-normalised) form — see
        `normalize_anchor`: tuples and numpy arrays as lists, numpy
        scalars as Python numbers.

        Examples:
            >>> journal = PatchJournal("out/run.jsonl")
            >>> journal.commit((0, 0), status="ok", runtime_s=0.1)
            >>> journal.commit((0, 8), status="error", runtime_s=0.1)
            >>> journal.completed()
            [[0, 0]]
            >>> len(journal.completed())  # progress on restart
            1
        """
        return [row["anchor"] for row in self._rows.values() if row["status"] == "ok"]

    def _load(self) -> None:
        with self.path.open(encoding="utf-8") as f:
            for line in f:
                try:
                    row = json.loads(line)
                except json.JSONDecodeError:
                    warnings.warn(
                        f"skipping malformed journal row in {self.path}",
                        RuntimeWarning,
                        stacklevel=2,
                    )
                    continue
                self._rows[_anchor_key(row["anchor"])] = row

commit(anchor, *, status, runtime_s, output_uri=None, error=None)

Append a durable status row for anchor.

The row is flushed and fsync-ed before the call returns so a process crash after commit() returns does not lose the record.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/journal.py
def commit(
    self,
    anchor: Any,
    *,
    status: str,
    runtime_s: float,
    output_uri: str | None = None,
    error: str | None = None,
) -> None:
    """Append a durable status row for ``anchor``.

    The row is flushed and ``fsync``-ed before the call returns so a
    process crash after ``commit()`` returns does not lose the record.
    """
    row = {
        "anchor": normalize_anchor(anchor),
        "status": status,
        "runtime_s": float(runtime_s),
        "output_uri": output_uri,
        "error": error,
    }
    key = _anchor_key(anchor)
    with self.path.open("a", encoding="utf-8") as f:
        f.write(json.dumps(row, sort_keys=True))
        f.write("\n")
        f.flush()
        # fsync isn't supported on every filesystem (e.g. some network
        # mounts, tmpfs in container CI). Fall back to the plain flush
        # in that case — the row is still in the OS page cache.
        with contextlib.suppress(OSError):
            os.fsync(f.fileno())
    self._rows[key] = row

completed()

Return every anchor whose latest row has status == "ok".

Anchors come back in their journal (JSON-normalised) form — see normalize_anchor: tuples and numpy arrays as lists, numpy scalars as Python numbers.

Examples:

>>> journal = PatchJournal("out/run.jsonl")
>>> journal.commit((0, 0), status="ok", runtime_s=0.1)
>>> journal.commit((0, 8), status="error", runtime_s=0.1)
>>> journal.completed()
[[0, 0]]
>>> len(journal.completed())  # progress on restart
1
Source code in packages/geotoolz-patcher/src/geopatcher/_src/journal.py
def completed(self) -> list[Any]:
    """Return every anchor whose latest row has ``status == "ok"``.

    Anchors come back in their journal (JSON-normalised) form — see
    `normalize_anchor`: tuples and numpy arrays as lists, numpy
    scalars as Python numbers.

    Examples:
        >>> journal = PatchJournal("out/run.jsonl")
        >>> journal.commit((0, 0), status="ok", runtime_s=0.1)
        >>> journal.commit((0, 8), status="error", runtime_s=0.1)
        >>> journal.completed()
        [[0, 0]]
        >>> len(journal.completed())  # progress on restart
        1
    """
    return [row["anchor"] for row in self._rows.values() if row["status"] == "ok"]

has(anchor)

Return True when anchor has a successful journal row.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/journal.py
def has(self, anchor: Any) -> bool:
    """Return ``True`` when ``anchor`` has a successful journal row."""
    row = self._rows.get(_anchor_key(anchor))
    return row is not None and row["status"] == "ok"

pending(all_anchors)

Return anchors without a successful journal row.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/journal.py
def pending(self, all_anchors: list[Any]) -> list[Any]:
    """Return anchors without a successful journal row."""
    return [anchor for anchor in all_anchors if not self.has(anchor)]

geopatcher.observe.normalize_anchor(anchor)

Return anchor as plain JSON-compatible Python values.

The one anchor normaliser shared by PatchJournal (rows and keys) and PatchCache (entry keys), so an anchor is the same key however a sampler spelled it:

  • numpy scalars → .item(); datetime64 / timedelta64 → a tagged {"__datetime64__": str} / {"__timedelta64__": str} dict, so they stay JSON-serialisable without colliding with a string anchor ("2024-01-01") or with each other (NaT). Those two keys are reserved: a dict using them is accepted only in exactly that tagged form (it is the datetime's canonical spelling, which journal rows are re-keyed from);
  • numpy arrays → nested lists of normalised elements;
  • tuples and lists → lists;
  • dicts → dicts of normalised values (keys must be strings).

Parameters:

Name Type Description Default
anchor Any

A sampler anchor.

required

Returns:

Type Description
Any

The normalised anchor.

Raises:

Type Description
TypeError

anchor contains a value with no exact JSON form (an arbitrary object, a non-string dict key, a longdouble or complex numpy scalar, a reserved tag key used any other way). There is no str() fallback: two distinct objects with the same repr would otherwise collide.

Examples:

>>> normalize_anchor((np.int64(5), np.int64(10)))
[5, 10]
>>> normalize_anchor(np.array([41, 31]))
[41, 31]
>>> normalize_anchor({"time": np.int32(2), "lat": 0})
{'time': 2, 'lat': 0}
Source code in packages/geotoolz-patcher/src/geopatcher/_src/journal.py
def normalize_anchor(anchor: Any) -> Any:
    """Return ``anchor`` as plain JSON-compatible Python values.

    The one anchor normaliser shared by `PatchJournal` (rows and keys)
    and `PatchCache` (entry keys), so an anchor is the same key however
    a sampler spelled it:

    - numpy scalars → ``.item()``; ``datetime64`` / ``timedelta64`` →
      a tagged ``{"__datetime64__": str}`` / ``{"__timedelta64__": str}``
      dict, so they stay JSON-serialisable without colliding with a
      string anchor (``"2024-01-01"``) or with each other (``NaT``).
      Those two keys are reserved: a dict using them is accepted only
      in exactly that tagged form (it *is* the datetime's canonical
      spelling, which journal rows are re-keyed from);
    - numpy arrays → nested lists of normalised elements;
    - tuples and lists → lists;
    - dicts → dicts of normalised values (keys must be strings).

    Args:
        anchor: A sampler anchor.

    Returns:
        The normalised anchor.

    Raises:
        TypeError: ``anchor`` contains a value with no exact JSON form
            (an arbitrary object, a non-string dict key, a ``longdouble``
            or ``complex`` numpy scalar, a reserved tag key used any other
            way). There is no
            ``str()`` fallback: two distinct objects with the same
            ``repr`` would otherwise collide.

    Examples:
        >>> normalize_anchor((np.int64(5), np.int64(10)))
        [5, 10]
        >>> normalize_anchor(np.array([41, 31]))
        [41, 31]
        >>> normalize_anchor({"time": np.int32(2), "lat": 0})
        {'time': 2, 'lat': 0}
    """
    if isinstance(anchor, np.ndarray):
        if anchor.ndim == 0:
            return normalize_anchor(anchor[()])
        return [normalize_anchor(v) for v in anchor]
    if isinstance(anchor, np.datetime64):
        return {_DATETIME_TAG: str(anchor)}
    if isinstance(anchor, np.timedelta64):
        return {_TIMEDELTA_TAG: str(anchor)}
    if isinstance(anchor, np.generic):
        value = anchor.item()
        if isinstance(value, (bool, int, float, str)):
            return value
        # ``longdouble.item()`` stays a numpy scalar (no exact Python
        # type); ``complex`` has no JSON form. Rounding would collide.
        raise TypeError(
            f"cannot journal / cache an anchor containing a "
            f"{type(anchor).__qualname__} ({anchor!r}): it has no exact "
            f"JSON form; cast it to a Python number first."
        )
    if isinstance(anchor, (tuple, list)):
        return [normalize_anchor(v) for v in anchor]
    if isinstance(anchor, dict):
        if not all(isinstance(k, str) for k in anchor):
            raise TypeError(
                f"anchor dict keys must be strings to be journalled / cached; "
                f"got {anchor!r}"
            )
        reserved = _RESERVED_TAGS.intersection(anchor)
        if reserved:
            # The tagged form is the canonical spelling of a numpy
            # datetime / timedelta (journal rows are re-keyed from it), so
            # accept exactly that and nothing else under those keys.
            if len(anchor) == 1 and isinstance(next(iter(anchor.values())), str):
                return dict(anchor)
            raise TypeError(
                f"anchor dict keys {sorted(reserved)} are reserved for tagged "
                f"numpy datetime / timedelta values; got {anchor!r}"
            )
        return {k: normalize_anchor(v) for k, v in anchor.items()}
    if anchor is None or isinstance(anchor, (bool, int, float, str)):
        return anchor
    raise TypeError(
        f"cannot journal / cache an anchor containing a "
        f"{type(anchor).__qualname__} ({anchor!r}); anchors must be numbers, "
        f"strings, booleans, numpy scalars / arrays, or tuples / lists / "
        f"string-keyed dicts of them."
    )

Errors

geopatcher.observe.PatchErrorRecord dataclass

A failed patch read recorded by a patcher's split.

Parameters:

Name Type Description Default
anchor Any

Key of the patch that failed to build — the anchor, or the patch key ((anchor, k), a (space, time) pair) where a patcher keys its patches more finely.

required
kind str

Exception class name.

required
message str

Exception message.

required
traceback str

Formatted traceback for debugging.

required
retry_count int

Number of retries already attempted for this failure.

required
Source code in packages/geotoolz-patcher/src/geopatcher/_src/walk.py
@dataclass(eq=False)
class PatchErrorRecord:
    """A failed patch read recorded by a patcher's ``split``.

    Args:
        anchor: Key of the patch that failed to build — the anchor, or the
            patch key (``(anchor, k)``, a ``(space, time)`` pair) where a
            patcher keys its patches more finely.
        kind: Exception class name.
        message: Exception message.
        traceback: Formatted traceback for debugging.
        retry_count: Number of retries already attempted for this failure.
    """

    anchor: Any
    kind: str
    message: str
    traceback: str
    retry_count: int

Strict mode

geopatcher.observe.get_strict()

Return the current value of the process-wide strict flag.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/config.py
def get_strict() -> bool:
    """Return the current value of the process-wide ``strict`` flag."""
    return _strict

geopatcher.observe.set_strict(value)

Set the process-wide strict flag.

When True, streaming_safe = False aggregations raise instead of emitting a warning. The flag is read by _warn_if_unsafe_streaming and any future check that wants the same fail-fast contract.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/config.py
def set_strict(value: bool) -> None:
    """Set the process-wide ``strict`` flag.

    When ``True``, `streaming_safe = False` aggregations raise instead
    of emitting a warning. The flag is read by
    `_warn_if_unsafe_streaming` and any future check that wants the same
    fail-fast contract.
    """
    global _strict
    _strict = bool(value)