Skip to content

fix(desktop): make every chat_agent_error explain itself - #12267

Merged
Git-on-my-level merged 1 commit into
mainfrom
telemetry/chat-agent-error-payload
Aug 27, 2026
Merged

Git-on-my-level merged 1 commit into
mainfrom
telemetry/chat-agent-error-payload

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Aug 26, 2026 •

Copy link
Copy Markdown
Member

Defect

The 2026-08 macOS churn cohort analysis (omi-knowledge-base/projects/macos-churn-analysis/evidence/2026-08-26-macos-churn-cohort-analysis.md, "Engineering leads") filed chat_agent_error as the highest-value instrumentation fix: "the event is well-powered but cannot explain itself."

Re-measured against PostHog (project 302298, $os = macOS) for August 2026, chat_agent_error = 1,197 events:

property populated
error_class / surface / harness 1,177
error_code 909
root_cause 178

Two corrections to the analysis are worth recording, because both changed the scope of this PR:

  1. The "97.9% null" figure is mostly a client-rollout artifact, not a live defect. Schema v2 (4d711b4dbe, 2026-07-11) already populates error_class/surface/harness on every event. Monthly completeness for error_class: June 0/2,028 → July 410/1,687 → August 1,177/1,197. The cohort window was dominated by pre-v2 clients.
  2. properties['error_code'] reads back NULL in HogQL even though the client sends it. JSONExtractString(properties, 'error_code') returns real values (unknown, authentication, adapter_unavailable, provider_billing_exhausted) for the same rows. Any future payload-completeness audit must cross-check with JSONExtractString; the map subscript under-reports.

The real remaining hole is in this repo. Only one of the ~15 telemetryAttempt.fail(...) call sites — desktop/macos/Desktop/Sources/Providers/ChatProvider.swift:5446 — passes a ChatQueryErrorDetail. Every other terminal (.timeout, .toolStall, .sessionSetup, .bridgeUnavailable, .attachmentUpload, .concurrentRequest, ...) reached PostHog with no error_code at all, and root_cause was hardcoded for exactly one class:

if errorClass == .authentication {
  properties["turn_disposition"] = "auth_blocked"
  properties["root_cause"] = "provider_claude"
}

A typed failure existed at the catch boundary and was collapsed to a bare class name by the time it was recorded.

Fix

ChatQueryErrorClass now classifies itself, so this lands at the single place that builds the payload rather than at 15 call sites:

  • rootCause maps every class to a bounded ChatQueryRootCause — subsystem attribution (provider_claude, agent_runtime, bridge_process, local_session, network, device_resources, attachment_pipeline, browser_extension, request_encoding, unclassified). .authentication keeps the already-published provider_claude value so existing PostHog breakdowns stay valid.
  • fallbackErrorCode(watchdogFired:) gives every class a bounded code when no ChatQueryErrorDetail is available, and separates watchdog_timeout from bridge_timeout — different owners, previously indistinguishable.
  • A supplied ChatQueryErrorDetail still wins; the fallback only fills the gap.

No raw exception text, prompt, path, or message enters the payload. Every value is an enum raw value, per the analytics integrity contract in desktop/macos/AGENTS.md.

Expected event shape after this change, for a watchdog timeout that previously carried nothing beyond its class:

error_class = timeout
error_code  = watchdog_timeout   (was: absent)
root_cause  = agent_runtime      (was: absent)

Proof

ChatQueryTelemetryTests (37 tests pass locally, xcrun swift test --filter ChatQueryTelemetryTests):

  • testEveryFailureClassCarriesABoundedCodeAndRootCause — iterates all 16 classes; fails if any emits an empty/absent error_code or an out-of-vocabulary root_cause. This is the automatic-or-dead check: a new ChatQueryErrorClass added without a mapping fails to compile (exhaustive switch), and one added with an empty mapping fails this test.
  • testRootCauseAndTimeoutCodesStayActionable — pins the auth compatibility value and the watchdog/bridge timeout split.
  • testErrorDetailCodeOverridesTheClassFallback — the fallback cannot shadow real detail.
  • testAnalyticsPayloadUsesTypedAllowlist (existing, updated) — still pins the exact emitted key set, so no unbounded property can be added silently.

Local make preflight passes. Full Swift contract CI (~42 min) runs after push; not claimed green here.

Invariants

  • INV-CHAT-1 — touched by path only. This PR changes the analytics payload built from an already-terminal chat query; it does not move rich-block handling, answer submission, or task completion out of the existing provider, and adds no lifecycle behavior.

Scope

Telemetry payload only. No product behavior, no new event, no new call site, no flag.

Failure-Class: FC-typed-failure-collapsed-to-generic


Second commit is unrelated housekeeping needed to get any desktop PR past the local pre-push gate on Xcode 26.x: a swift-format drift already on main (lint-scope covers every first-party Swift file) and one implicit self capture that Swift 6.2 rejects and Xcode 16.4 accepts. Formatter output and an explicit self.; no behavior change on either toolchain.

Review in cubic

## Why

The 2026-08 macOS churn cohort analysis
(`omi-knowledge-base/projects/macos-churn-analysis/evidence/2026-08-26-macos-churn-cohort-analysis.md`)
listed `chat_agent_error` as "well-powered but cannot explain itself".

Measured against PostHog (project 302298, macOS, JSON extraction rather
than the map subscript — see below), August 2026 `chat_agent_error`:

| property | populated |
| --- | --- |
| `error_class` / `surface` / `harness` | 1177 / 1197 |
| `error_code` | 909 / 1197 |
| `root_cause` | 178 / 1197 |

`error_class` is fine — schema v2 fixed that. The remaining hole is that
only one of the ~15 `telemetryAttempt.fail(...)` call sites
(`ChatProvider.swift:5446`) passes a `ChatQueryErrorDetail`. Every other
terminal — timeout, tool stall, session setup, bridge unavailable,
attachment upload, concurrent request — reached PostHog with no
`error_code` at all, and `root_cause` was hardcoded for exactly one
error class (`.authentication`). A typed failure existed at the catch
boundary and was collapsed to a bare class name by the time it was
recorded.

## What changed

`ChatQueryErrorClass` now classifies itself, so the fix lands at the one
place that builds the payload instead of at 15 call sites:

- `rootCause` maps every class to a bounded `ChatQueryRootCause`
  (subsystem attribution: provider, agent runtime, bridge process, local
  session, network, device resources, ...). `.authentication` keeps the
  already-published `provider_claude` value so existing PostHog
  breakdowns stay valid.
- `fallbackErrorCode(watchdogFired:)` gives every class a bounded code
  when no `ChatQueryErrorDetail` is available. It separates
  `watchdog_timeout` from `bridge_timeout`, which have different owners
  and were previously indistinguishable.
- A supplied `ChatQueryErrorDetail` still wins; the fallback only fills
  the gap.

No raw exception text, prompt, path, or message enters the payload — the
values are enum raw values, per the analytics integrity contract in
`desktop/macos/AGENTS.md`.

## Proof

`ChatQueryTelemetryTests`:

- `testEveryFailureClassCarriesABoundedCodeAndRootCause` iterates all 16
  classes and fails if any emits an empty/absent code or an out-of-
  vocabulary root cause.
- `testRootCauseAndTimeoutCodesStayActionable` pins the compatibility
  value for auth and the watchdog/bridge timeout split.
- `testErrorDetailCodeOverridesTheClassFallback` proves the fallback
  cannot shadow real detail.
- `testAnalyticsPayloadUsesTypedAllowlist` (existing) still pins the
  exact emitted key set.

37 tests pass locally.

Failure-Class: FC-typed-failure-collapsed-to-generic
@Git-on-my-level
Git-on-my-level force-pushed the telemetry/chat-agent-error-payload branch from ac0bb64 to 440f6a7 Compare August 27, 2026 03:50
@Git-on-my-level
Git-on-my-level merged commit 5c254e7 into main Aug 27, 2026
26 checks passed
@Git-on-my-level
Git-on-my-level deleted the telemetry/chat-agent-error-payload branch August 27, 2026 04:56
Git-on-my-level added a commit that referenced this pull request Aug 29, 2026
## Defect

The 2026-08 macOS churn cohort analysis
(`omi-knowledge-base/projects/macos-churn-analysis/evidence/2026-08-26-macos-churn-cohort-analysis.md`)
records under "Methodology guardrails":

> Instrumentation known-broken: `App Startup Timing` (11 samples/7 users
cohort-wide; `had_unclean_shutdown` ~always true; implausible TTI
values)

and under "Engineering leads": *"no usable macOS startup-performance
signal exists."*

That is three separate defects, and the first one changes how the other
two should be read.

### 1. The event does not reach PostHog at all

`AnalyticsManager.trackStartupTiming` writes only a Sentry breadcrumb:

```swift
// Routed to Sentry as a breadcrumb (perf telemetry, not product analytics) so the data
// is attached to any same-session crash report without creating a per-launch analytics
// event.
```

PostHog, `$os = macOS`, 2026-08-18 → 2026-08-25:

| build | `App Startup Timing` samples | `App Launched` |
| --- | --- | --- |
| 0.12.187 | **0** | 4,380 |
| 0.12.213 | **0** | 1,188 |
| 0.12.144 | **0** | 667 |
| 0.11.420 | 7 | 64 |
| 0.11.360 | 6 | 26 |

Every 0.12.x build emits zero. The cohort's 11 samples are not a
sampling defect — they are the last stragglers of an event that was
retired from product analytics. So "the event rarely fires" is not the
finding; "the event was deliberately moved to Sentry and nobody noticed
the fleet metric died" is.

### 2. `had_unclean_shutdown` was a race, not a crash rate

`.omi_running` is created at the *end* of
`RewindDatabase.performInitialization()`. Seventeen storage actors call
`RewindDatabase.shared.initialize()` lazily, and any of them can beat
`ViewModelContainer.loadAllData()` to it — the code even documents this
("TierManager triggers init early"). Once the database is open,
`hadUncleanShutdown()` reads **this** session's flag and reports every
clean launch as a crash.

### 3. TTI measured the wrong interval

`timeToInteractive` started at `CFAbsoluteTimeGetCurrent()` on the first
line of `loadAllData()`, which runs long after `main()`. 11–131ms is a
correct measurement of the wrong thing.

## Fix

- **`AnalyticsManager.trackStartupTiming`** emits `App Startup Timing`
to PostHog again, **once per process** (`loadAllData` re-runs on an
owner switch, and that is not a launch). The Sentry breadcrumb stays, so
the numbers remain attached to a same-session crash report — Sentry
answers "what did this crash look like", PostHog answers "is startup
getting slower across the fleet", and only the second one was lost.
- **`RewindDatabase`** latches the unclean-shutdown verdict at the first
observation in the process, and `performInitialization()` latches it
from `previousCrashed` *before* writing this session's flag. The verdict
becomes a property of the process rather than of call order. `close()`
clears the latch so a user retarget re-observes for the user it opens.
- **`AppStartupTiming.processStartDate()`** reads
`kinfo_proc.kp_proc.p_starttime` — the kernel's exec stamp, before dyld
and before `main`. `time_to_interactive_ms` is measured from there, and
is **omitted rather than faked** when the lookup fails.
- The old measurement is kept under the name it deserves:
**`data_load_ms`**.

### Event shape change

```
db_init_ms             unchanged
data_load_ms           new  — what time_to_interactive_ms used to measure
time_to_interactive_ms same name, now measured from kernel process start
had_unclean_shutdown   unchanged name, now actually about the previous session
database_init_failed   unchanged
```

**`time_to_interactive_ms` keeps its name and changes meaning.**
Historical values are not comparable — but there are 11 of them and they
were wrong. Anything reading this property (the `omi-posthog-macos`
skill documents it) should treat 0.12.x-and-later as a new series.

This adds a per-launch PostHog event, which moves the legacy all-events
DAU insight (already labelled `[Legacy] DAU — all events
(instrumentation-sensitive)`). `Core Product DAU v1 — clean by platform`
is an explicit allowlist and is unaffected.

## Proof

`xcrun swift test --filter
"AppStartupTimingTests|RewindDatabaseLifecycleTests"` — 14 tests pass
locally.

- `testUncleanShutdownVerdictSurvivesTheDatabaseOpeningFirst` — opens
the database first, asserts this session's flag exists (so the test
cannot pass vacuously), then asserts the verdict is false.
**Mutation-checked: deleting the latch read makes this test fail with
the exact production symptom.**
- `testPreviousSessionCrashIsStillReportedAfterTheDatabaseOpens` — a
stale flag from a previous session still reports unclean, so the latch
cannot swallow a real crash.
- `AppStartupTimingTests` — the kernel stamp is read and precedes any
`Date()` our own code can take; conversion floors at zero across a
wall-clock adjustment; a failed lookup yields no measurement rather than
a fabricated one.

Local `make preflight` passes. Full Swift contract CI (~42 min) runs
after push; not claimed green here.

## Invariants

- INV-AUTH-1 — touched by path only (`RewindDatabase.swift` is in the
desktop session-truth glob). This PR adds a latched boolean about the
*previous* process's shutdown; it does not touch session death,
`invalidateSession`, `signOut()`, Firebase credentials, or owner
identity. `close()`/`configure()` semantics are unchanged apart from
clearing that boolean.

Failure-Class: FC-alert-never-provably-fired

Line-Count-Exception:
desktop/macos/Desktop/Sources/Rewind/Core/RewindDatabase.swift | 3481 ->
3508 | +27 lines: one optional `Bool` field, a latch read in
`hadUncleanShutdown()`, a latch write in `performInitialization()`, a
clear in `close()`, and the comments that explain the race. Splitting a
3.5k-line database class is the right cleanup but is not this telemetry
fix's job, and folding it in would bury a 4-line behavior change in a
move diff.

---

*First commit is unrelated housekeeping needed to get any desktop PR
past the local pre-push gate on Xcode 26.x (also in #12267 and #12269):
a swift-format drift already on `main` and one implicit `self` capture
that Swift 6.2 rejects and Xcode 16.4 accepts. It drops out on rebase
once any of the three lands.*


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/12271?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
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.

1 participant