Repository navigation
PostHog ingestion config as code with a cost guard (SCA-3665) - #26119
Conversation
PostHog drifted from about $500 to $2.8k a month because agents changed live sampling through the API with no review and estimates 2-6x low, and a 31M-row warehouse table full-refreshed every week. - contracts/analytics/posthog.json: ordered Hog transformations, keep-list, 2% default, warehouse schemas, budget and price tiers, and a measured 7-day volume, purpose and reader per event. - scripts/check_posthog_config.py (stdlib, no network), run from the mobile-event-registry manifest entry: prints the PR's cost against the merge-base and rejects unread 100% events, debug events above 2% without a David waiver, over-budget configs, large full-refresh syncs and sampler stages that would mis-tag omi_sample_pct. - scripts/posthog/apply.py plan|apply|drift, applied after merge. - Readers reweight by omi_sample_pct: admin device-health and the desktop_health_event weight shared by response-reliability and fallback-triage. - EMISSION.md and posthog-events.md: PostHog is for product analytics only; sampling changes go through the config file. Failure-Class: new Co-Authored-By: Claude Opus 5.5 <[email protected]>
… rule (SCA-3665) Failure-Class: new Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: eb5bcde581
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if live.get('name') != fn['name']: | ||
| changes.append({'target': fn['id'], 'field': 'name', 'live': live.get('name'), 'desired': fn['name']}) | ||
| for key, want in desired_inputs(fn).items(): |
There was a problem hiding this comment.
Detect and reconcile sampler enablement drift
If a managed sampler is disabled in PostHog while its name and inputs remain unchanged, diff() returns no differences: it never compares the live enabled field with the configuration. Using the existing fixture with functions['keep']['enabled'] = False reproduces this. Consequently, the daily drift command exits successfully and apply cannot restore the sampler, even though disabling the 2% default can increase affected ingestion volume by 50×. Compare enablement and include it in the PATCH bodies so the cost guard detects and repairs this state.
Useful? React with 👍 / 👎.
- Reject negative or non-integer estimates; estimate() tolerates bad values. - apply.py drift reports enabled/execution_order changes; PATCH keeps each input's metadata and lets the server recompile changed bytecode. - Device health: pendant groups need 20 estimated and 5 sampled users. - Drop the dead Capture Ingress Health keep-list entry. - Guard owns its own test file for enforcement scope. Failure-Class: new Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 464a72ff74
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| def desired_inputs(fn): | ||
| if fn['kind'] == 'keep_list': | ||
| return {'keep': names(fn['events']), 'percentage': fn['pct']} | ||
| return {'percentage': fn['pct'], 'triggeringEvents': names(fn['events'])} |
There was a problem hiding this comment.
Include sampling mode in the managed drift comparison
If a sampler's randomSampling input changes to true in PostHog, drift still reports success because the desired inputs contain only the percentage and event names. Changing that input in the existing in_sync() fixture reproduces an empty diff. This changes sampling from stable distinct-ID cohorts to individual events, invalidating the unique-user reweighting used by the Device Signals queries in backend/charts/monitoring/alert-rules.json: users with many events can appear almost universally and then be multiplied by the inverse sampling rate. Record the expected sampling mode in the configuration and compare it so this reader-breaking change is detected.
Useful? React with 👍 / 👎.
| countIf(if(build_presence.has_v2, interval_schema = 2, interval_schema = 1)) AS n_pairs, | ||
| uniqExactIf(person_id, if(build_presence.has_v2, interval_schema = 2, interval_schema = 1)) AS users, | ||
| round(sumIf(100 / sample_pct, if(build_presence.has_v2, interval_schema = 2, interval_schema = 1))) AS n_pairs, | ||
| round(uniqExactIf(person_id, if(build_presence.has_v2, interval_schema = 2, interval_schema = 1)) * 100 / greatest(maxIf(sample_pct, if(build_presence.has_v2, interval_schema = 2, interval_schema = 1)), 0.01)) AS users, |
There was a problem hiding this comment.
Estimate unique users per actor across sampling-rate changes
When a query window spans the rollout from 100% to 2%, one historical untagged row makes the group-wide maximum rate 100, so users observed only after the cutover receive no reweighting. This affects both phone and pendant health queries until historical rows leave the window, even with the intended stable distinct-ID sampling. Running the existing phone SQL fixture with one historical user and one different user tagged at 2% returns 51 estimated intervals but only 2 estimated users; the latter user's contribution should be weighted rather than suppressed by another user's historical rate. Aggregate the maximum applicable rate per user before summing user weights, and apply the same correction to the pendant user estimate and population guard.
Useful? React with 👍 / 👎.
…(SCA-3665) - No budget ceiling; any ceiling needs an unexpired waiver signed by David. - Wedge, WAL stuck, Recording Start/Upload Failed at 2%, waivers removed; other debug/ops events without a product reader dropped at ingestion. - identified now counts force_upgrade rows (personless on a known person still bills identified); flags priced from measured billing usage. - budget.planned prices the MCP daily rollup and PostHog flag shutdown; the check prints the estimate with and without them. - The config prices at $1,212/mo, over the $500 budget, so the guard fails on budget by design until further cuts land. Failure-Class: new Co-Authored-By: Claude Opus 5.5 <[email protected]>
Failure-Class: new Co-Authored-By: Claude Opus 5.5 <[email protected]>
…SCA-3665) David's ruling 2026-11-23: the $500 target includes product sampling; no ceiling; no skip hatch. - Device Session Ended, Memory Created and Recording Started leave the keep-list (2% default). Omi TV activity/MAU, saved creators, cohort captured, device-funnel conversions and viral-metrics activation and saved conversations weight by omi_sample_pct per person. - MCP Daily Activity: Redis accumulator per uid/client/UTC day and a sweeper that emits cumulative snapshots (also for today's tile). wall-mcp falls back to the rollup where raw rows are absent; daily MCP actors 11-16..22 are identical. Kill switch MCP_DAILY_ROLLUP_ENABLED. The raw event stays on until the rollup is verified (planned mcp-raw-off). - Flags priced from feature_flags.measured_requests_per_day (157,105); the check prints the estimate at flags = 0 and per planned change. Failure-Class: new Co-Authored-By: Claude Opus 5.5 <[email protected]>
… cuts (SCA-3665) David's ruling 2026-11-23: flags stay (switch-off saves ~$0 while any KEEP flag is active). budget.monthly_usd stays 500; budget.waiver raises the limit to 660 until 2027-01-31 (old-build /flags traffic). The check accepts a budget waiver only when signed by David Zhang and unexpired; the ceiling mechanism is gone. - MCP Tool Use Succeeded is off in the desired state; the release owner applies it after the rollup's first full UTC day matches the raw reader. - Rewind Screenshot Viewed, Battery Indicator Clicked, Apple Reminders Sync Completed and Action Items Page Opened take the 2% default ($25/mo): their readers are per-build presence checks and saved insights last viewed in October. Estimate $652/mo under the $660 waiver. Failure-Class: new Co-Authored-By: Claude Opus 5.5 <[email protected]>
The MCP daily rollup reads an env kill switch; the feature-flag registry requires every read to have a reviewed entry. ops_kill, default on, fail open; rendered registry doc regenerated. Failure-Class: new Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1a80132e5f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const prop = (name: string) => `JSONExtractString(properties,'${name}')`; | ||
| const num = (name: string) => `toFloatOrZero(${prop(name)})`; |
There was a problem hiding this comment.
Extract rollup counters as JSON numbers
snapshot_properties() emits calls, raw_calls, gap statistics, and last_call_s as JSON numbers, but this helper reads them with JSONExtractString. That function extracts String values, returning an empty string otherwise, so num("calls") becomes zero and the calls > 0 predicate excludes every rollup snapshot. Once the configured drop of MCP Tool Use Succeeded is applied, MCP activity and marker presence disappear from Omi TV. Use numeric JSON extraction for the counters and timestamp.
Useful? React with 👍 / 👎.
| }), | ||
| ranked AS (SELECT *,sum(captures) OVER (PARTITION BY actor,period) saved,row_number() OVER (PARTITION BY actor,period ORDER BY (p!='integrations') DESC,days DESC,latest DESC,${PLATFORM_RANK_SQL} ASC) rn FROM pd)`; | ||
| ranked AS (SELECT *,sum(captures) OVER (PARTITION BY actor,period) saved, | ||
| sum(fgn) OVER (PARTITION BY actor,period) fg_any,max(cap_pct) OVER (PARTITION BY actor,period) pct_any,row_number() OVER (PARTITION BY actor,period ORDER BY (p!='integrations') DESC,days DESC,latest DESC,${PLATFORM_RANK_SQL} ASC) rn FROM pd)`; |
There was a problem hiding this comment.
Exclude capture-free platforms from the saved sampling rate
For a person with a sampled capture on iOS and foreground-only activity on macOS in the same period, app_pd assigns rates of 2 and 100 respectively. This unconditional maximum therefore sets pct_any to 100, and the saved-creators query weights that person's sampled outcome by 1 instead of 50. Foreground activity makes the active-person count exact, but does not make saved status unsampled. Compute the saved sampling rate only across platform rows with captures.
Useful? React with 👍 / 👎.
| if len(parts) != 5 or not stats: | ||
| continue | ||
| _, _, key_day, client, uid = parts | ||
| emit( |
There was a problem hiding this comment.
Requeue snapshots when capture rejects an emission
If emit_product_event returns False, for example because its bounded SDK queue is full, this code still increments emitted after permanently removing the dirty entry with ZREM. If that user/client has no further calls that day, no later sweep retries the snapshot, even though its statistics remain in Redis; with raw successes dropped, the user's activity is permanently omitted or left at an earlier snapshot. Check the emitter result and restore the dirty entry on rejection or an emission exception.
Useful? React with 👍 / 👎.
| with _sweeper_lock: | ||
| if _sweeper_started: | ||
| return | ||
| threading.Thread(target=_sweep_forever, name="mcp-daily-rollup", daemon=True).start() |
There was a problem hiding this comment.
Run the sweeper through the managed background lifecycle
On the first successful accumulation, this starts an untracked, infinite daemon thread. backend/AGENTS.md explicitly forbids ad-hoc Thread instances and requires long-running coordinators to use the managed async/background primitives. This sweeper bypasses task tracking and shutdown cleanup, so it cannot be cancelled or awaited through the backend's lifecycle. Start a managed async coordinator and offload each blocking Redis sweep through the appropriate executor instead.
AGENTS.md reference: backend/AGENTS.md:L274-L279
Useful? React with 👍 / 👎.
| except Exception as exc: # noqa: BLE001 - telemetry must fail open | ||
| logger.warning("mcp daily rollup record failed error=%s", type(exc).__name__) | ||
| return False |
There was a problem hiding this comment.
Instrument rollup fail-open paths with the shared helper
When Redis accumulation fails, this branch drops the rollup contribution and continues with only a warning; the new scheduling and sweep failure branches do likewise. backend/AGENTS.md requires new fail-open paths to call utils.observability.fallback.record_fallback. Without that signal, the shared degradation monitoring cannot distinguish missing MCP activity caused by rollup failures from genuinely lower usage, especially after raw success ingestion is disabled. Record the degraded outcome through the shared helper at these failure boundaries.
AGENTS.md reference: backend/AGENTS.md:L326-L326
Useful? React with 👍 / 👎.
| mcp_stream_union AS (SELECT actor,client,utc_day,calls c,span sp,gaps g,sum_gap sg,sum_gap_sq sq,dominant dm,latest lt,1 prio FROM mcp_raw_stats | ||
| UNION ALL SELECT actor,client,utc_day,calls c,span sp,gaps g,sum_gap sg,sum_gap_sq sq,dominant dm,latest lt,0 prio FROM mcp_roll_stats), | ||
| mcp_stream_stats AS (SELECT actor,client,utc_day,argMax(c,prio) calls,argMax(sp,prio) span,argMax(g,prio) gaps, |
There was a problem hiding this comment.
Prefer complete daily statistics across the raw-stream cutover
When the raw-success ingestion drop is applied partway through a UTC day, any raw prefix for an actor/client/day always wins over that day's complete rollup because it has priority 1. For example, one success before the cutover and two afterward produces raw calls=1 and rollup calls=3, but this aggregation selects 1 and incorrectly excludes the person from mcp_days. The documented rollout waits for a full comparison day but does not require applying at midnight, so this affects the supported cutover procedure. Select the more complete source consistently across all statistics, or explicitly handle the cutover day's partial raw stream.
Useful? React with 👍 / 👎.
- Rollup day comes from the success time, not the worker clock (F1). - A refused snapshot is re-queued instead of consumed (F2). - wall-mcp reads whichever source saw more qualifying calls, raw on a tie, so the switch-off day reads the complete rollup (F4); the marker counts scheduled-agent-only snapshots (F5). - Saved-creator weights ignore rows without captures (F8). - Docs and failure class no longer claim a scheduled daily drift run (F6/F7); rate and claim corrections (F9, F10 wording), retired wal-backlog-health zero policy (F11), live fixture covers the rollup CTEs (F15), success-marker fixture pins the raw path alone (F16), top-level import (F17), dead keep-list entries removed (F18), reader path fixed (F19), boolean estimates rejected (F20). Failure-Class: new Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c7d26e23b5
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| saved: "toInt64(round(sum(100/pct_any)))", | ||
| assistant: "count()", |
There was a problem hiding this comment.
Apply the activity weights to weekly growth accounting
For capture-only actors after the 2% rollout, the snapshot now applies these weights, but weeklyGrowthQuery() still aggregates the shared pd rows with count() and unweighted person-days, dropping fgn and cap_pct in its ap CTE. One sampled capture-only actor therefore contributes 50 people to activityQuery() but only one to the weekly growth series used by wall-series.ts. Carry sampling weights through that query and apply them consistently to its population and growth-accounting outputs so the two views do not report different populations for the same week.
Useful? React with 👍 / 👎.
| "nX4yHJZR", | ||
| "Ljh22BGA" | ||
| ], | ||
| "sampled": "2% by the keep-list default since 2026-11-23 (David). Readers weight by omi_sample_pct; per-actor qualified metrics count actors with foreground activity exactly and weight capture-only actors." |
There was a problem hiding this comment.
Preserve sampling rates in the BigQuery daily rollup
When OMI_TV_ROLLUP_ENABLED=1 and coverage is complete, wall-series.ts prefers the BigQuery reader over the updated HogQL queries. However, dailyExtractQuery() still collapses activity into saved and count() without preserving the sampling rate or foreground-versus-capture evidence, and wall-rollup-sql.ts still uses unweighted distinct-actor counts and COUNTIF(captured). Removing Memory Created from the keep-list therefore makes covered saved-capture cohorts and capture-only activity up to 50× lower than the fallback reader, while permanently discarding the information needed to reweight stored rows. Update the extraction schema and BigQuery aggregations alongside this sampling change, or prevent affected windows from being served as covered.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d9da57801e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| toDate(timestamp) as day, | ||
| uniq(COALESCE(person_id, distinct_id)) as conversation_creators, | ||
| count(*) as saved_conversations | ||
| toInt64(round(uniq(COALESCE(person_id, distinct_id)) * 100 / max(${SAMPLE_PCT_SQL}))) as conversation_creators, |
There was a problem hiding this comment.
Weight conversation creators per person before summing
On a UTC day spanning the sampling rollout, one untagged Memory Created row makes the day's maximum sampling rate 100, so every creator observed only at 2% is counted without reweighting. For example, an untagged row from one person and a 2%-tagged row from another produce 51 estimated saved conversations but only 2 estimated creators, instead of a creator estimate of 51. This understates the cutover day's creator series until it leaves the requested history, and recurs on future rate changes. Aggregate the highest applicable rate per person/day first, then sum those person weights.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8bb0730df6
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| redis.call('HINCRBY', key, 'sg2', gap * gap) | ||
| end | ||
| end | ||
| redis.call('HSET', key, 'last', now) |
There was a problem hiding this comment.
Preserve the success timestamp separately from the Redis clock
When a success just before midnight is processed by the executor after midnight, the hash is correctly bucketed under the success day, but last records the following day's Redis time. snapshot_properties() then exports that value as last_call_s, which wall-mcp.ts exposes as mcp_days.latest. In wall-posthog.ts, activity periods are calculated from that timestamp rather than utc_day: for example, a November 23 success processed at November 24 00:00:04 is assigned to November 24 in the daily history ending November 25. Once raw successes are dropped, this moves qualifying users between daily or weekly populations. Keep the original success timestamp for the exported latest-call time, independently of the Redis clock used for cadence statistics.
Useful? React with 👍 / 👎.
Why
PostHog drifted from about $500/mo to about $2.8k/mo projected (
/api/billing/, read 2026-11-23T07:44:58Z). Agents changed live sampling through the API with no PR, putting debugging events at 100% with estimates 2-6x low, and a 31M-row GCP billing table full-refreshed every week. David's rules (2026-11-23): PostHog is for product analytics only; target under $500/mo; nothing joins the 100% set without a cost estimate; guards are cheap stdlib checks; live drift is reported byapply.py drift(scheduling it daily is a follow-up).Tracking: SCA-3665 (Multica).
Cost line (passes under David's $660 waiver)
David's rulings (2026-11-23): the target is $500 and includes product sampling; no ceiling; no skip hatch. A switch-off audit then found that turning off the safe PostHog flags saves about $0, because every
/flagsrequest bills while any KEEP flag is active, so flags stay as they are.budget.monthly_usdstays 500, andbudget.waiverraises the limit to $660 until 2027-01-31. The waiver records David's ruling (given in chat, recorded on SCA-3665 and in anx); it is not self-granted by the agent.The check accepts a budget waiver only when
byis David Zhang, it has a date and reason, andexpireshas not passed; after 2027-01-31 the $500 budget applies again (tested). The earlierbudget.ceilingmechanism is removed. Flags are priced fromfeature_flags.measured_requests_per_day(157,105, mean of 11-16..22).Measurements (read-only, 2026-11-23)
omi_sample_pct. 578k stored/day; 99.3% bill as identified (person_modefullorforce_upgrade), matching/api/billing/(16.07M identified of 16.17M projected)./api/billing/usage, team 302298 only): about 2M/day in late October, then 600k/day on 11-06, and 125k-174k/day on 11-16..22 (mean 157,105/day, about 4.71M/mo, $222/mo). The 6.88M projection includes the early-period days.(a) Debugging events
Capture Wedge Detected,Local WAL Stuck,Recording Start Failed10% -> 2%;Recording Upload Failed3% -> 2%; the Dec 7 waivers are removed.Recording Upload Started/Completed(stage 01a147e7 to 0) and 49 debug/ops events with no product reader, in the drop stage 01a14955: App Startup Timing, Audio Playback/Share Failed, Capture Gap Detected, Capture Recovery Observed / Resolved / Prompt Shown, Conversation Processing Completed / Stalled, Conversation Untitled Rendered, Desktop Conversation Reconciliation Failed, Desktop Recording Error, Desktop Silent Mic Diagnostic, Diagnostics Send Failed, Diarization Completed, Encoded Audio Duration Measured, Integration Connect/Sync Failed, Listen Session Realtime Demand, Memories Cache Reconcile, Mobile Background Resource Session / Observation Interrupted, Native Custody Observed, Orphan Audio Recovery / Reclaim, Pendant Frames Dropped, Saved Pendant Reconnect, Screen Task Frame Terminal, Siri Index Rebuilt, Speaker Identity Proposed, Speech Positive Duration Measured, Suggestion Assistant Evaluation Started / Completed / Failed, Transcript Started / Completed / Cancelled / Failed, Update Check Completed, WAL Reconcile Poll Summary, WAL Stop Drain, WAL Upload Refused, WAL Write Receipt, api_edge_throttled, auth_token_refresh_failed, authenticated_request_401, fallback_triggered.desktop_health_event(admin voice reliability), Phone Battery Sample and Mobile Device Health Daily (admin device health, reweighted here), Product Error (experiment guardrailSqdSDiVW, journey scorecard), Recording Requested, Recording Observation and Mobile Telemetry Health (journey scorecard), Live Preview Notes / Verdict / Engine / First Word (live-previewfeature consumer), Suggestion Assistant Gate Outcome and Device Disconnected Detailed (dispositions table: Keep), Update Check Started / Failed (3RxbhZLf), Device Connect Failed, Firmware Update Failed, chat_agent_error.What is lost (accepted by David until SCA-3922 moves Device Signals to Prometheus). The Device Signals rules stay on PostHog and go coarse or blind:
aU3qFtY1absolute counts ~50x lowx8kWRnFmError rate by app version loses these series(b) Feature flags
advanced_disable_feature_flags) block PostHog/flagsand read Omi flags. Personas also disables flags.utils/proactivity_flags.pymakes a remoteget_feature_variantscall per uid (5-minute cache) whenOMI_FLAGS_SOURCEisposthogordual(pusher and listen rundual, llm-gateway runsomi). GMPomi_flag_dual_read_totalshows 0 calls in 7 days on every job, so the backend makes no PostHog flag requests today.$feature_flag_called. No in-repo change reaches those builds. The switch-off audit found that deactivating the safe flags saves about $0 (every request bills while any KEEP flag is active), so flags stay as they are and are covered by David's $660 waiver until those builds upgrade. No billing limit on flags is used.(c) Identified-person add-on
Not implemented, because it would save nothing. PostHog documents that an event sent with
$process_person_profile: falsefor a distinct_id that already has a person "counts as an identified event". The data agrees: MCP Tool Use Succeeded is already personless server-side and lands asforce_upgrade(61,295 of 61,405 rows in a day). Omi's events carry the signed-in uid, so a real saving would need a separate distinct_id, which breaks every person-level funnel, retention and DAU join. I judged that unsafe.(d) MCP Tool Use Succeeded (71k/day): server daily rollup, in this PR
Per-actor sampling cannot keep the Omi TV MCP DAU/WAU/MAU exact (MCP actors are unioned with app actors), so the server now rolls up per uid/client/UTC day and
wall-mcpselects the source with more qualifying calls per actor, client and UTC day.posthog.jsonalready hasMCP Tool Use Succeededoff (drop stage01a14955): the file is the desired state. The server keeps emitting it, and live keeps it until the release owner applies the file after the rollup is verified (see Rollout).DESIGN: MCP Daily Activity rollup (R19)
EVALonpostprocess_executor(off the request path), one atomic Lua script of 6-10 Redis commands on one hash (HINCRBY raw; foruser/unknowncallsHGET last,HSET first|last,HINCRBY pg|sg|sg2|n|t:<tool>,HGET/HSET dom),EXPIRE(3 days),ZADD NXinto the day's dirty set and itsEXPIRE. Measured volume 71.3k calls/day, 0.8 EVAL/s mean.omi_fallback_totalsignal with componentmcp_daily_rollup. Snapshots remain cumulative, at most one per key per 30 minutes plus a final one after the day ends. The measured upper bound remains about 7.7k PostHog events/day versus 71.3k raw.mcp:roll:{YYYYMMDD}:{client}:{uid}hashes, about 1,310 a day, 3-day TTL, so about 3.9k live hashes of 10-15 small fields (listpack), under 600 B each: about 2.4 MB. Three live dirty sorted sets of at most about 1.3k members: about 0.3 MB.wall-mcp.tsreads, per actor/client/day, whichever source saw more qualifying calls (raw on a tie; the largest snapshot byraw_calls), so the day the raw event goes off mid-day reads the complete rollup. The snapshot carries the same counts the raw query computes (qualifying calls, span, positive gaps, gap sum and sum of squares, dominant tool calls, last call second) and its UTC day comes from the success time, so the>= 2threshold is identical; gaps use Redis TIME (one ordered clock), which can differ from the raw event clock by queue delay, so the first full day's comparison gates the switch-off.mcp_markercounts any snapshot with raw calls, so the marker survives the raw switch-off. A snapshot the capture client refuses is re-queued. Read-only check against live PostHog: daily MCP actors 2026-11-16..22 are identical to the current reader (857, 872, 897, 928, 896, 750, 769).MCP_DAILY_ROLLUP_ENABLED(on unless0/false/off/no). Redis failures fail open; the raw event never depends on Redis.Product sampling (David, 2026-11-23)
Device Session Ended,Memory CreatedandRecording Startedleave the keep-list and take the 2% default, on the samedistinct_idhash as the rest of the recording journey (Recording Requested, Completed and Observation and Device Connected are already at 2%).Readers changed (each checked old vs new SQL against live PostHog, read-only; identical while nothing is sampled yet):
activityQuery(DAU/WAU/MAU by platform): an actor seen only through saved captures counts 100/pct, one with foreground or MCP activity counts once; actors with untagged (pre-change) captures count once, so windows that straddle the change stay unbiased. Live 7 days to 11-23: android 1,448, ios 3,063, macos 512, integrations 664 before and after.activityQuerykindsaved): every saved actor weighted, since saved status is itself sampled (android 836, ios 2,132, macos 461 before and after).mauOffsetsQuery(Omi TV MAU series): weighted per 30-day window (11,142 / 11,192 before and after).cohortQuerycapturedanddeviceFunnelQueryconv1/conv7: per-person weight from the rows that show the outcome (all rows identical before and after).app/api/omi/stats/viral-metrics/route.ts: activation (activated,capable_activated) weighted per signup; saved conversations weighted per row and each creator weighted once per day at their highest eligible rate (macOS 7-day activation identical before and after).Loss. Capture-only actors are 721 of 5,687 weekly app actors (ios 449, macos 183, android 89). At 2% one sampled person stands for 50, so the standard error is about sqrt(n x 49): weekly ios actors about +/-150 (5%), macos about +/-95 (18%), android about +/-66 (5%); saved creators ios about +/-320 (15%), android about +/-200 (24%), macos about +/-150 (33%). Daily tiles and small groups are noisier. macOS daily activation (1-10 activated a day) becomes 0 or 50; the Firestore activation overlay stays the macOS source.
Readers not changed (they read low for people seen only through these events):
activated/retained/day1, device-funnelactivated/kept,weeklyGrowthQuery(people, person-days, retained, new, L1-L7),retentionCurveQuery,establishedQuery,captureSourceQuery(hardware segments from Device Session Ended and Memory Createdconversation_source; Device Paired stays at 100%, so paired hardware is still seen).daily-1loses capture sampling rates and foreground evidence. The admin reader falls back to HogQL for windows touching November 23, 2026 UTC or later, even with a complete BigQuery receipt. The updated writer also skips these days and rejects explicit backfills on and after the cutoff.contracts/product-telemetry/posthog/journey-scorecard.hogql(Recording Started): ratios stay unbiased because the whole recording journey is sampled per user; attempt counts are at 2% scale.Four more events to the 2% default (to fit $660)
With raw MCP off the file was $678. These four have the weakest readers among events kept at 100%: none is in Omi TV, the journey scorecard, any web/admin or alert code, or a flag path, and their saved insights were last viewed in October.
xkycBQGR(K-factor proxy, "awaiting client releases", viewed 10-11),nX4yHJZR(shares per active user, viewed 10-11),Ljh22BGA(Core Product DAU v1, viewed 10-27): macOS rewind users read about 50x low in them unless reweightedmobile-instrumentation-presence.sqlonly: it needs one row per build, so low-volume builds can read "absent"xkycBQGR,nX4yHJZR,Ljh22BGA,cCyMigls(Lifecycle, viewed 10-27) read about 50x lowTotal $25.2/mo: $678 -> $652.
Estimate
What changes
contracts/analytics/posthog.json, the single source of truth: the nine ordered transformations (id, name, execution_order, kind, pct, events), the keep-list, the 2% default, warehouse schemas, the budget with price tiers (warehouse price marked derived), and an entry for every event seen in the last 7 days withest_events_per_day(7-day HogQL count reweighted byomi_sample_pct),identified, and for events kept above 2%purposeandreader. No waivers: every debug event is at or below 2%.scripts/check_posthog_config.py, called from the existingmobile-event-registrymanifest entry (paths and command extended, no workflow change). Stdlib, no network, about 0.1 s. It fails when an event kept at 100% has no estimate or no reader; a debug/ops event (bypurposeor name token: Failed, Error, Health, Wedge, Stuck, Diagnostic, Retry, Throttled, 401, Observation, Coverage, fallback; Sample and Daily as the last word) is above 2% without an unexpired waiver signed by David Zhang; the estimate exceedsbudget.monthly_usd, orbudget.waiver.monthly_usdwhile that waiver is signed by David Zhang and unexpired; a warehouse schema full-refreshes over 1M rows per run; or a later sampler would overwriteomi_sample_pctwith a looser rate than an earlier stage applied. When a diff does not touch the PostHog files, findings print as warnings so an expiring waiver cannot block unrelated mobile PRs. Negative estimates and a missingfeature_flags.measured_requests_per_dayare rejected; flags are priced from that measured daily rate, and the check also prints the estimate at flags = 0. 24 fixture tests.scripts/posthog/apply.py plan|apply|drift: reads the file, GETs each hog function's detail (inputs) plus the transformation list and warehouse schemas, prints a diff,applysnapshots the before-state to--snapshot-dirand PATCHes only differing inputs, names andshould_sync;driftexits 1 on any difference, including an untracked transformation and a changedenabledorexecution_order. Missing managed samplers and mismatched or unavailable enablement block every PATCH after saving the before-state. Release reconciles the reviewed enablement in PostHog and reruns the plan for the same step. The sampler moderandomSamplingis managed alongside the rates and triggering events. The key comes fromPOSTHOG_PERSONAL_API_KEY.omi_sample_pct(web/admin/lib/posthog-sampling.ts); the product-event readers are listed above:app/api/omi/stats/device-health/route.ts(Phone Battery Sample, Mobile Device Health Daily): counts weighted per row, each person weighted once at their highest eligible rate; quantiles stay on the sample; a pendant group needs 20 estimated and 5 sampled users, so it survives a 2% rate. SQL fixtures cover mixed 100%/2% rates and the five-person pendant guard.lib/telemetry/desktop-health-sampling.ts: thedesktop_health_eventweight used byfallback-triage.tsandresponse-reliability.tsis now the per-row tag instead of a hard-coded x10 after the 2026-10-17 cutover. Equivalent on history: every row since the cutover carriesomi_sample_pct=10(daily HogQL count, 10-17 through 11-23); earlier rows weigh one.app/lib/services/telemetry/EMISSION.mdandweb/admin/docs/posthog-events.mdno longer tell agents to add events to the 100% list. New rule: PostHog is product analytics only, debugging goes to the collector, sampling changes are a PR toposthog.json, with a cost-footguns list.FC-vendor-ingestion-config-changed-outside-review.Desired-state changes the parent applies after merge
apply.py planagainst live (read-only, 2026-11-24) shows 14 differences, including the (a) changes above andMCP Tool Use Succeededadded to the drop stage01a14955:Recording Upload Started/Completedare not in it because their stages drop them). Removed:Phone Battery Sample,Mobile Device Health Daily,fallback_triggered,authenticated_request_401,Product Error,Update Check Failed,Desktop Conversation Reconciliation Failed,Device Connect Failed(its only reader,onboarding-activation-funnel, counts presence);web/admin,contracts/analytics/consumers,contracts/product-telemetryor the alert rules. These were added by volume on 2026-10-28, not by reader. They fall to the 2% default; re-add any with a reader and an estimate:$rageclick,AI App Generator Banner Clicked,Add MCP Server Opened,Announcement Dismissed,App Detail Opened,App Detail Viewed,App Language Changed,App Startup Timing,Application Backgrounded,Apps Capability Filter,Apps Filter Capability,Apps Rating Filter,Apps Searched,Apps Sort Changed,Apps Sort Filter,Apps Type Filter,Audio Playback Failed,Audio Playback Paused,Audio Playback Started,Audio Share Failed,Audio Share Started,Auth Browser Opened,Auth Callback Received,Auth Callback Server Started,Auth Callback Valid,Auth Flow Cancelled,Auth Flow Completed,Auth Flow Started,Auth Flow Timed Out,Auth Token Exchange Completed,Auth Token Exchange Started,Capture Gap Detected,Capture Recovery Prompt Shown,Chat Apps Opened,Chat Message Copied,Chat Message Memory Clicked,Connection Guide Device Tapped,Connection Guide Dismissed,Connectors Page Viewed,Conversation Deleted,Conversation Detail Folder Chip Clicked,Conversation Processing Stalled,Conversation Star Toggled,Conversation Starred,Conversation Three Dots Menu Action Selected,Conversation Three Dots Menu Opened,Conversation Viewed,Conversations Page Viewed,Custom Vocabulary Opened,Daily Summary Conversation Clicked,Daily Summary Deleted,Daily Summary Time Changed,Delete Account Kept Account,Delete Account Reason Selected,Desktop Call App Audio Summary,Desktop Meeting Confirmed,Developers Page Viewed,Diagnostics Opened,Fact Page Deleted Fact,Firebase Custom Token Exchange Completed,Firebase Custom Token Exchange Started,Firmware Update Completed,Firmware Update Failed,Firmware Update Started,Goal Deleted,Guided Intro Content Save,Guided Intro Prompt Completed,Guided Intro Prompt Viewed,Guided Intro Recording Started,Guided Intro Review Shown,Guided Intro Save Submitted,Guided Intro Started,Guided Intro Voice Enrollment,Home Page Viewed,Import Started,Integration Connect Attempted,Integration Connect Failed,Integration Nudge Actioned,Integration Nudge Shown,Integration Sync Failed,Language Settings Opened,MCP Tool Call,Memories Cache Reconcile,Memories Page Viewed,Menu Bar Action Clicked,Menu Bar Opened,Notification Repair Triggered,Notification Settings Checked,Omi Shop Opened,Permission Changed,Profile Change Name Opened,Profile Delete Account Dialog Opened,Profile Speech Profile Opened,Push Token Status,Re-process Memory,Recap Summary Card Clicked,Recording Mute Toggled,Screen Task Delivery Completed,Search Opened,Setting Toggled,Settings Page Viewed,Sign Out,Speech Profile Memories Opened,Summarized App Create Template Clicked,Summarized App Enable Apps Clicked,Summarized App Selected,Summarized App Sheet Viewed,Summary Apps Opened,Tagged Segment User,Tagged Segment User Person,Task Integration Enabled,Task Intelligence Attribution,Tasks Page Viewed,Transcribe Later Recording Captured,Transcript Segment Tapped,Transcription Provider Selected,Transcription Source Selected,Update Firmware Memories Opened,Update Install Started,User Acquisition Source,User Deleted,chat_first_capability_resolution,chat_first_rich_block,chat_first_route_entered,desktop_daily_summary,first_real_app_card,followup_chip_tapped,memory_review_action,memory_review_card_shown,notification_settings_drift,question_answered,quiz_email_skipped.Capture Ingress Health(dropped by its own stage since 10:08Z today; the entry was dead).desktop_health_eventsampler 10% -> 2%, renamed.gcp_cost_dailysync is active. The contract now includes the replacement view schema ID01a20b47-efdb-0000-2289-a86b1a97dd46.Readers that will read low after the cuts (PostHog insights, not code):
x8kWRnFmError rate by app version (fallback_triggered, authenticated_request_401, Desktop Conversation Reconciliation Failed),SqdSDiVWProduct Error by arm,3RxbhZLf(Update Check Failed), andcontracts/product-telemetry/posthog/journey-scorecard.hogql(Product Error). They need the weight or a move to the collector. Already reading low since the 2026-11-23 10:08Z live change, not changed here:contracts/analytics/consumers/capture-recovery.sqlandcapture-recovery-presence.sql(Capture Recovery Observed, now 2%),wal-backlog-health(WAL Reconcile Poll Summary at 2%; Pendant Frames Dropped had no events in the 7-day window), andjourney-scorecard.hogql(Recording Start Failed at 10%, Recording Observation at 2%).Readers skipped
fallback-triage.tsreadsdesktop_health_event(health_event = 'fallback_triggered'), not the separatefallback_triggeredevent; it is covered by the weight change above. Thefallback_triggeredevent itself has only the PostHog insightx8kWRnFmas reader.Rollout
web/admin/docs/posthog-events.md, which keeps raw MCP successes in the 100% keep-list and out of the drop stage. Runapply.py planwith that config. Reconcile any sampler enablement finding and rerun the plan beforeapply.py apply --snapshot-dir <dir>. Drift against the checked-in file should be limited to the two inputs for this one event.backend/docs/server-product-telemetry.md.Rollback restores the before-state captured in
--snapshot-dir. The backend rollup kill switch isMCP_DAILY_ROLLUP_ENABLED=false.Verification
Historical pre-R2 verification receipt (revision
d53c98c491b9; not the current PR head): This revision included main atc84f3095128d. The feature-flag registry check and managed pre-push passed on that revision; the 87 backend, 34 PostHog, and 1,066 admin tests and the admin typecheck below were rerun there.M1 Studio:
python3 scripts/check_event_registry.py --base origin/main --posthog-testspassed 34 tests and modeled $652/month under the signed $660 waiver through January 31, 2027.M1 Studio: 87 backend tests passed across MCP daily rollup, success marker, product telemetry and process-role startup. The tests cover Redis Lua accumulation and claims, capture retry, degradation, executor dispatch and cancellation.
M1 Studio: admin typecheck passed.
OMI_TV_CLICKHOUSE_FIXTURE=1 npx vitest run lib/__tests__/ --maxWorkers=4passed 1,066 tests with 10 skipped. Numeric ClickHouse fixtures matched the complete day's raw and rollup counts and detected a missing final snapshot while the raw input was still present.The mixed-rate creator fixture returns 51 estimated creators and 151 estimated saves across repeated rows. Coverage fixtures verify the cutoff for historical reads, scheduled writes and explicit backfills. The enablement fixture verifies zero PATCH requests on disabled, missing or unverifiable sampler enablement.
The M1 pre-push gate passed. A separate ClickHouse fixture ran the production weekly growth aggregation with a 2% capture-only actor and a fully observed actor in the same platform and returned an estimated population of 51.
Live read-only HogQL comparisons, old vs new SQL, 2026-11-23: MCP daily actors 11-16..22,
activityQueryactive and saved (7 days),mauOffsetsQuery[0, 3],cohortQuery(maturity 7),deviceFunnelQuery(10-20), viral-metrics activation (macOS, 7 days): all identical. No PostHog, GCP, Grafana or Multica writes.Current PR head (
66ac40513f7a49bb4bff5bf701c82db4f69bc4ca, SCA-5050 R2, 2026-11-27): the rollup preserves the latest success timestamp separately from Redis processing time; daily and weekly readers use that success timestamp for reader windows.test_delayed_cross_midnight_success_keeps_reader_time_and_redis_cadencecovers delayed, out-of-order calls across the Nov 23 UTC week boundary: attribution stays on Nov 23 and the latest success timestamp is retained, while Redis-time cadence remains ordered (2 positive gaps; 8-second sum and span).wall-mcp.test.tsasserts both daily and weekly queries uselast_call_s. The recorded focused runs passed (11 backend MCP rollup tests; 8 admin wall-MCP tests, 1 skipped), as did the bounded pre-push gate. Release's 15:33 UTC report says PR PostHog ingestion config as code with a cost guard (SCA-3665) #26119 is OPEN, MERGEABLE and CLEAN; both required checks passed. The 15:32 gate check recorded 55 checks successful, 16 skipped, none pending or failing, with Mobile Release Eligibility and UI author approval successful.Failure-Class: new
UI-Evidence: none -- no UI change; admin queries, a backend telemetry rollup, Python checks and docs
🤖 Generated with Claude Code