Skip to content

Port the read-only Postgres store to TypeScript - #709

Merged
arrry-hydraDB merged 1 commit into
adityamishra/oss-136-pg-storefrom
adityamishra/oss-136-pg-store-ts
Dec 4, 2026
Merged

arrry-hydraDB merged 1 commit into
adityamishra/oss-136-pg-storefrom
adityamishra/oss-136-pg-store-ts

Conversation

@adityamishra-hydradb

@adityamishra-hydradb adityamishra-hydradb commented Dec 4, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

3/5 of #706. Ports PgHydraDBStore to TypeScript over the pg driver (optional peer dependency), with the same ids, types, statements, and error text as Python.
It has the same review fixes as 2/5: full bigint range, one-time initialize, retry after a failed connect, reserved types, exact names, URI credentials, and one namespace per store.

Implementation details

Door: one-way
New public TypeScript store class and an optional pg peer dependency.

Cleanup: none

What to delete:

Decisions

  • Driver (decided by the maintainers on 2026-12-05): node-postgres (pg), the common pure JavaScript client. It is an optional peer dependency, loaded with loadOptional, so a missing install raises missing_package with npm install pg. The options startup parameter sets default_transaction_read_only=on and statement_timeout; the pool runs no statement when it returns a client.
  • The store runs the same statements as Python, word for word. Integer keys travel as bigint and the walk returns keys as text, so keys above 2^53 keep their value.
  • Options are camelCase, as the other TypeScript stores take them: graph, names, statementTimeout, seedLimit, poolSize. The error text names the Python primitive (upsert_node), so both SDKs give identical messages.
  • The write primitives are declared on the class and defined in one loop, each raising read_only_store.
  • CI (decided by the maintainers on 2026-12-05): #729 adds the CI job 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.
  • The Postgres tests share their setup SQL with Python through tests/fixtures/pg_hydradb_work.sql.
  • The TypeScript every-code test keeps the helper triggers from 1/5, to keep this PR under 1,000 lines; test/pgHydradbStore.test.ts raises each code from the store itself.

Validation

  • New test/pgHydradbStore.test.ts mirrors the Python tests (skipped unless SG_PG_HYDRADB_URI is set): passes on Postgres 16, 17, and 18 with pg_hydradb.
  • The same error text as Python for an unreachable server, a wrong password, and a bad host (checked side by side).
  • Docs repro: npm pack of this branch, installed with pg in an empty folder, ran the TypeScript example of the docs as written against the docs' Docker setup: it printed the draft schema and Ann Lee -[WORKS_AT]-> Acme.
  • TypeScript lint, typecheck, build, and the full test suite with SELFGRAPH_PY: A (main): lint, typecheck, and build pass; 1420 passed, 27 skipped. B (top of the stack): lint, typecheck, and build pass; 1427 passed, 36 skipped, 0 failed, conformance pair included; CI runs the same suites green on every PR. One earlier run of A timed out in conformanceGraph while Docker builds loaded the machine; the rerun passed.
  • precheck, make probes, ruff: precheck --base 2/5: all checks passed; the same conformance warning, answered in 5/5. make probes: plan_apply, secret_echo, and unmerge_order pass; parity_table fails the same way on main and on the branch (vitest cannot parse a .scm query file in this environment). ruff check and ruff format --check: clean.

Limits

Same as 2/5.

Linked issue

Closes #706

AI Assistance

Model Effort
Claude Opus 5.5 High

Checklist

  • Implements an issue a maintainer has /approved.
  • Small and scoped to that issue.
  • New errors have a code and hint, the same on API, CLI, and MCP in both SDKs (see AGENTS.md).
  • Breaking changes described below, or none.

Breaking changes

None.

🤖 Generated with Claude Code

@adityamishra-hydradb

Copy link
Copy Markdown
Collaborator Author

@hydra-mira-review review

@hydra-mira-review

hydra-mira-review Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Mira score 5/5 · 🟢 Good to merge

  • No findings in the code.
  • Confirm outside this PR: Install pg >=8 in applications selecting this store, Provide the expected pg_hydradb registry and walk API and 1 more.
  • Finish the requirement: Raise every error code from the TypeScript store in its dedicated tes…
  • Read these high-risk changes closely: Translate Postgres failures and hide URI credentials.
1 more
  • Not read, excluded by the filter rules: typescript/package-lock.json.

TypeScript applications can read PostgreSQL graphs through a new read-only store. The PR adds an optional pg dependency, preserves Python store behavior, and adds integration tests.

Before this ships · 3 to confirm
  • ❔ Install pg >=8 in applications selecting this store (config), needed in Consuming TypeScript applications. typescript/package.json makes the driver optional, and start raises missing_package when it is absent. Install pg >=8 before configuring an application to use PgHydraDBStore.
  • ❔ Provide the expected pg_hydradb registry and walk API (contract), needed in Target Postgres database. The Python store already uses the same registry queries and walk function; the deployed extension version is not established. Install a compatible extension before enabling the store, including the registry columns and reachable_edges response fields used here.
  • ❔ Register the graph and grant reader access (schema), needed in Target Postgres database. tests/fixtures/pg_hydradb_work.sql demonstrates graph registration, schema usage, and SELECT grants; production registrations and grants are not established. Register the application tables and grant reader access before enabling the store; refresh paused registrations before connecting.
How this PR works · 7 changes, 1 high risk, 5 medium risk, 1 low risk

TypeScript applications can now read existing Postgres tables as a graph without copying their rows into another store. This PR ports the Python store using an optional Postgres driver, registered graph metadata, and bounded reads. It adds the TypeScript layer above the Python store branch.

1. Connect through an optional Postgres driver · 🟠 medium risk · typescript/package.json +2

Applications gain a Postgres store through the public SDK export. PgHydraDBStore loads the optional driver on first use and shares one initialization promise.

Risk: Applications using the new store could fail on first use, fail to recover after connection errors, or retain connections after closing.

Check:

  • Start concurrent first reads and confirm initialization happens once.
  • Fail initialization, restore connectivity, and confirm the same store can initialize successfully.

In package.json:97-101, package.json:159-161, index.ts:220 and 3 more.

2. Build graph types and a schema from registered tables · 🟠 medium risk · typescript/src/stores/pgHydradb.ts

Registered tables become entity and relation types, with a draft schema available to callers. Initialization rejects missing, paused, or unreadable graphs.

Risk: Applications could receive incorrect graph types or schema endpoints, or fail to initialize against valid registered tables.

Check:

  • Check a graph with custom display columns and a relation kind column.
  • Confirm unreadable tables and reserved relation labels fail with graph_unavailable.

In pgHydradb.ts:39-62, pgHydradb.ts:107-109, pgHydradb.ts:162-172 and 1 more.

3. Read entities by exact keys and bounded name searches · 🟠 medium risk · typescript/src/stores/pgHydradb.ts

Applications can fetch entities by ID and search display names without listing every row. Integer keys retain the full signed 64-bit range.

Risk: Entity reads could miss existing rows, return incorrect names, or identify the wrong row when large keys lose precision.

Check:

  • Read keys -9223372036854775808 and 9223372036854775807, then reject an out-of-range key.
  • With seedLimit: 2, confirm an exact Ann lookup survives nearby Annabelle matches and treats wildcard characters literally.

In pgHydradb.ts:116-153, pgHydradb.ts:181-184, pgHydradb.ts:466-609.

4. Walk adjacent relations and expose truncated results · 🟠 medium risk · typescript/src/stores/pgHydradb.ts

Neighbor and path reads can follow registered relations in either direction. Results report truncation when a single seed still exceeds the database walk limits.

Risk: Graph reads could omit relations, attach incorrect endpoints, or present an incomplete neighborhood without warning.

Check:

  • Check incoming and outgoing walks with bigint endpoints and an entity label named relation.
  • Exceed 5,000 edges for one seed and confirm truncation is reported without affecting the next unrelated read.

In pgHydradb.ts:40-43, pgHydradb.ts:63-65, pgHydradb.ts:192-195 and 1 more.

5. Translate Postgres failures and hide URI credentials · 🔴 high risk · typescript/src/stores/pgHydradb.ts

Callers receive SDK error codes instead of raw driver failures. Error messages redact URI credentials and escape control characters.

Risk: Connection failures could expose database credentials in application logs or reach callers under an incorrect error code.

Check:

  • Compare authentication and connection errors with Python for the same failing URI.
  • Check passwords containing encoded characters in both URI user information and query parameters.

How it works:

  1. query sends driver failures through error.
  2. error maps connection, authentication, database, permission, extension, and timeout failures to SDK errors.
  3. redact removes URI credentials and both encoded and decoded password query values.
  4. constructor rejects unencoded user information before opening a connection.

What it touches:

  • typescript/src/stores/pgHydradb.ts: query, loadRegistry.
  • typescript/test/pgHydradbStore.test.ts: password redaction test.
  • Store initialization and every Postgres query.
  • Exceptions carry stable SDK codes and sanitized messages instead of raw driver text.

In pgHydradb.ts:217-220, pgHydradb.ts:395-464.

6. Reject writes and reads requiring full scans · 🟠 medium risk · typescript/src/stores/pgHydradb.ts

Application-owned rows cannot be changed through this store. Writes raise read_only_store; unrestricted entity lists, relation lists, counts, and Cypher raise unsupported_read.

Risk: Unsupported SDK operations could run unexpectedly or fail with inconsistent errors for applications using the read-only backend.

Check:

  • Confirm every GraphPrimitives write method is included in the refusal loop and uses the expected Python error text.
  • Confirm transaction callbacks never run and unrestricted reads return unsupported_read.

In pgHydradb.ts:44-45, pgHydradb.ts:599-602, pgHydradb.ts:709-713 and 1 more.

7. Supporting changes · 🟢 low risk · typescript/src/tables.ts +2

Integration tests cover retrieval, live row updates, read restrictions, initialization, key boundaries, namespace checks, and truncation using the shared Python SQL fixture. words becomes an internal export for schema synonyms; development dependencies supply the driver and its types.

Risk: Regressions could escape detection if the integration database or its extension differs from supported deployments.

Check:

  • Confirm the shared fixture registers the tables and grants only SELECT privileges to the reader.

In tables.ts:35-37, package.json:228-234, pgHydradbStore.test.ts:1-200.

Requirement check · 9 met, 1 partly met · from the PR description
  • ✅ Expose a TypeScript Postgres store using an optional pg dependency (met). typescript/src/index.ts exports the store; typescript/package.json declares optional pg >=8; start loads it through loadOptional.
  • ✅ Preserve the Python store's IDs, graph types, SQL statements, and coded error templates (met). pgHydradb.ts ports the registry queries, key lookups, walk query, encoders, and error branches from src/selfgraph/stores/pg_hydradb.py.
  • ✅ Preserve the full signed bigint range (met). keyOf uses bigint; walk preserves numeric JSON seeds; SQL returns keys as text.
  • ✅ Initialize once and permit another attempt after initialization fails (met). initialize shares its promise and clears it on rejection; start closes the pool after a registry failure.
  • ✅ Reject reserved relation types and preserve exact-name lookup candidates (met). allowed checks labels and row kinds; entitiesMatching submits exact patterns before broader patterns.
  • ✅ Validate URI credentials and keep credentials out of errors (met). constructor calls requireEncodedUserinfo; redact removes URI credentials and encoded or decoded password query values.
  • ✅ Serve exactly one namespace per store (met). open rejects namespaces different from the configured namespace before reading rows.
  • ✅ Use startup read-only settings and refuse write primitives with Python primitive names (met). start configures read-only transactions and timeout; transaction and the prototype loop raise read_only_store.
  • ✅ Share Postgres setup SQL with Python tests (met). typescript/test/pgHydradbStore.test.ts loads tests/fixtures/pg_hydradb_work.sql.
  • 🟡 Raise every error code from the TypeScript store in its dedicated tests (partial). pgHydradbStore.test.ts covers graph failures and read restrictions, but lacks cases for timeout, missing database, and generic query rejection.

Comment @hydra-mira-review help for commands.

@hydra-mira-review hydra-mira-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mira Review Summary

Valid 19-digit bigint IDs can disappear from lookups and traversal, and some Unicode names cannot be found even by exact spelling (pgHydradb.ts). Concurrent initialization can expose an incomplete registry and leak competing pools, while an initial connection failure permanently disables the graph; large neighborhood reads also spend quadratic work grouping edge keys. CI skips every Postgres store integration test (pgHydradbStore.test.ts).

Key Issues

Issue Location
🔴 Valid 19-digit bigint IDs are silently discarded from lookups and traversal. typescript/src/stores/pgHydradb.ts:141
🔴 Concurrent initialization can expose an incomplete registry and leak competing pools. typescript/src/stores/pgHydradb.ts:270
🔴 An initial connection outage permanently closes the store and prevents recovery. typescript/src/stores/pgHydradb.ts:285

Comment thread typescript/src/stores/pgHydradb.ts Resolved
Comment thread typescript/src/stores/pgHydradb.ts Resolved
Comment thread typescript/test/pgHydradbStore.test.ts Resolved
Comment thread typescript/src/stores/pgHydradb.ts Resolved
Comment thread typescript/src/stores/pgHydradb.ts Resolved
Comment thread typescript/src/stores/pgHydradb.ts Resolved
@adityamishra-hydradb
adityamishra-hydradb removed this pull request from stack #711 December 4, 2026 20:47
@adityamishra-hydradb
adityamishra-hydradb force-pushed the adityamishra/oss-136-pg-store-ts branch from cda06bc to a0d61b2 Compare December 4, 2026 20:47
@adityamishra-hydradb

Copy link
Copy Markdown
Collaborator Author

@hydra-mira-review review

@hydra-mira-review hydra-mira-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mira Review Summary

If the store is closed while initialization is in progress, database connections can remain open. This resource leak is in typescript/src/stores/pgHydradb.ts.

Comment thread typescript/src/stores/pgHydradb.ts Resolved
@adityamishra-hydradb
adityamishra-hydradb force-pushed the adityamishra/oss-136-pg-store-ts branch from a0d61b2 to 81f5c0e Compare December 4, 2026 21:19
@adityamishra-hydradb

Copy link
Copy Markdown
Collaborator Author

@hydra-mira-review review

@hydra-mira-review hydra-mira-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mira Review Summary

Graphs with a vertex label named constructor fail to initialize in typescript/src/stores/pgHydradb.ts.

Comment thread typescript/src/stores/pgHydradb.ts Resolved
@adityamishra-hydradb
adityamishra-hydradb force-pushed the adityamishra/oss-136-pg-store-ts branch from 81f5c0e to a65d0a2 Compare December 4, 2026 21:37
@adityamishra-hydradb

Copy link
Copy Markdown
Collaborator Author

@hydra-mira-review review

@adityamishra-hydradb
adityamishra-hydradb force-pushed the adityamishra/oss-136-pg-store-ts branch from a65d0a2 to a681d71 Compare December 4, 2026 21:49
@adityamishra-hydradb

Copy link
Copy Markdown
Collaborator Author

@hydra-mira-review review

@adityamishra-hydradb
adityamishra-hydradb force-pushed the adityamishra/oss-136-pg-store-ts branch from a681d71 to 253216f Compare December 4, 2026 22:00
@adityamishra-hydradb

Copy link
Copy Markdown
Collaborator Author

@hydra-mira-review review

@hydra-mira-review hydra-mira-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mira Review Summary

Retrying initialization in typescript/src/stores/pgHydradb.ts can return rows from tables that have been removed from the graph.

Comment thread typescript/src/stores/pgHydradb.ts Resolved
Signed-off-by: adityamishra-hydradb <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@adityamishra-hydradb
adityamishra-hydradb force-pushed the adityamishra/oss-136-pg-store-ts branch from 253216f to ce8fb6b Compare December 4, 2026 22:11
@adityamishra-hydradb

Copy link
Copy Markdown
Collaborator Author

@hydra-mira-review review

@arrry-hydraDB arrry-hydraDB left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@arrry-hydraDB
arrry-hydraDB merged commit 0adf66c into main Dec 4, 2026
51 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Read Postgres tables through pg_hydradb with a read-only store

2 participants