Skip to content

feat(integrations): read company Postgres data from patches - #218

Merged
allisonmahmood merged 3 commits into
mainfrom
sdk/202-postgres
Sep 12, 2026
Merged

allisonmahmood merged 3 commits into
mainfrom
sdk/202-postgres

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Patches can declare company Postgres connections, but cannot yet read from them.

This adds bounded, read-only Postgres operations using each published version's pinned schema and the connection's live credentials. Generated typed clients and native PGlite fixtures share the same handlers and type mapping. Attributed runtime calls appear in the admin's recent-calls view.

Stacked on #217 (sdk/201-integrations). This PR targets that branch; the earlier runtime, primitive and connection-management work belongs to the parent stack.

Validation

  • pnpm lint
  • pnpm typecheck
  • pnpm test — 572 tests across 62 files
  • Native Postgres execution regressions, generated-client/PGlite smoke, and desktop/mobile connections-page checks
  • Standards and Spec self-review findings resolved

The unmerged 0006_runtime_baseline gains the call outcome field and recent-calls index without a new migration ID. Existing disposable dev databases need a reset.

Closes #202.

Implemented with GPT-6 Astra in Oh My Pi.

@github-actions github-actions Bot added area:server Touches the server area area:ci CI, shared testing infrastructure, development scripts and tooling area:docs Touches the docs area size:l 501-1,000 changed lines labels Sep 10, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Astra review

Reviewed 40654beb451f608d6f891eed8e798ffea3ed3d06 against origin/sdk/201-integrations (d43350bf483b553842af9af52f3d1d34e5b06afc), using #202 and its linked decisions. One pass, no subagents; merge-blocking findings only.

Standards

No merge-blocking method or YAGNI findings.

Spec

[P2][Intent] Preserve fixture parity for arrays of domains

Operations.ts:283–290, together with Mapping.ts:165–173.

#202 requires “domains resolved” and “the fixture layer answers the same list from an agent-authored file.” This breaks for an array of a supported domain:

CREATE DOMAIN public.positive AS integer CHECK (VALUE > 0);
CREATE TABLE public.items (id integer PRIMARY KEY, "values" public.positive[] NOT NULL);

Discovery includes this relation without exclusions and records the array as public._positive, with its element resolved to pg_catalog.int4. Fixture DDL correctly resolves that to int4[], but typeGuardOffset accepts only public._positive: the array's original and base names are identical, so the additional accepted type is never added. Consequently list/get/getMany reject the fixture as source schema drift, even though nothing changed. Selecting only id does not avoid the guard over all columns.

Reproduced: an isolated PGlite database containing the source DDL → actual discovery → shared list handler returns { id: 1, values: [1, 2] }. Passing that same discovered snapshot and an agent-authored INSERT to Dev.dev initializes successfully; query returns the row, but the shared list handler returns shape_mismatch / source_schema_changed.

Fix: make the shared type mapping and drift guard agree on resolved array-element types, preserving production drift detection. Add coverage that takes an actual discovered domain-array snapshot through the fixture and relation handler; separate discovery and fixture tests miss this boundary.

Verification: eight focused offline suites passed, 46 tests. The isolated cross-surface reproduction above exposes behavior those suites do not cover. No repository files changed.

Summary: Standards: 0 blockers. Spec: 1 blocker — a supported domain-array relation cannot be read through its local typed surface.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Code review — PR 218 vs #202

Reviewed sdk/202-postgres (40654be) against sdk/201-integrations, with #202 as the spec (and the #180 Postgres decision it cites).

#202’s intent is not “a Postgres driver.” It is: a published version can run constrained reads through a declared company connection, through the snapshot that version named, with a generated relation client, a local PGlite fixture that shares the same handlers, and an admin recent-calls list. The admitted-at-merge bar is that postgres.* actually run.

That bar is met. The method is mostly the one #180 asked for. The misses are: Dev reimplements execution instead of swapping the source; a timed-out local fixture stays dead; a few surfaces still say this work has not landed.


Standards

(a) Documented standards

  • packages/integrations/src/postgres/Execution.ts:29-31 — InvalidQuery.message returns this.details.message, filled from the Postgres error. Effect service conventions: derive the wrapper message from stable attributes, never cause.message; do not copy defect text into details and then into message. Product/The integration definition, the Postgres integration and its fixture #180 also require the source text on details (sqlstate / message / position). Keep that on details; use a stable wrapper such as “The Postgres query was refused.”
  • packages/integrations/src/postgres/Dev.ts:41-49 — FixtureInvalid does the same (Invalid Postgres fixture ${path}: ${details.message}). Message from path (and sqlstate if useful); raw SQL text stays cause.
  • packages/integrations/src/postgres/Dev.ts:315 — onError(new Error("The local PGlite worker exited.")) manufactures an Error solely for SourceUnavailable.cause. Omit cause or pass the real worker failure.
  • packages/integrations/src/ConnectionPage.ts:154-157 — SqlError fallback is a company-section whose <h2> has no id / aria-labelledby, unlike the success list (aria-labelledby="connection-calls"). ui-consistency: keep the labelled region (and div.note, not p.note).

(b) Judgement (smells; not hard)

  • Mysterious overlapping tags. Operations.Errors unions Execution.Errors with Runtime.AccessDenied / SourceUnavailable / TooLarge. Execution uses those same _tags. catchTags on the union is ambiguous. Prefix Execution tags like the other Postgres* errors.
  • Duplicated Code. Row/byte caps and collection live in Execution.collect and again in the PGlite workerSource string (Dev.ts ~130–132).

Namespace imports, yield* acquisition, catchTags, no runPromise, one-file Execution, no ADR-0009 company-db callers, and no extra CLI surface are fine. makeWithClient is a documented test seam.


Spec

(a) Missing / partial

  • “validated rows for every kind in the mapping.” Operations.test.ts list round-trip covers int2/4/8, numeric, float4/8, text, bool, timestamps, date, jsonb, arrays, enum, domain. It never lists uuid or citext, which Mapping implements and §6 names.
  • “the fixture layer answers the same list from an agent-authored file and names an excluded relation.” postgres/Runtime.test.ts lists through Dev.dev from fixtures/postgres-warehouse.sql. That snapshot has no exclusions. Naming lives in Mapping.test.ts, not on the fixture or generated context.
  • “Raw SQL using something PGlite lacks fails locally with the reason.” Dev.ts special-cases PGLITE → invalid_query / 0A000. No test. Other non-SQLSTATE codes become source_unavailable, so the local reason never appears.

(b) Scope creep

(c) Implemented but wrong

  • Dev timeout vs production. Spec: production and dev “hand the same handlers the same execution dependency; the dev layer swaps only the source.” Native Execution.test.ts destroys the backend on timeout, then a later SELECT 7 works. Dev.ts terminates the worker; Dev.test.ts:236-238 asserts the next SELECT 1 is SourceUnavailable. The local fixture is bricked until the layer is rebuilt. That fails “a statement past 10 s is timeout and the connection is destroyed” on the fixture path — destroy, then the next call should work.
  • Dropped vs retyped column. Spec: “a dropped or retyped column fails that call with a clear code.” Retype is shape_mismatch / source_schema_changed (typeGuardOffset). Drop is invalid_query SQLSTATE 42703 because the guard SQL itself is invalid.

Otherwise the Done-when set is actually tested: INSERT/side-effect 25006; 10s/15s destroy on native; rotation uses the new revision while in-flight keep the old; unkeyed view → offset_exhausted and no get; pinned revision ignores a later refresh; query missing/duplicate/null → shape_mismatch; query SQL logged, list SQL null; recent-calls HTML on the connection detail page. Wire schemas live in packages/api/src/postgres.ts. Vocabulary and docs/product.md § What patch code sees / § Development are updated.


Method

They followed the spec’s handler-sharing method, not “swap only the source.”

Operations.makeHandlers captures Execution + ConnectionStore once (Operations.ts:645-677). Production Execution.layer and Dev.dev both satisfy Execution.query. Server spreads those handlers into Runtime.layer the same way primitives do. Mapping is the one type table. Generate is pure strings. node-pg is the right customer-DB adapter (@effect/sql-pg is the platform DB). Editing unmerged 0006_runtime_baseline is the right migration method for disposable DBs.

Execution.query is a deep interface: {companyId, declaration, text, parameters} → {fields, rows}. Pooling, revision checkout, TLS, cancel, BEGIN READ ONLY, destroy, and collection sit behind it. Operations, Runtime tests, and a test fake all cross that seam — two adapters, so the seam is earned.

Where the method is too big: Dev reimplements the read-only protocol, bounds, and extended-protocol collection inside an eval worker (Dev.ts:93-160). Invariants (read-only tx, 1000/8MiB, 10s/15s, int8-as-text) are not in the type and drift across three adapters (prod, worker, Operations.test PGlite). defineIntegration / operation() are an unused typed bag; Server ignores them and registers makeHandlers directly.

Verdict: reshape the Execution/Dev split. Keep the handler seam, Mapping, node-pg, the killable worker, and the 0006 rewrite. Extract one statement runner so Dev only swaps transport. Do not drop the worker (WASM cannot meet the 15s deadline on-thread) and do not switch to @effect/sql-pg.


YAGNI

The PR works. It is also a second system around the first.

Delete without failing #202:

Delete Why
PATCHY_POSTGRES_* env knobs (Execution.ts:100-116) Spec constants. Generated client documents the spec numbers. Tunable bounds that disagree with the client are extra product surface. Pass limits into make for tests.
ItemLimit, SourceSchemaChanged, extra Execution/Runtime boundary twins One class per wire code. Spec: boundary failures declared once.
Worker portal protocol (Dev.ts:119-138, the 65-line String.raw) Keep the worker; PGlite.query + worker.terminate() on 15s is the smallest honest deadline.
Runtime’s second 15s around Execution’s 15s Spec is one service deadline including queue wait.
checkedBytes after collection Execution already fails during rows.
Three of five fixture error classes Spec needs missing / invalid / excluded.

defineIntegration / operation() are identity functions with one consumer. #180 asked for that record shape; they do not compose the runtime. Keep the plain object; the helpers are not earning their keep until integration #2.

typeGuardOffset (Operations.ts:278-294) is the extra depth: schema drift stuffed into OFFSET so empty pages still fail. Spec’s “done when” is a dropped column (42703). The empty-result type drift suite is the OFFSET trick testing itself.

Query OID allowlists (Operations.ts:565-580) are the mapping table’s third job, living as magic numbers. Spec: one module drives types, projection, and validation. Move the OIDs into Mapping.

Tests are mostly one case per Done-when, which is the right shape. Slop is definition.test.ts and the cancelled-pool-initializer internals test.


Surfaces

Surface
Wire (packages/api → Runtime → docs/API.md) Applied. Browser-only; no CLI --json (correct).
CLI / skill / ADR-0004 Not this ticket (catalog/refresh follow).
Migrations Applied: rewrite of unmerged 0006, already in server / dev runner / vitest template.
Vocabulary / product.md / CONTEXT-MAP Applied.
README.md:13 Missed. Still: “Publish admits resolved Postgres declarations; query operations and higher tiers are still to come.”
docs/DEVELOPMENT.md “How it works” Missed. Runtime still admits only me / tables / shared / files.
.agents/skills/patchy-dev-loop/SKILL.md Missed. Reset still only names 0003_patches_baseline; this PR rewrites 0006.
Company DB / ADR-0009 Not applied (correct): customer Postgres via pg, not company databases.
Reverse states Applied: rotate/retarget/disconnect bump credential revision; RuntimeLog.recent is the way to see calls.

Summary

  • Standards: 4 documented findings, 2 judgement smells. Worst: InvalidQuery/FixtureInvalid copying Postgres defect text into message (tension with The integration definition, the Postgres integration and its fixture #180, which wants that text on details).
  • Spec: 3 partials, 3 creep notes, 2 mismatches. Worst: a timed-out dev fixture stays SourceUnavailable on the next call (Dev.test.ts:236-238), against “destroy the connection” then serve the next one.

Method is keep-and-reshape, not reject. The beautiful version of this PR is the same Execution.query seam with one statement runner, Mapping owning the OIDs, spec constants instead of seven env knobs, and Dev as a transport adapter rather than a second Postgres.

Reviewed with Grok 4.6.

@allisonmahmood

allisonmahmood commented Sep 10, 2026 •

Copy link
Copy Markdown
Owner Author

Reviewed Astra and Grok against the implementation. The three requested merge blockers are fixed in 27de001.

Fixed

  • Domain-array drift / cross-surface regression (Astra): drift compatibility now comes from Mapping and accepts the pinned source type or its native fixture representation. A real PostgreSQL discovery of an integer domain array supplies the same snapshot to native and worker-backed dev handlers. The regression exercises list, get, getMany, selected columns and empty results on both surfaces, plus real retype/drop failures and excluded-relation context.
  • Dead dev worker after a timeout (Grok): interruption destroys the worker; the next call lazily reopens the persisted fixture. The failed statement is not retried. The regression times out a call, then successfully reads the original fixture through the same executor.
  • Duplicate native/dev execution policy (Grok): one statement runner owns the read-only transaction, statement timer, UTC/ISO settings, row/byte collection, rollback/reset and destruction. Native and dev supply transport adapters; the worker no longer owns a second transaction/bounds implementation.
  • Removed PATCHY_POSTGRES_* configuration: production uses the specified constants; tests pass explicit limit arguments. Moved query-result OID compatibility into Mapping.
  • Kept native Postgres diagnostics on structured details; InvalidQuery and FixtureInvalid now have stable wrapper messages. Removed the fabricated worker-exit Error; real emitted errors retain their cause. Execution error tags are namespaced to distinguish them from Runtime errors without changing wire codes.
  • Added UUID/citext round trips and a real local COPY refusal with SQLSTATE/reason. Native and dev now share UTC/ISO setup. Dropped columns/relations produce SourceSchemaChanged for helpers; raw queries preserve the database SQLSTATE.
  • Corrected the call-log SQL-error fallback to a labelled section and an alert div; rendered the actual page through a SQL-fault layer and visually checked the mobile surface with no horizontal overflow.
  • Updated README implementation status, DEVELOPMENT's deployment/How-it-works descriptions, and the dev-loop reset instructions to include 0006_runtime_baseline. No new migration was needed; the internal dev-loop skill has no entry in skills-lock.json.

Kept as-is, with reasons

  • Exact Origin admission: SELECT can invoke functions with side effects; this remains an intentional CSRF boundary, not an assumption that every read-only query is harmless.
  • bpchar / name / char mappings: these are native PostgreSQL text variants needed for supported-source projection compatibility, not additional product features.
  • defineIntegration / operation declarations and their compile checks: these enforce the settled The integration definition, the Postgres integration and its fixture #180/feat(integrations): the integration definition, connections on /company, credentials and discovery #201 contract; replacing them with an ad-hoc map would undo that decision.
  • Worker portal streaming: retained solely as transport so collection bounds and backpressure apply while rows arrive. PGlite.query would fully buffer before enforcing the cap.
  • Runtime and Execution deadlines: the budgets are nested, not additive. Runtime covers admission/metadata/encoding; Execution covers checkout/queue and direct native/dev callers. Removing either weakens a boundary.
  • Final checkedBytes: projected values and the encoded envelope can differ from raw collected rows. The final wire-size check complements the during-collection bound.
  • Structured error categories: fixture validation, item limits and schema drift carry distinct actionable context. The actual tag collision was fixed instead of flattening these contracts.
  • The drift guard, including empty results: retyped columns must invalidate pinned helper semantics even when unselected or no rows match. The shared compatibility fix preserves this contract rather than deleting the guard.
  • Cancelled-initializer regression: it protects a real cross-request cancellation failure and remains meaningful after the shared-runner refactor.

Verification: pnpm lint, pnpm typecheck, pnpm test (574 tests / 63 files) and pnpm format:check all passed. Focused native/dev regressions and the actual SQL-error fallback browser smoke passed. Changes committed and pushed as 27de001.

Latest-commit CI: all seven reported checks passed on 27de001 — test (22), test (24), clerk-live, cli-smoke, lint, dependency-review and label (CI run). GitHub reports no configured required checks for this branch. The PR is mergeable; no newer review findings remain. Not merged.

Base automatically changed from sdk/201-integrations to main September 12, 2026 12:01
…tures

Implements #202: bounded native execution, pinned metadata, generated clients and PGlite fixtures, with attributed runtime logs and recent calls.
@allisonmahmood
allisonmahmood merged commit 28ae591 into main Sep 12, 2026
7 checks passed
@allisonmahmood
allisonmahmood deleted the sdk/202-postgres branch September 12, 2026 12:06
allisonmahmood added a commit that referenced this pull request Sep 12, 2026
Patch repos need matching tooling and browser types, but the CLI was a
separate package and release discovery did not provide an installable
artifact.

Ship the CLI, config builders and browser client together as the private
`patchy` package. The instance serves its immutable tarball with
verified SHA-512 integrity, and shared release checks reject outdated
tooling without disrupting pending publish recovery. Rename mirrors,
ADRs and the skill lock follow the package.

**Stacked on #218 (`sdk/202-postgres`).** This PR targets that branch
and contains only the #203 implementation; merge after its dependency.

Closes #203.

## Verification
- Full offline suite: 604 tests passed across 68 files.
- Packed CLI real-server end-to-end flow passed.
- After review corrections: typecheck, lint, formatting and 69 focused
CLI/release tests passed.
- Standards and spec reviews completed; findings addressed.

Implemented with OpenAI GPT-6 Astra (`openai-codex/gpt-6-astra`) in the
Oh My Pi harness.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:ci CI, shared testing infrastructure, development scripts and tooling area:docs Touches the docs area area:server Touches the server area size:l 501-1,000 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(integrations): the Postgres integration: read-only execution, the generated surface and its fixture

1 participant