Skip to content

feat(integrations): patches can query a company's PostHog, read-only, live in patchy dev too - #662

Merged
allisonmahmood merged 12 commits into
mainfrom
feat/646-posthog-integration
Oct 13, 2026
Merged

allisonmahmood merged 12 commits into
mainfrom
feat/646-posthog-integration

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Oct 13, 2026 •

Copy link
Copy Markdown
Owner

This PR now includes #664 (PostHog dev reads), squashed into this branch as 5cff0e2, so main gets the integration and its live dev reads in one commit. The connect form tells admins that agents read real data while building, which is only true with #664.

Closes #646. Part of #643.

Problem

A patch can read only one kind of outside source, company Postgres. We want internal patches, such as dashboards, to read a company's PostHog project too. #644 made connections integration-aware but left three things for the second integration: typed per-integration variants, the handle-key swap and the snapshot default.

Fix

PostHog is a company-mode, read-only integration with one operation, connections.<alias>.query({ name, query, values, shape }) over HogQL. It is additive within manifest and wire version 1.

  • Connect. A walkthrough on the connections page (mock B7): create a key limited to one project with Read on Query, Event definitions and Property definitions, then paste it with the US or EU region and the project id. It warns before connecting: "While someone builds a patch that uses this connection, their agent reads real PostHog data through Patchy, as them. Nothing is written, and every read appears in recent calls." A test query and discovery run before anything is saved. Refusals sit at their field. Replace key keeps the project; Change project rediscovers.
  • Hosts and bodies. Patchy calls only us.posthog.com and eu.posthog.com, refuses every redirect, and reads bodies, refusals included, under the 8 MiB cap before decoding them.
  • Discovery. Event, event-property and person-property definitions, paged only within the project's own list. Pages, entries and snapshot bytes are bounded in the limits registry; overflow refuses before anything is saved. A description over 1,000 characters is only a hint, so it is cut and marked [truncated], as guest diagnostics are.
  • Query. Patchy builds a default (blocking, cache-aware) HogQLQuery with the name and values. Values are constants for {placeholders}, never interpolated. Results map through a ClickHouse type table, using a small type parser: nullable and low-cardinality unwrap, 64-bit integers only while safe (inside arrays, maps and tuples too), decimals, wide integers and unmapped types need a cast wherever they appear, and DateTime becomes UTC ISO. hasMore: true fails too_large, telling the author to add a LIMIT up to 1,000 or aggregate. HogQL errors are invalid_query, with PostHog's message and no SQLSTATE. Rate, budget and concurrency refusals are one new source_rate_limited code, with retryAfter only when PostHog sent one; the shell broker now forwards it to tier 1 pages. Nothing is retried.
  • Slots. Each process lets 3 queries run per region and project, shared by every connection, connection tests and dev and production calls. A queued call waits within its deadline (keeping a second's reserve), then fails busy with nothing sent. It re-reads the connection after it gets a slot, so it never reaches a project the connection has left.
  • Where it runs. Tier 1 through the broker as the viewer. Tier 2 in actions only, reauthorising the live viewer on every callback; queries, mutations and direct calls from a tier 2 page are refused. Not a live-query dependency. Calls land in recent calls by name ("query dailyRequests") with the first 8 KiB of query text, never values or rows.
  • Error details per integration. A refusal records the operation that made it, and isPatchyError(error, code, from) narrows by an integration (posthog) or one of its operations (posthog.query), whose details it then types; a from that could name either integration doesn't compile. When a tier 2 action relays an integration's refusal, the host restores its operation from its own record of the refusal, so the page still gets PostHog's details. If identical refusals from two integrations make the record ambiguous, it names neither. Callback replies to guests never carry the field, so published bundles, which decode them strictly, are unaffected. Narrowing on the code alone keeps Postgres's details, with sqlstate required, so existing Postgres patches typecheck unchanged after patchy refresh.
  • Variants. A connection's display and a snapshot's metadata are typed per integration. A snapshot decodes by its own row's integration, including after its connection is deleted.
  • Everything else. Publish binding and stale_generated, SDK generation (client, context listing events and properties, patchy-posthog skill, no fixture), patchy add posthog/<handle>, the posthog(handle) builder, list connections posthog/<handle>, the browser client and the tier 2 guest. With feat(patchy): PostHog patches read real data in patchy dev #664, patchy dev reads the real connection, read-only, through POST /api/connections/dev-read (see feat(patchy): PostHog patches read real data in patchy dev #664 and ADR-0013).
  • Release-10 CLIs. They send integrations=all and decode Postgres rows only, so a PostHog row would break their list and add postgres. The integrations query now names what the caller decodes: all and omitted mean Postgres only, and new CLIs send postgres,posthog.

Migrations

0013_handles_per_integration swaps UNIQUE (company_id, handle) for UNIQUE (company_id, integration, handle) in one ALTER TABLE statement, so both keys never hold at once. It also drops the 'postgres' default on connection_snapshots.integration.

The previous release still works. Release 10 and main both connect with a targetless ON CONFLICT DO NOTHING, which resolves on either key, and always name a snapshot's integration. An upgrade suite runs release 10's writes against the migrated schema.

Rolling back. Since #657, connection and call-log readers skip rows of integrations their release doesn't know (docs/OPERATIONS.md). Rolling back to a release with #657 hides PostHog connections, their snapshots and calls, and Postgres keeps working. A patch whose current version declares PostHog still needs this release to serve, so recovering it means rolling forward. Release 10 predates that filter and decodes every connection as Postgres, so don't roll back past #657's release while a PostHog connection exists. Releases before 10 can't run against 0013: their connect names the old key and their snapshot writes omit the integration.

Seeing it work

  • pnpm verify passes on the final commit, rebased on main: format, lint, typecheck, synth, the offline tests, postgres-concurrency, cli-smoke, tier2-smoke and browser.
  • Journeys against an injected PostHog double (src/test/posthog.ts; production hosts and the fetch guard unchanged): the generated tier 1 client, bundled from the packed patchy, over the runtime wire as a signed-in viewer; and a tier 2 action in real workerd through the callback gateway, including one that doesn't catch PostHog's refusal, whose caller still gets operation: "posthog.query".
  • The double covers parameterised, empty and explicit-LIMIT queries, injection-looking values, invalid query, shape mismatch, hasMore, 429 with and without Retry-After, an exhausted budget, a timeout, an endless chunked body, a refused redirect, pagination leaving the project, discovery overflow, and busy slots.
  • Denials: tier 2 queries and mutations, direct calls from a tier 2 page, public versions, undeclared aliases, another company's connection, a disconnected connection, and a viewer deactivated mid-action.
  • In pnpm dev, the connect walkthrough rendered as mock B7: the steps, the region/project/key fields and the warning. A seeded PostHog connection's page showed its project and key hint, "6 events, 2 event properties and 1 person property", Refresh events / Replace key / Change project, and recent calls named "query dailyRequests". The index showed "PostHog · project 12345, US".

Made by Claude Opus 5.5 via Claude Code in T3 Code

@github-actions github-actions Bot added area:server Touches the server area area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:docs Touches the docs area area:integrations Company connections and integration implementations area:ui Portal and first-party browser pages, shared rendering and styles size:xl Over 1,000 changed lines; review in multiple passes labels Oct 13, 2026
@allisonmahmood
allisonmahmood force-pushed the feat/645-connections-page branch from b33d336 to 45018ba Compare October 13, 2026 16:12
@allisonmahmood
allisonmahmood force-pushed the feat/646-posthog-integration branch from 1cb2ccb to c35d527 Compare October 13, 2026 16:26
@allisonmahmood
allisonmahmood force-pushed the feat/645-connections-page branch from 45018ba to 059f9a9 Compare October 13, 2026 19:39
Base automatically changed from feat/645-connections-page to main October 13, 2026 19:50
allisonmahmood added a commit that referenced this pull request Oct 13, 2026
…e, or thirty (#657)

`/company/connections` was a Postgres-only list with the connect form
stacked under it, and each connection's page laid out every admin action
inline. Past a couple of connections nobody could find, scan or fix
anything, and a company with none got no help starting.

This builds direction B v2 from the approved mocks (#643):

- **One table across integrations.** Each row is titled with the name
agents type (`postgres/warehouse`) and shows its source, status, the
live patches that use it and, for admins, its last call. Healthy rows
read Connected in plain text; only problems get a pill, and admins see
disconnected sources named above the table.
- **Controls from nine connections.** Search over names and
descriptions, a source filter, Needs attention and (admins) Unused, as a
GET form and links, so the page needs no script. Filters combine and say
"Showing X of Y" with a way to clear.
- **Used by and Unused follow the deletion rule.**
`ConnectionStore.usage` and `delete` share one SQL fragment, so Unused
is exactly when Delete is offered. A connection no live patch uses but
stored versions still declare reads "None live · 3 retired" or "None
live · 2 older versions".
- **Connect a source** leads to a catalogue (today: Postgres). With
nothing connected, admins get the catalogue inline; members are told
which admins can connect a source. The catalogue invites "Need a source
we don't connect yet? Tell us what you'd use." (a mailto), and
`docs/product.md` no longer promises Patchy builds integrations on
request.
- **One connection page for every integration.** The `patchy add` line,
what patches can read and the latest ten calls (patch and version,
person, call, duration, outcome, with query text and correlation id
under Details) on the left; facts, Added by, Used by and actions on the
right. An integration supplies only its words (`postgres/Page.ts`),
keyed by `Integration`, so #646 must add PostHog's.
- **Risky actions moved to their own pages:** replace credentials, point
elsewhere, edit description, disconnect (naming the patches that lose
access) and delete, like the portal's retire and delete. Refusals land
at the field they're about.
- **Members** see the index without Last call, the attention notice or
Unused, and connection pages without recent calls or actions. They never
read the call log.

Supporting changes: `RuntimeLog.latest` (one index probe per
connection), `ConnectionStore.versions` to name calls' patches, and
`ago` plus the copy line moved into `@patchy/core` so the portal and
this page share them. `docs/product.md` and the integrations glossary
(Catalogue, Unused) are updated. No wire, CLI, migration or skill
change.

**Rollback from the PostHog pair is safe for connections and call
logs.** #657 ships alone, and #662 then #664 follow. If that pair is
released and rolled back to this release, a PostHog connection or a
dev-read call would otherwise fail to decode and break the connections
page, `patchy list connections` and the call logs. Connection and
snapshot reads now filter to the integrations this release ships, and
call-log reads (recent calls, last call, lookup by correlation id, an
invocation's steps) to the credential kinds it records, held in one
const, `credentialKinds` in `packages/runtime/src/RuntimeLog.ts`. A
connection of an unknown integration looked up by id answers not found.
A patch whose current version declares PostHog is outside this: it still
needs that release to serve or roll back (`docs/OPERATIONS.md`).

Not here: the Key rejected status (a follow-up on #643) and PostHog's
facts and connect form (#646).

## Seeing it work

Captures from `pnpm dev shot` as an admin (Ada) and a member (Ben), with
no connections, one, and thirty seeded locally:
https://post.patchyhq.com/d/mauqap0wv9h1 (public but unlisted; local
test data only).

- `ConnectionsView.test.ts` renders thirty connections across fifteen
integrations through fixtures: controls at nine but not eight, source,
search and view filters combining, member visibility and empty states.
- Rows a later release would write (a synthetic integration, a synthetic
credential kind) are inserted straight into the database: lists skip
them, lookups answer not found, and the tests fail without the filters.
- `ConnectionPages.test.ts` runs every Postgres action and its reverse
from its new place against real SQL. It also covers usage (two aliases
count a patch once, retired and foreign versions don't count), member
refusals that never read the log, field callouts, and a directory outage
that leaves the actions working.
- `pnpm verify`: format, lint, typecheck, synth, postgres-concurrency,
cli-smoke, tier2-smoke and browser pass. The offline suite passes on its
own (1671 tests). During verify, 12 untouched CLI and sdk tests timed
out under machine load; they pass on rerun.

Closes #645.

Made by Claude Opus 5.5 via Claude Code in T3 Code

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
allisonmahmood and others added 11 commits October 13, 2026 21:50
…L queries

Connections become per-integration variants; handles are unique per
integration; PostHog's source, operation, wire, runtime, generation and CLI
paths land. Docs, skills and remaining tests follow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…type checks, empty discovery pages

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…follow the type, not its words

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A refusal records the operation that made it. isPatchyError(error, code, from)
narrows by an operation or an integration, so PostHog's invalid_query types its
message only, while narrowing on the code alone keeps Postgres's required
SQLSTATE and existing patches typecheck unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…refused

The host stamps an integration callback's refusal with its operation, so a tier 2
action that relays it, and the broker after it, keep PostHog's details. A from
known only as a string narrows to either integration's details. The broker also
forwards PostHog's retryAfter on source_rate_limited.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… the guest

Published guests decode callback replies strictly, so the operation stays in the
host's record of the refusal and is restored when a guest relays it. isPatchyError
takes an integration or one of its operations, so its details are never a guess.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s certain

Identical refusals from two integrations in one action can't say which one the
action relayed, so neither is named, rather than the first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@allisonmahmood
allisonmahmood force-pushed the feat/646-posthog-integration branch from c35d527 to 263e3cc Compare October 13, 2026 20:21
Stacked on #662. Merge together with #662: PostHog ships once `patchy
dev` can use it.

Closes #647. Part of #643.

## Problem

`patchy dev` runs integrations against local fixtures. That works for
Postgres, because PGlite can stand in for it. It doesn't work for
PostHog: HogQL can't run locally, and a project's events aren't known
ahead of time. Until now `patchy dev` refused PostHog calls, so an agent
couldn't see a PostHog dashboard work before publishing it.

## Fix

Allison decided in #643 that each integration chooses its dev binding.
ADR-0013 records the rule. Postgres keeps fixtures. PostHog, which can't
write and whose shapes can't be known ahead, reads the real connection
in dev, through the instance, as the machine token's person.

- **A separate, narrow endpoint: `POST /api/connections/dev-read`.**
It's bearer-authenticated; the published runtime still refuses bearer
tokens.
- The company, person and machine come only from the token. The
request's `connection { id, handle }` only selects which connection, and
must name a connected PostHog connection of the token's company.
- It runs only the operations an integration's definition lists as
`live`; PostHog lists `query`. Every Postgres operation answers
`invalid_request`.
- It reuses the runtime's bounds: `runtime.posthog.bytes` for the body,
the 15-second `integration.deadline`, the result row and byte bounds,
and the per-project query slots (one `Source`, so dev and published
reads share them). It also shares the runtime's draining.
- It adds a per-person limit at `runtime.calls.perMinute`. The key names
no patch, so naming patches can't widen it. The ApiGuard's per-address
limit still applies first.
- The token is checked again once a read gets its slot, so a key revoked
during a queue wait sends nothing to PostHog.
- **The call log learns dev calls.** Every call with a valid token and
envelope is logged, refused or not: credential kind `machine`, the
machine's id and name, no patch or version. A call whose connection
lookup fails is logged, then refused. The connection page shows these
rows with a **Dev** pill: "patchy dev on <machine>". Another company's
connection id is never recorded.
- **`patchy dev`.**
- PostHog's dev binding (`posthog/Dev.ts`) sends each `posthog.query` to
the endpoint. Both local viewers, and tier 1 broker calls and tier 2
callbacks alike, read as the token's person.
- The instance's refusals reach the patch as it sent them, with the
instance's `correlationId`. A live operation's refusals name it in
`operation`, as #662 has published patches do, so `isPatchyError(error,
code, "posthog")` narrows the same way in dev; rate limits keep
`retryAfter`. The callback gateway now keeps a refusal's own correlation
id, so it survives a workerd action too.
- A refused key fails `access_denied`, naming `patchy login` and a dev
restart. An unreachable instance fails `source_unavailable`, and other
dev work keeps going.
- **The token handoff.** The CLI writes the key to the daemon's stdin,
only when a live integration is declared, and always closes stdin. The
daemon reads it with a size cap and a timeout and keeps it in memory. It
never goes through argv, the environment, `prepared.json`,
`daemon.json`, `dev.log` or workerd. Foreground and detached dev share
this one path.
- **Docs.** ADR-0013, `docs/product.md` (local dev and Integrations ›
Development), ADR-0003 and ADR-0004, the Integrations, Runtime and
Publishing glossaries (**Dev binding**, **Dev read**),
`GLOSSARY-MAP.md`, `docs/DEVELOPMENT.md`, the `patchy-dev-loop`,
`patchy-loop`, `patchy-server`, `patchy-posthog` and global `patchy`
skills (lock hash refreshed), the CLI README, `sdkCapabilities`,
`docs/API.md` and `docs/limits.md`.

## Migration: `0014_runtime_calls_machine`

It adds `'machine'` to `runtime_calls.credential_kind`, plus nullable
`machine_id` and `machine_name` columns. A check requires both machine
fields, and no patch or version, on machine rows, and neither machine
field on other kinds. Existing rows upgrade untouched, and the previous
release's writes still succeed: an upgrade test runs them against the
migrated schema. `machine` joins #657's `credentialKinds`, the one list
every call-log read filters by.

**Rollback is covered by #657's filters.** A release reads only the
credential kinds it knows, so rolling back from this pair hides dev
calls instead of breaking a connection's recent calls. Connection reads
are filtered the same way, by integration.

## The new machine-token endpoint's security posture

- **Authority comes only from the token.** The body only routes the
call. A token of company A naming company B's connection id gets the
same `access_denied` as a missing one, and B's id isn't recorded.
- **It can only read.** It runs only the operations a definition lists
as `live`. The query goes through PostHog's operation, which builds the
request itself; nothing runs on Postgres.
- **The PostHog key never leaves the instance.** The machine token stays
in the daemon's memory.
- **Keys are checked on every call, and again after any queue wait.**
Expired, revoked or idle keys and deactivated people are refused.
- **Bounds and logging match the runtime's.** The body, deadline,
result, slots and draining are the runtime's; there is a per-person and
per-address limit; every call is logged. What's missing compared with
published calls is the company admission token bucket. The per-person,
per-address and per-project bounds cover this endpoint instead.

## Evidence

- `DevReads.test.ts` runs the local binding against the real endpoint on
a socket, over a migrated database and the PostHog double. It covers:
- both viewers reading as the token's person, with the call logged as a
machine call;
  - relayed `invalid_query` and `too_large`;
  - expired, revoked and idle keys and a deactivated person;
  - a disconnected source, and another company's connection;
- Postgres refused; extra arguments and NUL text refused after logging;
an oversized body, declared or streamed (413); and no token (401);
- published and dev reads sharing the three slots, with a key revoked
during the wait sending nothing;
  - a caller that gives up while queued sending nothing;
- an unreachable instance, draining, and the per-person limit across two
machines;
- a read whose log row can't be written, refused before PostHog hears of
it;
- the guard's per-address 429 and a bare 401, from a stub, mapped to
`rate_limited` and the key refusal.
- `devLifecycle.test.ts` runs the real daemon, detached and in the
foreground, against a stub instance. Both mounts' PostHog calls carry
the CLI's key. The key appears in no state file or log, and not in the
daemon's `/proc` cmdline or environ.
- `devExecution.test.ts` runs a tier 2 action in real workerd: it reads
PostHog for both viewers, and a refusal keeps the instance's correlation
id. An action that rethrows the refusal hands its caller `operation:
"posthog.query"`.
- `DevReads.test.ts` also checks that `invalid_query` and a PostHog 429
(`source_rate_limited`, `retryAfter`) name `posthog.query`, and that the
client's `isPatchyError(error, code, "posthog")` narrows them while
`"postgres"` doesn't.
- The call log shows machine calls on the connection page while a
synthetic unknown kind stays hidden (#657's test, extended).
- The connection page renders the Dev marker. The `0014` upgrade test
covers partial machine rows. Dev preparation needs no PostHog fixture
and still checks PostHog metadata. Postgres dev suites are unchanged and
pass.
- Production hosts and the fetch guard are untouched; no real PostHog
project was contacted.
- `pnpm verify` passes on the final commit: format, lint, typecheck,
synth, the offline tests, postgres-concurrency, cli-smoke, tier2-smoke
and browser.

Made by Claude Opus 5.5 via Claude Code in T3 Code

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
@allisonmahmood allisonmahmood changed the title feat(integrations): patches can query a company's PostHog project, read-only feat(integrations): patches can query a company's PostHog, read-only, live in patchy dev too Oct 13, 2026
@allisonmahmood
allisonmahmood merged commit a253cb2 into main Oct 13, 2026
13 checks passed
@allisonmahmood
allisonmahmood deleted the feat/646-posthog-integration branch October 13, 2026 21:23
allisonmahmood added a commit that referenced this pull request Oct 13, 2026
…s and Company pages are easier to use (#667)

Release 11's What's new entry, written through `a253cb2`. It ships as
`patchy` `0.11.0`.

**Changes**
- New: Tools can show your PostHog data (#662, #664)
- Improved: The Connections page stays clear with one connection or
thirty (#657)
- Improved: Find anyone on the Company page (#661)
- New: Invite many people at once (#661)
- Fixed: Browser tabs show Patchy's icon and your tool's name (#660)

**Behind the scenes**
- Each version of Patchy now skips kinds of connection it doesn't know,
so going back to an earlier version stays safe (#657)

**Deploying in two steps.** `c1e7de9` (#657 and everything before it) is
released first, with no entry of its own. Then main is released with
this entry. A rollback from the PostHog release therefore lands on a
release that hides PostHog connections and dev-read calls instead of
failing on them. Global CLIs and patch repos on `0.10.0` are told to
upgrade, as on any release.

Made by Claude Opus 5.5 via Claude Code in T3 Code

Co-authored-by: Claude Opus 5.5 <[email protected]>
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:cli Touches the cli area area:docs Touches the docs area area:integrations Company connections and integration implementations area:server Touches the server area area:ui Portal and first-party browser pages, shared rendering and styles size:xl Over 1,000 changed lines; review in multiple passes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(integrations): PostHog connections and read-only HogQL for patches

1 participant