Skip to content

feat(analytics): record runtime outcomes and refusals - #419

Merged
allisonmahmood merged 2 commits into
mainfrom
tier2/388-wide-events
Oct 1, 2026
Merged

allisonmahmood merged 2 commits into
mainfrom
tier2/388-wide-events

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Runtime calls lacked a single record tying their identity, operations, refusals and timing together, making failures and limit usage hard to inspect.

This adds scoped wide events that finalize once on success, failure or interruption. Runtime call and bytes routes emit to stdout and the shared PostHog client without waiting for delivery. Attribution comes from trusted runtime state, local output is compact, and the five event schemas are ready for the later emitters.

Stacked on tier2/387-limits-registry; this PR intentionally targets that branch, not main. Implements the observability work in #384 §14.

Closes #388.

Verification

  • pnpm typecheck and pnpm lint passed.
  • pnpm test --maxWorkers=2: 1,014 tests passed across 88 files.
  • Real-server smoke: four requests produced four stdout events; the PostHog SDK delivered the first three exactly once to a local collector, and a request still succeeded with the collector unavailable.
  • Standards and spec reviews completed; both findings were fixed.

Implemented with OpenAI GPT-6 Astra using omp.

@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:primitives Patch tables and files area:integrations Company connections and integration implementations size:xl Over 1,000 changed lines; review in multiple passes labels Sep 28, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Astra review

Reviewed 145d878...6b0f675 against origin/tier2/387-limits-registry, issue #388 and spec #384 §14. One pass, no subagents. Merge blockers only.

Standards

No blocking method or YAGNI findings. The five emitter schemas and later enrichment fields are explicitly requested, not speculative additions.

Spec

  1. [P2] Intent: classify capacity refusals as refusals, not execution failures. In RuntimeApi.ts:54–64, error.status >= 500 assigns outcome: "failure" to busy. Both existing table and file capacity errors use HTTP 503. Issue feat(analytics): wide events: the accumulator, the stdout and PostHog sinks, the request event on runtime routes #388 requires request events with "the operation names, outcome, refusal code and limit id"; Tier 2: hosted server code, live sync and the execution service #384 distinguishes capacity admission refusals from failed execution.

    Reproduced through the real HTTP route with the existing TableBusy error: tables.list returned HTTP 503 with code: "busy", and its event contained {"outcome":"failure","code":"busy"}. Normal capacity refusals therefore inflate execution-failure counts and disappear from outcome = refused queries. Classify by runtime refusal semantics rather than HTTP status alone, preserving the separate failure and unknown-outcome cases. Add a capacity-refusal case to the existing runtime-event coverage.

Verification: isolated real-HTTP smoke with fixture identity/version and a failing PostHog client. Six requests covering success, invalid operation, capacity refusal, source failure, and PUT/GET bytes produced exactly six stdout events; PostHog failures left the expected responses unchanged. No production or running development instance was touched.

Summary: Standards 0 blockers, no blocking method/YAGNI issue; Spec 1 blocker, P2 incorrect capacity-refusal outcome.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Opus review

Two findings, most severe first. Neither is a runtime bug: the accumulator, the finalizer, the detached best-effort delivery, the shared PostHog client and the refusal paths all hold up. Both findings are about the event's field meanings. Those meanings get baked into PostHog data, and #393, #396 and #399 build on them.

1. Intent: tier 1 requests put the operation name in handler, and kind mixes two vocabularies

  • packages/runtime/src/Runtime.ts:373 enriches { handler: input.op, kind }.
  • packages/runtime/src/RuntimeApi.ts:148 does the same for files.put / files.get.
  • packages/analytics/src/WideEvents.ts:40 widens kind to read | mutation | integration | query | action.

The issue lists "operation names" and "handler name" as separate things. r304 §3 says the request event "names each operation (tables.insert, …)" through the operation list. The spec (§1, §14) reserves handler and kind for a tier 2 patch's own server functions (query / mutation / action). A tier 1 request has no handler, and the rule is that absent fields are "omitted, never borrowed".

What goes wrong: every tier 1 event reports handler: "tables.get", which duplicates operations: ["tables.get"]. Once tier 2 lands, a PostHog breakdown by handler mixes Patchy's own operations with patch-authored handlers. kind: "mutation" then means two different things (a table-write operation, or a transactional handler). Nothing on the event says which one you have except tier.

Fix: for tier 1, leave handler unset and record the name only through WideEvents.operation. Either leave kind off tier 1 events or give the operation kind its own field. Keep kind to the handler kinds. formatDev already falls back from handler to operations (WideEvents.ts:357), so the dev line doesn't change. RuntimeEvents.test.ts:97 and :241 would need to assert operations in place of handler.

2. Vocabulary surface: two different "deployment revisions" in one record

WideEvents.ts:374 adds a top-level deploymentRevision from the new PATCHY_DEPLOYMENT_REVISION variable, meaning which build or deploy is running. The same event's limits[].configRevision.deploymentRevision (WideEvents.ts:29, from #387) is something else: the SHA-256 of the resolved operating-limit values. docs/limits.md defines "deployment revision" as that config hash and says "there is no operator-maintained revision variable". This PR adds exactly such a variable under the same name.

No glossary defines the new meaning. Per CLAUDE.md "Vocabulary and product shape", a new concept goes into its owning CONTEXT.md. Rename one of them (for example the event field and env var to release / PATCHY_RELEASE_REVISION, or the limits one to operatingRevision), or at least add a glossary line under Analytics that tells the two apart. A rename is cheap now and expensive once PostHog holds data.

Checked, no finding

  • The issue's done-when conditions: exactly one request event per tier 1 call, refusals carrying code and limit id (including before admission and for oversize bodies), a hanging or broken PostHog sink or stdout sink leaving the response unchanged, and events on failure, defect and interruption.
  • Attribution comes only from the loaded version and authenticated session.
  • Unknown operation names and request bodies stay out of the event.
  • Nested hops link parent and trace without inheriting attribution.
  • One PostHog client and one bounded shutdown flush are shared with Analytics.
  • The request scope stays open.
  • The dev daemon's stdout goes to dev.log, not to CLI --json output.
  • ApiGuard passes runtime routes straight to the handler, so no refusal skips the event.
  • The packed CLI bundles only the effect-only ./wide-events subpath.
  • Docs and skills surfaces: ADR-0004, the CLI README, both dev-loop skills, DEVELOPMENT.md, product.md, CONTEXT-MAP.md, and the Analytics and Runtime glossaries. "Readers stay unwatched" is retired.
  • Locally, pnpm typecheck and pnpm lint pass, as do the analytics and runtime suites, FilesApi.test.ts, the integrations Runtime.test.ts and devServer.test.ts.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Reviewed 6b0f675 against tier2/387-limits-registry, issue 384 §14, the limits decision on issue 304, and issue 388.

Standards

The Effect shape holds. withEvent takes Sink and metadata from the environment, enrichment outside a hop is a no-op, and the package does not call runPromise. Server.ts builds Analytics.layer and WideEventsPostHog.layer from the same PostHogClient.layer, and the shared-client test locks a single acquisition and a single shutdown.

WideEvents.ts holds both the WideEvents tag and the Sink tag. Production composes WideEventsPostHog.layer. Sink has two adapters, dev stdout and PostHog, and one consumer. Leave it in this module.

SinkError is never constructed. Both sinks catch into void, and bestEffort catches the rest. write can return Effect<void>. Keep the as WideEvent cast. The finalizer already copies only keys on that emitter's schema, and a thrown encode runs on the detached fiber, after the response.

The old Analytics.ts header said a served patch is not an event, and that visits are counted in the database and never reported. Issue 388 tells this PR to retire "readers stay unwatched" and to allow viewer ids on runtime work. The visit rule is a different sentence. packages/patches/CONTEXT.md still says a visit is never an analytics event. The analytics header and the closed event-name comment no longer say it. Put that sentence back beside the new wide-event comment.

Spec

Issue 388 narrows §14, and the build order puts metering and the rest of the request event on ticket 15. This diff has the accumulator, one emit from the finalizer, stdout plus the shared PostHog client, sampleProbability: 1, the five schemas, and a request event on call, putFile, and getFile. Refusals carry code and limitId. A hanging or dying sink still returns the caller's result. Failure and interrupt still emit. Queue wait, guest time, callbacks, attempts, and commit outcome stay with the later ticket, which matches 388's line that runtime tickets enrich the event.

LimitPeak.configRevision is string | { deploymentRevision, overrideRevision } at packages/analytics/src/WideEvents.ts:27. The registry revision is only that pair, packages/limits/src/OperatingLimits.ts:31. The limits decision says a peak joins to the settings in force. WideEvents.test.ts accepts "one" and "two" as revisions, so a peak stored that way cannot join override history. Drop the string arm. Two strings are enough for the map key. Analytics does not need to depend on limits for that.

WideEventsPostHog.ts:21 sets the PostHog distinct id to the viewer, then the company, then patchy-instance. Company is enriched as soon as the version loads, and viewer only after identity succeeds, Runtime.ts:411. session_expired, shell_outdated, not_available_on_public, and every public call therefore share one distinct id, the company. $process_person_profile: false stops a person profile. It still groups events by distinct id. Business events use the principal or patchy-instance, and the glossary says the principal is the user or the instance. Use the viewer id or INSTANCE_DISTINCT_ID, and keep companyId as a property.

Four schema fields sit outside the emitter sentences in that decision. dbMs and callbackBytes are invocation-row columns. boundSeconds is binding history. The binding event there is spare wait, peak processes, and release cause. peakBufferedBytes is beside the stream bytes field. They can land with the ticket that emits that hop.

patchy dev prints the compact line. layerDev({ json: true }) is tested, and devServer.ts:175 calls layerDev() with no flag. Issue 388 asks for the full record behind --json, and the same bullet assigns wiring that through dev.log to the dev ticket. docs/DEVELOPMENT.md records that handoff. Leave the flag for that ticket.

Issue 388

The ticket's build list is in the code. One record per hop, a finalizer, best-effort stdout and PostHog, probability 1, absent fields omitted, five schemas with only the request event emitted, and "readers stay unwatched" gone from the analytics package. The glossary and docs/DEVELOPMENT.md name the wide event and the local PostHog key.

The done-when cases are in RuntimeEvents.test.ts. A tier 1 me call emits one request event with company, patch, version, viewer, handler, kind, tier, and outcome. A refusal before invocation carries its code. too_large carries limitId. A 503 still emits failure, the code, and duration. Unknown operation names and request bodies stay off the record. Concurrent company and public calls do not swap viewers.

That me case does not assert eventId, traceId, an absent parentId, replica, or deploymentRevision. Those show up on synthetic hops, and layerMetadata has no test. Asserting them on the existing me case would lock the fields 388 names.

.agents/skills/patchy-dev-loop/SKILL.md:195 still says the server has no per-request access log. This server writes one JSON line per runtime call into that log, and docs/DEVELOPMENT.md says pnpm dev logs shows it. The skill edit at line 39 covers patchy dev only. The server sentence should say the runtime lines are there.

Method

A hop is a mutable record in a Context.Reference, closed in onExit, and handed to forkDetach. startImmediately: false is Effect's default. It schedules the sink on the dispatcher, and the daemon flag keeps the request fiber from cancelling that task. The handler does not wait, and delivery is not dropped. enrich and operation as module functions are the API callers should have. The five schemas and sampleProbability: 1 were ordered.

Cut SinkError, the string configRevision arm, and the four extra metric fields. Leave the accumulator, Sink, and the cast.

Pre-decode too_large on /api/runtime/call names the envelope that sets the absolute cap. With the registry defaults that envelope is runtime.batch.bytes. The event copies the limit id the refusal already returns. A body that parses still gets the op-specific id, runtime.call.bytes for me.

Standards: 2 findings. The one to fix is the visit sentence dropped from the analytics header.
Spec: 3 findings. The one that will hurt once events are stored is the PostHog distinct id falling back to companyId.

Review by Grok 4.7, Grok Build.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Addressed the Astra, Opus and Grok Build reviews in 1335f04 (fix(analytics): correct runtime event semantics). Read the conversation, submitted review bodies and inline-review endpoints; all three reviews were conversation comments, with no submitted or inline reviews.

Fixed

  • Astra: capacity refusals. Outcomes now follow runtime codes, not HTTP status. busy is refused; source_unavailable and timeout remain failure; unknown_outcome stays separate. HTTP statuses and response bodies are unchanged. Route regressions cover those distinctions and retain the refusal limit ID.
  • Opus: handler vocabulary. Tier 1 records put known operation names only in operations, omitting handler and kind. The schema reserves kind for query | mutation | action. JSON and bytes-route tests cover omission; internal operation metadata is unchanged.
  • Grok: limit configuration revisions. LimitPeak.configRevision now requires { deploymentRevision, overrideRevision }, matching the registry. Tests reject string/incomplete revisions and distinguish peak measurements across either revision component.
  • Grok: PostHog identity. The distinct ID is the viewer when known, otherwise patchy-instance. companyId remains a property and never becomes the principal. Tests cover both viewer and anonymous events without person profiles.
  • Grok: unused declarations. Removed SinkError and its unused error channel, plus dbMs, callbackBytes, boundSeconds and peakBufferedBytes. No emitter consumed them; later owners can add measured fields when they implement those hops. Defects and unavailable sinks remain isolated from callers.
  • Grok: visit wording. Restored the distinction that serving a page is not a business analytics event and visits are database counts. Runtime wide events can still carry viewer IDs; the retired "readers stay unwatched" promise stays retired.
  • Grok: request metadata coverage. The existing tier 1 me route now verifies configured replica/deployment revision, event-ID format, root trace linkage and absent parent ID.
  • Grok: dev-loop skill. Corrected the stale no-access-log sentence. pnpm dev logs includes JSON events for runtime call and file-byte routes; it is not an all-routes access log.

Kept as is

  • Opus: deployment revision names. Kept the spec's top-level deploymentRevision and PATCHY_DEPLOYMENT_REVISION. Added the Analytics glossary definition and development-doc distinction: this identifies the running host build; limits[].configRevision.deploymentRevision is the automatic operating-config fingerprint. The latter still has no operator-maintained revision variable. This resolves the ambiguity without renaming the preceding PR's limits contract.
  • Grok: accumulator, Sink location and finalizer cast. Kept them. The sink has one consumer, each emitter selects only its own fields, and bounded detached delivery keeps logging outside request completion. No additional service split or abstraction is needed.
  • Grok: structured dev-log --json wiring. Kept the issue feat(analytics): wide events: the accumulator, the stdout and PostHog sinks, the request event on runtime routes #388 boundary. Full-record formatting exists; the dev-loop ticket owns structured dev.log retrieval. The documented CLI response contract remains unchanged.

Verification

  • pnpm typecheck: all 36 tasks passed. pnpm lint passed.
  • Disposable real-HTTP smoke through Runtime/RuntimeApi and the real PostHog SDK: nine requests produced nine stdout events and nine loopback collector deliveries. Responses were 200, 503, 503, 503, 200, 401, 200, 200, 503; table/file capacity errors emitted refused, source failure emitted failure, and unresolved commit emitted unknown_outcome. Confirmed operation-only tier 1 attribution, configured host metadata, viewer/instance distinct IDs, retained company properties, and bytes round-trip. Only fixture identity/version/operation dependencies were injected; no production or existing dev instance was touched.
  • pnpm test --maxWorkers=2: 1,017 tests passed across all 88 files.
  • CI on 1335f04: all eight PR checks pass, including Node 22/24, format/lint/typecheck, real-Postgres concurrency, packed CLI/Preact smoke, live Clerk, dependency review and labels.
  • Node 22 initially hit the existing 5-second timeout in packages/integrations/src/postgres/Runtime.test.ts:127. That suite uses the no-op event layer. The changed event suites passed on the initial attempt; the entire failed Node 22 job passed when rerun on the same commit, without code or timeout changes.

GitHub reports MERGEABLE and CLEAN against tier2/387-limits-registry. That stacked base has no separately required-check policy; every configured check is green. No new conversation or review findings appeared after the push. No unresolved blockers. The PR remains open and unmerged.

@allisonmahmood
allisonmahmood force-pushed the tier2/387-limits-registry branch from 145d878 to 3ff7560 Compare October 1, 2026 00:14
Base automatically changed from tier2/387-limits-registry to main October 1, 2026 00:23
Add scoped hop records, shared best-effort stdout and PostHog delivery, and request instrumentation for call and bytes routes. Keep local output compact and attribution specific to each hop.

Refs #388, #384.
@allisonmahmood
allisonmahmood merged commit b72ff04 into main Oct 1, 2026
8 checks passed
@allisonmahmood
allisonmahmood deleted the tier2/388-wide-events branch October 1, 2026 00:35
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:primitives Patch tables and files area:server Touches the server area 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(analytics): wide events: the accumulator, the stdout and PostHog sinks, the request event on runtime routes

1 participant