Repository navigation
Read Postgres tables through pg_hydradb with a read-only store - #708
arrry-hydraDB merged 1 commit into
Conversation
|
@hydra-mira-review review |
Mira score 5/5 · 🟢 Good to merge
Applications can read existing PostgreSQL tables as graph entities and relations through a new read-only Python store. The PR adds optional installation support, database fixtures, and tests for reads and errors. Before this ships · 2 to confirm
How this PR works · 8 changes, 4 high risk, 3 medium risk, 1 low riskApplications can query existing Postgres rows as a graph without copying them into another store. This PR adds a Python store that reads tables registered with pg_hydradb and uses existing retrieval algorithms. It refuses writes and unbounded reads, while leaving TypeScript support and documentation to later parts of the stack. 1. Open a bounded pool with read-only sessions · 🔴 high risk ·
|
There was a problem hiding this comment.
Mira Review Summary
PgHydraDBStore has several read-path issues: valid 19-digit bigint keys are discarded, rows under a vertex label named relation and relations with reserved type names disappear from reads, and substring candidates can hide exact entity-name matches. Concurrent first reads can expose an incomplete registry and leak duplicate pools; connection errors can expose URI query passwords, and CI skips all Postgres integration tests.
Key Issues
| Issue | Location | |
|---|---|---|
| 🔴 | Concurrent initialization exposes an incomplete registry and can leak duplicate pools. | src/selfgraph/stores/pg_hydradb.py:190 |
| 🔴 | Valid 19-digit bigint entity and edge keys are silently discarded. | src/selfgraph/stores/pg_hydradb.py:120 |
| 🔴 | Capped substring candidates can hide an existing exact entity-name match. | src/selfgraph/stores/pg_hydradb.py:372 |
88813b4 to
583597a
Compare
|
@hydra-mira-review review |
583597a to
fa32f08
Compare
|
@hydra-mira-review review |
fa32f08 to
ec238e2
Compare
|
@hydra-mira-review review |
ec238e2 to
d2f0ffc
Compare
|
@hydra-mira-review review |
d2f0ffc to
4d1d632
Compare
|
@hydra-mira-review review |
Signed-off-by: adityamishra-hydradb <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
4d1d632 to
d976b66
Compare
|
@hydra-mira-review review |
Summary
2/5 of #706. Adds
PgHydraDBStore, a read-only store over Postgres tables that a pg_hydradb graph registers, behind theselfgraph[postgres]extra.Rows are entities, edge rows are current relations, and every write raises
read_only_store. Python only; 3/5 ports it to TypeScript, and 5/5 adds the docs page.Implementation details
Door:
one-wayNew public store class, extra, entity and relation id forms (
person:1,relation:works_at:10), and the docs contract for what the store runs.Cleanup:
noneWhat to delete:
Decisions
asyncpg>=0.30). It is native asyncio like the other stores, speaks the binary protocol, and binds$1parameters. 0.30 added the poolresethook, which lets the pool return a connection with noRESET ALLor other reset statement on the user's server.default_transaction_read_only=onandstatement_timeout(10 s default) as startup settings, so every statement runs read-only and noSETis sent. Only fixed statements run: registry reads (hydradb.graphs,graph_vertex_tables,graph_edge_tableswith their catalog rows),hydradb.reachable_edges, key lookupsWHERE <key> = ANY(...), and the name lookupWHERE <name> ILIKE $1 LIMIT $2. Identifiers come only from the registry and are quoted; values are always bound. Key lists bind as one JSON parameter so the driver runs no type introspection query.reachable_edgescall withmax_depth1, soretrieve,neighbors, andfind_pathkeep their own walk and tie-breaking.paths_fromandpaths_betweenare not used: their tie-breaking differs fromfind_path, so results would change between stores. A walk that pg_hydradb cuts is split in halves until one row is cut alone; that row callsmark_partial. 4/5 walks such a row alone on later reads.seed_candidateshook from 1/5: one ILIKE lookup per table and query word, up toseed_limit(200) rows each, then the usual BM25.Schema.from_tablesnames a table (personisPerson,works_atisWORKS_AT).draft_schema()returns them with each table as a synonym and a mapping.names={label: column}, else the first text column calledname,full_name,display_name,title,label,login, orusername, else the first text column. A NULL name shows the key.entities.list,relations.list, counts, raw Cypher) raisesunsupported_readinstead of reading the tables in full.initializeruns once behind a lock; every read waits for the registry. A failed first connect releases the pool without closing the store, so a later call can retry. An edge label or kind whose type Self Graph reserves (PREFERS,HAS_PROFILE, ...) fails withgraph_unavailable, since_opswould hide those relations.namespace=, defaultdefault); a read for another raisesValidationError, so two graphs with different namespaces cannot share one store and read each other's rows.relation:<edge label>:<key>; only that one prefix is stripped, so a vertex or edge label namedrelationstill works.passwordquery parameter as well as the user and password. A URI with an unencoded/,?,#,@,[, or]in its user or password is refused at construction, before anything can echo it.postgres. It builds pg_hydradb from a pinned hydradb commit and runs these gated tests of both SDKs on Postgres 16 and 17. No image goes to a registry.check_answerable(decided by the maintainers on 2026-12-05): it stays refused on this store withunsupported_read, because it must read every row. No version that checks only seed candidates. The docs page lists it under "What is refused".draft_schemareads the pg_hydradb registry and the Postgres catalog, never user rows. #729 changes the AGENTS.md rule to match: a schema draft may read a store's own catalog and registry, never user rows.Validation
Local only, on throwaway Postgres 16.16, 17, and 18.7 in Docker with pg_hydradb built from
hydra-db/hydradbmain. Raw outputs are kept locally inselfgraph-oss136-proof/.from selfgraph.stores.pg_hydradb import PgHydraDBStoreraisesModuleNotFoundError;pip install "selfgraph-0.2.2-py3-none-any.whl[postgres]"warnsselfgraph 0.2.2 does not provide the extra 'postgres'; the docs have no Postgres mention.tests/test_pg_hydradb_store.py(skipped unlessSG_PG_HYDRADB_URInames a Postgres with pg_hydradb) passes on PG 16, 17, and 18. It also covers the review findings: bigint keys at both ends of the range, labels namedrelation, a reservedpreferslabel, an exact name behind more substring matches thanseed_limit, concurrent first reads, and a retry after the graph is registered.retrieve("who works at Acme")retrieve(entity_ids=["person:1"])neighbors("person:1")find_path("person:2", "company:acme")read_only_storegraph_unavailable, not registeredneeds_refresh)graph_unavailable, is pausedtruncated: trueentities.list()unsupported_readno_seeds_matched'; DROP TABLE ...,%,_,\, and a UNION gives no seeds or normal seeds; entity and relation ids with SQL return None ornot_found; a graph registered over a schema, tables, columns, and a label full of quotes andDROPtext reads correctly; row counts are unchanged after each. A login with INSERT, UPDATE, and DELETE grants still only reads; the same session settings refuse a raw INSERT with25006 cannot execute INSERT in a read-only transaction. A login that row-level security applies to getsgraph_unavailablefrom pg_hydradb on a walk. A wrong password givesstore_auth_failedwithout the password. The statement log (log_statement=all) of the final run holds only the four allowed shapes.statement_timeoutgivesTransientErrorstore_busyin 0.07 s. 50 concurrent retrieves on a pool of 4: 0 errors, at most 4 connections, 0 left after close.precheck,make probes(secret_echoclean), ruff:precheck --base1/5: all checks passed, with one warning: the store's error text gets conformance cases in 5/5, once both SDKs have the store.make probes:plan_apply,secret_echo, andunmerge_orderpass;parity_tablefails the same way on main and on the branch (vitest cannot parse a.scmquery file in this environment).ruff checkandruff format --check: clean.Limits
check_answerable,suggest_schema,namespaces, and full listings raiseunsupported_read.Linked issue
Closes #706
AI Assistance
Checklist
/approved.AGENTS.md).Breaking changes
None.
🤖 Generated with Claude Code