Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
93f5a62
fix(databases)!: hash SQL store table names (ITL-1552)
eywalker Nov 28, 2026
dfc8147
fix(databases): preserve SQL append lookups with catalog names
eywalker Nov 28, 2026
b491e18
fix(postgresql): import SQL composition within connector operations
eywalker Nov 28, 2026
c1501bf
feat(databases): version SQL store catalog entries
eywalker Nov 28, 2026
0219524
merge: incorporate main through the API reference fix
eywalker Nov 28, 2026
a9abacf
fix(databases): enforce SQL store catalog ownership
eywalker Nov 28, 2026
7d65090
merge: incorporate main through the pull-request CI update
eywalker Nov 28, 2026
9734092
fix(postgresql): escape schema qualifiers in bound store queries
eywalker Nov 28, 2026
651d3b4
fix(databases): guard pending reads and refuse temporary store schemas
eywalker Nov 28, 2026
35e7055
Merge remote-tracking branch 'origin/main' into eywalker/itl-1552-sql…
eywalker Nov 28, 2026
ba18f17
fix(databases): address CodeRabbit review findings
eywalker Nov 28, 2026
ec26893
fix(databases): preserve metadata validation and mocks
eywalker Nov 28, 2026
b06d9c9
fix(store): normalize SQL paths and release PostgreSQL read locks
eywalker Nov 28, 2026
5b11c51
test(store): pin SQL table name v1 vectors
eywalker Nov 28, 2026
9d0aa19
fix(databases): refuse an invalid SQL path in get_table_schema as the…
eywalker Nov 28, 2026
af4d77a
chore: merge main into the SQL table names branch
eywalker Nov 28, 2026
360f177
Merge remote-tracking branch 'origin/main' into eywalker/itl-1552-sql…
eywalker Nov 28, 2026
293f906
fix(databases): bind SQL store operations to their selected schema
eywalker Nov 28, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions changelog.d/ITL-1552.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
### Breaking changes and migration

- SQLite and PostgreSQL stores now name record tables using a readable path hint
and a digest of the full path. Existing tables under the old names stay in the
database, but Orcapod omits them from listings and reads their paths as missing.
Rebuild an existing store from its inputs in a fresh SQLite database or
PostgreSQL schema. Orcapod leaves the old tables untouched and does not migrate them.
15 changes: 8 additions & 7 deletions docs/concepts/pipeline-job.md
Original file line number Diff line number Diff line change
Expand Up @@ -243,8 +243,10 @@ A non-null column is created `NOT NULL` and reads back non-null. SQLite refuses
`double` column holding a NaN or `-0.0`, which it would read back as NULL and `0.0`. Any
other type (lists,
structs, dates or timestamps on SQLite, narrower integers and floats, logical types) is
refused. PostgreSQL also refuses a column name or a table name longer than
63 bytes, which it would truncate (`UnstorableTableNameError` for a table). A database on
refused. PostgreSQL also refuses column names and explicit table identifiers longer than
63 bytes, which it would truncate (`UnstorableTableNameError` for a table).
SQLite and PostgreSQL stores generate table names within 63 bytes from the node's
path, using a readable hint and a digest of the full path. A database on
`SpiralDBConnector` refuses every write for now (`SpiralDBWriteNotSupportedError`): Orcapod
reads SpiralDB only. The full list,
type by type, is [Data types per database](../reference/database-types.md).
Expand All @@ -265,11 +267,10 @@ is attached to them, before anything runs:
An operator cache or cached source on a SQL connector is also refused when it is written, before
anything is stored, if one of its own columns has a type or name the connector does not store. On
PostgreSQL that is every operator cache with caching on: its system-tag column names
(`_tag_source_id::` and a 64-character hash) are longer than 63 bytes.
A table's name is its Orcapod path joined by `__`, and every node table and cached source path
holds a 64-character hash, so on PostgreSQL only tables you write through `ConnectorArrowDatabase`
yourself under short paths fit; reading an existing table with `PostgreSQLTableSource` is
unaffected. Use
(`_tag_source_id::` and a 64-character hash) are longer than 63 bytes. Connector store table names
use a readable path hint and a digest of the full path, so long paths fit the SQLite and PostgreSQL
table-name limits. These generated names do not change the separate column-name restrictions.
Reading an existing table with `PostgreSQLTableSource` is unaffected. Use
`InMemoryArrowDatabase` or `DeltaTableDatabase` for such jobs. Storing these columns on
connector databases is planned for a later release.

Expand Down
16 changes: 16 additions & 0 deletions docs/dev/design_issues/ITL-1552-CA4.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
## `src/orcapod/databases/connector_arrow_database.py`

### CA4 — Distinct paths could share a SQL record table
**Status:** resolved
**Severity:** critical
**Issue:** ITL-1552

Path sanitization could turn distinct paths into the same table name and let one
write overwrite the other's rows. PostgreSQL also refused names beyond 63 bytes.

**Fix:** Both SQL backends use a 63-byte budget for the path hint and digest. A
versioned catalog keeps the original paths so lookups can refuse name collisions.
SQL stores normalize string subclasses before validating path components or
matching prefixes, so subclass methods cannot change which path a table uses.
PostgreSQL catalog reads and flush transactions use the schema selected for the
operation, even if another connection makes an earlier search-path entry available.
14 changes: 14 additions & 0 deletions docs/dev/plans/itl-1552-sql-table-names.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# ITL-1552 SQL store table names

1. Reproduce the table-name collision through the SQLite store and add a
PostgreSQL integration test for long Unicode paths.
2. Extract the readable hint and canonical path digest from PR 589 into a shared
naming helper with caller-supplied length limits. Verify the helper against
one of PR 589's name examples.
3. Apply the approved identifier budget and path listing design to the SQL
stores. Test that another connection can list and read the tables and that
the stale-table check finds older layouts and result revisions under the
node name. Test that tables written under the old names are ignored and
preserved.
4. Document the required store rebuild and record the digest in the hash site
inventory. Run the targeted suites, lint, type checks, and golden check.
1 change: 1 addition & 0 deletions docs/reference/hashing.md
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,7 @@ test session with `-p tests.test_hashing.hash_site_trace`.
| user-class identity | a class's identity record | SHA-256 hex prefix | extension name `name@<fingerprint>` (a name) | `logical_types/user_class_identity.py:identity_string` |
| database registry key | a database config, canonical JSON | SHA-256 hex, 8 digits | `db_<hex>` key in a saved job (a name) | `pipeline/serialization.py:DatabaseRegistry._make_key` |
| SpiralDB schema table digest | the scope and the rows of a dataset's schema table, canonical JSON with the stored schema bytes | SHA-256 hex | completion marker of the schema table (a checksum of stored rows) | `databases/spiraldb_schema_table.py:rows_digest` |
| Connector store table name | the full store path, as a compact UTF-8 JSON array of path components | SHA-256 hex, `spiral_table_name_v1` (`SPIRAL_TABLE_NAME_LABEL`) | the bare hexadecimal suffix in a table name, with a length set by the backend | `databases/store_table_names.py:store_table_digest` |
| synthesized struct class name | the field signature | MD5 hex, 8 digits | a Python class name (a name) | (not reached by a traced test) `semantic_types/universal_converter.py` |
| random ids | nothing | `uuid4`, `uuid7` | run ids, datagram and record uuids, observer ids, correlation keys | (not hashes) |
| unused code | Arrow tables | SHA-256, SHA3, BLAKE2b | no caller; removal is ITL-1156 | (not reached) `hashing/arrow_utils.py`, `hashing/arrow_serialization.py` |
Expand Down
140 changes: 140 additions & 0 deletions src/orcapod/databases/_sql_store.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
"""Catalog contract for SQLite and PostgreSQL connector stores."""

from __future__ import annotations

import json
from contextlib import AbstractContextManager
from typing import TYPE_CHECKING, Protocol, cast, runtime_checkable

from orcapod.errors import OrcapodDatabaseError
from orcapod.types import ColumnInfo

if TYPE_CHECKING:
import pyarrow as pa

STORE_PATH_LAYOUT_VERSION = 1
# Quoted as one identifier. The dots keep this name outside the grammar for
# both old and current record table names.
STORE_PATH_CATALOG = f"orcapod.store_paths.v{STORE_PATH_LAYOUT_VERSION}"
TABLE_PATH_ENTRY_KIND = "table"

# A table entry uses an empty entry_name and holds the path as canonical JSON.
# A future column entry can key its mapping by the physical column name.
STORE_PATH_CATALOG_FIELDS = """(
table_name TEXT NOT NULL,
entry_kind TEXT NOT NULL,
entry_name TEXT NOT NULL,
entry_value TEXT NOT NULL,
layout_version INTEGER NOT NULL CHECK (layout_version = {layout_version}),
PRIMARY KEY (table_name, entry_kind, entry_name)
)"""


@runtime_checkable
class SQLStoreConnector(Protocol):
"""SQL operations a connector store needs to track record table ownership."""

def get_current_store_schema(self) -> str:
"""Return the persistent schema selected for this store operation."""
...

def get_store_table_paths(
self, name: str, *, exact: bool = False, schema: str | None = None
) -> list[tuple[str, str, str]]:
"""Return schema, physical name and stored JSON path for each record table."""
...

def store_table_transaction(
self, table_name: str, path_json: str, *, schema: str
) -> AbstractContextManager[tuple[str, bool]]:
"""Verify or register a path and yield its schema and table existence."""
...

def get_column_info(
self, table_name: str, *, schema: str | None = None
) -> list[ColumnInfo]:
"""Inspect the columns of a table in the verified schema."""
...

def create_table_if_not_exists(
self,
table_name: str,
columns: list[ColumnInfo],
pk_column: str,
*,
schema: str | None = None,
) -> None:
"""Create a record table in the verified schema."""
...

def upsert_records(
self,
table_name: str,
records: pa.Table,
id_column: str,
skip_existing: bool = False,
*,
schema: str | None = None,
) -> None:
"""Write rows to the record table in the verified schema."""
...


def catalog_name_pattern(name: str) -> str:
"""Escape a physical name prefix for a SQL LIKE expression with escape '!'."""
return name.replace("!", "!!").replace("_", "!_").replace("%", "!%") + "%"


def require_catalog_layout(table_name: str, layout_version: object) -> None:
"""Refuse to interpret a table entry in an unsupported catalog layout."""
if layout_version != STORE_PATH_LAYOUT_VERSION:
raise OrcapodDatabaseError(
f"Table {table_name!r} uses unsupported catalog layout version "
f"{layout_version!r}; this client supports version {STORE_PATH_LAYOUT_VERSION}"
)


def stored_path(table_name: str, path_json: str) -> tuple[str, ...]:
"""Decode the original path, refusing an unreadable catalog entry."""
try:
value: object = json.loads(path_json) # pyright: ignore[reportAny]
except (TypeError, ValueError) as exc:
raise OrcapodDatabaseError(
f"Table {table_name!r} has an unreadable stored path"
) from exc
if isinstance(value, list):
components = cast("list[object]", value)
if components and all(isinstance(part, str) for part in components):
return tuple(cast("list[str]", components))
raise OrcapodDatabaseError(f"Table {table_name!r} has an invalid stored path")


def require_store_table_owner(
table_name: str,
expected: tuple[str, ...],
actual: tuple[str, ...],
) -> None:
"""Refuse to open the table for a different path with the same name."""
if actual != expected:
raise OrcapodDatabaseError(
f"Table {table_name!r} already belongs to path {actual!r} and cannot be used for {expected!r}"
)


def require_catalog_pair(
table_name: str, has_table: bool, recorded_path: str | None, path_json: str
) -> None:
"""Refuse inconsistent ownership before creating or changing either object."""
if recorded_path is None:
if has_table:
raise OrcapodDatabaseError(f"Table {table_name!r} has no stored path")
return
require_store_table_owner(
table_name,
stored_path(table_name, path_json),
stored_path(table_name, recorded_path),
)
if not has_table:
raise OrcapodDatabaseError(
f"Stored path for table {table_name!r} has no record table"
)
Loading
Loading