Skip to content

PostHog ingestion config as code with a cost guard (SCA-3665) - #26119

Merged
Git-on-my-level merged 16 commits into
mainfrom
posthog-config-guard
Nov 27, 2026
Merged

Git-on-my-level merged 16 commits into
mainfrom
posthog-config-guard

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

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 by apply.py drift (scheduling it daily is a follow-up).

Tracking: SCA-3665 (Multica).

Cost line (passes under David's $660 waiver)

PostHog estimate: $652/mo (base $0/mo, delta $+652)
  events 3.40M/mo $98; identified 3.35M/mo $292; flags $222; warehouse 2.12M rows $13; other $28
  flags 157,105 requests/day (feature_flags.measured_requests_per_day); at flags = 0: $430/mo

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 /flags request bills while any KEEP flag is active, so flags stay as they are. budget.monthly_usd stays 500, and budget.waiver raises 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.

"waiver": {"monthly_usd": 660, "by": "David Zhang", "date": "2026-11-23",
  "reason": "PostHog /flags requests from Android 1.0.573 (about 2,245 users) and other old builds cannot be cut without user-visible flag fallbacks; return to 500 when they upgrade (SCA-3665)",
  "expires": "2027-01-31"}

The check accepts a budget waiver only when by is David Zhang, it has a date and reason, and expires has not passed; after 2027-01-31 the $500 budget applies again (tested). The earlier budget.ceiling mechanism is removed. Flags are priced from feature_flags.measured_requests_per_day (157,105, mean of 11-16..22).

Measurements (read-only, 2026-11-23)

  • Events: 7-day HogQL per event, reweighted by omi_sample_pct. 578k stored/day; 99.3% bill as identified (person_mode full or force_upgrade), matching /api/billing/ (16.07M identified of 16.17M projected).
  • Feature-flag requests (/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.
  • MCP Tool Use Succeeded: 499,219 calls over 9,164 actor-client-days in 7 days; 343 actor-days with 200+ calls carry 80% of the volume.

(a) Debugging events

  • Capture Wedge Detected, Local WAL Stuck, Recording Start Failed 10% -> 2%; Recording Upload Failed 3% -> 2%; the Dec 7 waivers are removed.
  • Dropped at ingestion (0%): 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.
  • Kept at 2% because a product reader needs them: desktop_health_event (admin voice reliability), Phone Battery Sample and Mobile Device Health Daily (admin device health, reweighted here), Product Error (experiment guardrail SqdSDiVW, journey scorecard), Recording Requested, Recording Observation and Mobile Telemetry Health (journey scorecard), Live Preview Notes / Verdict / Engine / First Word (live-preview feature 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:

Event After Lost
Capture Wedge Detected 2% Wedge count_cap and disk_reserve rules: one sampled device stands for ~50; the median 113 devices/hour becomes ~2 sampled, so pages are coarse and the disk_reserve rule (median 2/hour) is effectively blind
Local WAL Stuck 2% WAL backlog/age/other rules: medians 70 / 136 / 46 devices/hour become 1-3 sampled; coarse
Recording Start Failed 2% DS rule coarse; journey scorecard RSF counts read 50x low unweighted
Recording Upload Failed 2% Upload-failed rule (~297 devices/week) becomes ~6 sampled; insight aU3qFtY1 absolute counts ~50x low
Recording Upload Started / Completed 0% The upload failure-rate denominator; failure rates are no longer computable from PostHog
Capture Recovery * , Saved Pendant Reconnect, WAL Reconcile Poll Summary, Pendant Frames Dropped, Native Custody Observed, Orphan Audio *, WAL Upload Refused 0% Consumers capture-recovery, saved-pendant-reconnect, wal-backlog-health, native-custody-health, orphan-audio-*, wal-upload-refusals read nothing from PostHog
fallback_triggered, authenticated_request_401, auth_token_refresh_failed, Desktop Conversation Reconciliation Failed 0% Insight x8kWRnFm Error rate by app version loses these series
Conversation Untitled Rendered, Transcript *, Diarization Completed, api_edge_throttled, other dropped names 0% Regression probes and diagnostics with no product reader; data already stored stays

(b) Feature flags

  • Current mobile (iOS and Android native setup), desktop and web/app (advanced_disable_feature_flags) block PostHog /flags and read Omi flags. Personas also disables flags.
  • Backend utils/proactivity_flags.py makes a remote get_feature_variants call per uid (5-minute cache) when OMI_FLAGS_SOURCE is posthog or dual (pusher and listen run dual, llm-gateway runs omi). GMP omi_flag_dual_read_total shows 0 calls in 7 days on every job, so the backend makes no PostHog flag requests today.
  • The residual 157k/day comes from builds that predate the blocker. On 11-23, 745 Flutter users were still on 1.0.573, and older posthog-flutter and posthog-ios builds still fire $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: false for 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 as force_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-mcp selects the source with more qualifying calls per actor, client and UTC day. posthog.json already has MCP Tool Use Succeeded off (drop stage 01a14955): 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)

  • Reads/writes per unit of work. Per successful MCP call: one EVAL on postprocess_executor (off the request path), one atomic Lua script of 6-10 Redis commands on one hash (HINCRBY raw; for user/unknown calls HGET last, HSET first|last, HINCRBY pg|sg|sg2|n|t:<tool>, HGET/HSET dom), EXPIRE (3 days), ZADD NX into the day's dirty set and its EXPIRE. Measured volume 71.3k calls/day, 0.8 EVAL/s mean.
  • Flush. Each API-serving process starts a managed task. It runs the Redis sweep on the DB executor every 60 seconds and is cancelled during backend shutdown. The sweep reads today's due keys and the previous two days' pending keys, then atomically reads and claims each snapshot in Redis. Rejected captures are requeued. Redis, executor and capture degradation emit the shared omi_fallback_total signal with component mcp_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.
  • Keys and memory. 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.
  • Reader. wall-mcp.ts reads, per actor/client/day, whichever source saw more qualifying calls (raw on a tie; the largest snapshot by raw_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 >= 2 threshold 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_marker counts 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).
  • Production reconciliation. Run the documented read-only comparison for the first full UTC day served by the rollup. The check executes independent raw-only and rollup-only queries. Both must have input rows and return the same qualifying actor count and eligible-call total. Record the UTC day and outputs before step B.
  • Kill switch. MCP_DAILY_ROLLUP_ENABLED (on unless 0/false/off/no). Redis failures fail open; the raw event never depends on Redis.

Product sampling (David, 2026-11-23)

Device Session Ended, Memory Created and Recording Started leave the keep-list and take the 2% default, on the same distinct_id hash 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):

  • Omi TV qualified actors, 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.
  • Omi TV weekly growth uses the same per-person estimate for population. Weeks touching November 23, 2026 UTC or later omit growth transitions, quick ratio, stickiness and L1–L7. Those depend on transitions and qualified days that partially sampled capture data cannot recover.
  • Saved creators (activityQuery kind saved): 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).
  • cohortQuery captured and deviceFunnelQuery conv1/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):

  • Qualified-day counts mix foreground and capture days per person, so weights cannot fix them: cohort activated/retained/day1, device-funnel activated/kept, weeklyGrowthQuery (people, person-days, retained, new, L1-L7), retentionCurveQuery, establishedQuery, captureSourceQuery (hardware segments from Device Session Ended and Memory Created conversation_source; Device Paired stays at 100%, so paired hardware is still seen).
  • BigQuery daily-1 loses 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.
  • Saved insights that count Memory Created (37; PostHog writes are out of scope for this PR, the owner reweights them): ym8miKtQ, xkycBQGR, nX4yHJZR, Ljh22BGA, S9ejqxZf, hVOmWZof, lYPKzXez, tuJlwXAI, 2uESmZwV, 2UGD7AMt, r9swhXd4, SkeBEImo, xsqKOKIg, SiiWaJ22, dC91lpHT, PUMIm1Jd, IDKDRf2V, 8onn3LCw, gygGZzts, aVJxvnQH, Le551Mkd, MJbjzrTx, d7YuboKk, 37UGf8T6, Vlr3ISpf, Mfk4UNhF, fBoh2VuK, ellVtCM5, HW75LECu, iC2SPsYH, VHpsayOO, Hrd3g27M, uqawHNP4, 197taQZ7, Mbh2cugB, quKa37DZ, v1GPv0Im. Counts read about 50x low unweighted; retention and per-person insights (lYPKzXez, aVJxvnQH, d7YuboKk, Vlr3ISpf, Hrd3g27M and the lift and segment insights) are biased, not just scaled. No saved insight reads Device Session Ended or Recording Started.

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.

Event Stored/day before Saving Readers and what they lose
Rewind Screenshot Viewed 4,147 $12.7/mo Insights 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 reweighted
Battery Indicator Clicked 1,944 $5.9/mo Per-build presence check mobile-instrumentation-presence.sql only: it needs one row per build, so low-volume builds can read "absent"
Action Items Page Opened 1,352 $4.1/mo The same presence check; insights xkycBQGR, nX4yHJZR, Ljh22BGA, cCyMigls (Lifecycle, viewed 10-27) read about 50x low
Apple Reminders Sync Completed 809 $2.5/mo The presence check only

Total $25.2/mo: $678 -> $652.

Estimate

State $/mo
This file (raw MCP off, flags at 157,105/day) $652 (limit $660 under the waiver, $500 after 2027-01-31)
Flags at 0 (old builds upgraded) $430
Live until the rollup is verified (raw MCP still on) about $874

What changes

  1. 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 with est_events_per_day (7-day HogQL count reweighted by omi_sample_pct), identified, and for events kept above 2% purpose and reader. No waivers: every debug event is at or below 2%.
  2. scripts/check_posthog_config.py, called from the existing mobile-event-registry manifest 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 (by purpose or 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 exceeds budget.monthly_usd, or budget.waiver.monthly_usd while that waiver is signed by David Zhang and unexpired; a warehouse schema full-refreshes over 1M rows per run; or a later sampler would overwrite omi_sample_pct with 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 missing feature_flags.measured_requests_per_day are rejected; flags are priced from that measured daily rate, and the check also prints the estimate at flags = 0. 24 fixture tests.
  3. 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, apply snapshots the before-state to --snapshot-dir and PATCHes only differing inputs, names and should_sync; drift exits 1 on any difference, including an untracked transformation and a changed enabled or execution_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 mode randomSampling is managed alongside the rates and triggering events. The key comes from POSTHOG_PERSONAL_API_KEY.
  4. Readers reweight by 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: the desktop_health_event weight used by fallback-triage.ts and response-reliability.ts is 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 carries omi_sample_pct=10 (daily HogQL count, 10-17 through 11-23); earlier rows weigh one.
  5. Docs: app/lib/services/telemetry/EMISSION.md and web/admin/docs/posthog-events.md no 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 to posthog.json, with a cost-footguns list.
  6. New failure class FC-vendor-ingestion-config-changed-outside-review.

Desired-state changes the parent applies after merge

apply.py plan against live (read-only, 2026-11-24) shows 14 differences, including the (a) changes above and MCP Tool Use Succeeded added to the drop stage 01a14955:

  • Keep-list 291 -> 143 names (David approved 152; then Device Session Ended, Memory Created, Recording Started, MCP Tool Use Succeeded and the four weak-reader events above removed, MCP Daily Activity added; Recording Upload Started/Completed are not in it because their stages drop them). Removed:
    • debug events whose readers now reweight or tolerate 2%: 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);
    • 132 names with no reader in saved insights (290), web/admin, contracts/analytics/consumers, contracts/product-telemetry or 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_event sampler 10% -> 2%, renamed.
  • Keep-list function renamed.
  • The November 24 Change 3 receipt confirms the raw GCP resource export sync is off and the replacement gcp_cost_daily sync is active. The contract now includes the replacement view schema ID 01a20b47-efdb-0000-2289-a86b1a97dd46.

Readers that will read low after the cuts (PostHog insights, not code): x8kWRnFm Error rate by app version (fallback_triggered, authenticated_request_401, Desktop Conversation Reconciliation Failed), SqdSDiVW Product Error by arm, 3RxbhZLf (Update Check Failed), and contracts/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.sql and capture-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), and journey-scorecard.hogql (Recording Start Failed at 10%, Recording Observation at 2%).

Readers skipped

  • fallback-triage.ts reads desktop_health_event (health_event = 'fallback_triggered'), not the separate fallback_triggered event; it is covered by the weight change above. The fallback_triggered event itself has only the PostHog insight x8kWRnFm as reader.
  • The product-event readers that cannot be reweighted are listed under Product sampling.

Rollout

  1. Merge after independent review and green CI on the revised head.
  2. Deploy the backend rollup and updated admin reader. Keep raw MCP successes at 100%.
  3. Step A. Silence the eight Device Signals rules for 75 minutes. Use the staged config documented in web/admin/docs/posthog-events.md, which keeps raw MCP successes in the 100% keep-list and out of the drop stage. Run apply.py plan with that config. Reconcile any sampler enablement finding and rerun the plan before apply.py apply --snapshot-dir <dir>. Drift against the checked-in file should be limited to the two inputs for this one event.
  4. Step B. After the first full UTC day reconciles, plan and apply the checked-in config and confirm clean drift. The read-only reconciliation command is in backend/docs/server-product-telemetry.md.
  5. Read back vendor billing and the spend-watch projection 48 hours after step A, including whether step B landed.

Rollback restores the before-state captured in --snapshot-dir. The backend rollup kill switch is MCP_DAILY_ROLLUP_ENABLED=false.

Verification

  • Historical pre-R2 verification receipt (revision d53c98c491b9; not the current PR head): This revision included main at c84f3095128d. 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-tests passed 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=4 passed 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, activityQuery active 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_cadence covers 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.ts asserts both daily and weekly queries use last_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

Git-on-my-level and others added 2 commits November 23, 2026 17:32
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]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-27T12:25:34.861467Z 66ac405 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread scripts/posthog/apply.py
Comment on lines +92 to +94
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():

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread scripts/posthog/apply.py Outdated
Comment on lines +65 to +68
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'])}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Git-on-my-level and others added 6 commits November 23, 2026 18:38
…(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]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread web/admin/lib/wall-mcp.ts Outdated
Comment on lines +31 to +32
const prop = (name: string) => `JSONExtractString(properties,'${name}')`;
const num = (name: string) => `toFloatOrZero(${prop(name)})`;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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)`;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment thread backend/utils/mcp_daily_rollup.py Outdated
if len(parts) != 5 or not stats:
continue
_, _, key_day, client, uid = parts
emit(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment thread backend/utils/mcp_daily_rollup.py Outdated
with _sweeper_lock:
if _sweeper_started:
return
threading.Thread(target=_sweep_forever, name="mcp-daily-rollup", daemon=True).start()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment thread backend/utils/mcp_daily_rollup.py Outdated
Comment on lines +124 to +126
except Exception as exc: # noqa: BLE001 - telemetry must fail open
logger.warning("mcp daily rollup record failed error=%s", type(exc).__name__)
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment thread web/admin/lib/wall-mcp.ts Outdated
Comment on lines +100 to +102
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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +89 to +90
saved: "toInt64(round(sum(100/pct_any)))",
assistant: "count()",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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."

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit c0e5716 into main Nov 27, 2026
77 checks passed
@Git-on-my-level
Git-on-my-level deleted the posthog-config-guard branch November 27, 2026 15:53
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