Repository navigation
fix(desktop): stop the screen-activity cursor from skipping rows it will never revisit - #11868
Git-on-my-level wants to merge 2 commits into
Conversation
…ill never revisit ScreenActivitySyncService selected `WHERE id > ? AND embedding IS NOT NULL` and advanced a monotonic cursor past everything it shipped. Embeddings are computed asynchronously after insert, so any row whose vector had not landed when the sweep passed was skipped permanently. Measured on a live store: 705 of 26,822 rows over 30 days ever left the device. It reads as a working sync because rows keep arriving. Three further mechanisms independently denied a row its embedding, so repairing the cursor alone recovers little: cross-batch content-hash dedup returned early without queueing, gated or failed batches were dropped rather than requeued, and the backfill described in comments as the safety net had been stuck completed=1/processedCount=0 since 2026-04-16. Delivery is now durable per-row state (pending, textSynced, fullySynced, compacted) on an indexed column, so a row that was not ready when a sweep passed is picked up later. OCR-bearing rows ship without waiting for a vector; the vector attaches afterwards. Eligibility is evaluated per *closed* five-minute bucket, not per row. Comparing each row's own timestamp against `now - slack` makes eligibility slide: the early rows of a bucket become ready while its later rows do not, so the bucket is ranked more than once and ships more than one winner. Replayed over 7,346 real OCR-bearing rows, the sliding form ships 5,517 where bucket-aligned ranking ships 3,842 — 44% more than intended, which is most of the compaction saving. The same alignment applies to the embedding flush and to the backfill queries, so all three agree on what a bucket is. A closed bucket's winner now waits up to 15 minutes for its embedding before shipping text-only. Without that wait almost every row shipped twice, because sync sweeps at 5 minutes while the embedding flush also buffers to 5 minutes and then batches on a 60s timer. The second push wrote a byte-identical Firestore document and rewrote all of its index entries for no data change. Losslessness is preserved: the grace period is a delay, not a gate — a row whose vector never arrives still ships. Exempts ocrText, windowTitle, deviceName, and clientDeviceId from Firestore single-field indexing. Firestore auto-indexes every field in both directions, and nothing queries these — ocrText is only ever read back, never filtered or ordered on. Measured per document, index bytes were 75% of this collection's storage and the ocrText index alone was the majority of it. The one composite index is unaffected. The deferred embedding buffer is bounded. Requeueing gated batches fixes real data loss, but restores an unbounded buffer for a user whose backend gates every call; oldest deferred items are shed first. Timestamps are canonicalized at both the client and the ingest boundary. All 26,797 measured local rows already use the space-separated form the backend's lexicographic range filters assume, and zero use ISO `T`/`Z`, so no production query is currently returning wrong results — but the client had a live ISO fallback path, and the Pinecone timestamp for a naive string was computed in the process timezone rather than UTC. Verified: `swift build` and 9 Swift tests covering migration on a populated store, a row unready at sweep time, an open bucket shipping nothing, a closed bucket shipping exactly one winner and never shipping again, the embedding wait, and gated/failed requeue; plus 8 backend tests. Not verified: no deploy, and the cost model rests on list prices. Failure-Class: new Co-Authored-By: Claude Opus 5 <[email protected]>
Screen rows are cheap; the vector is not. Embedding and storing a 3,072-dim vector per delivered row is the large majority of what a synced screen row costs, and the vector's only server-side purpose is semantic screen search. Free-tier desktop users now sync their rows without vectors. They keep cloud screen history readable by time and app, and they keep on-device semantic search, which reads embeddings from the local store and never touches Pinecone. Because the OCR text is still stored, vectors can be backfilled from it when a user upgrades — this gate defers the cost rather than destroying the ability to recover. Gated on the desktop access tier rather than `is_paid_plan`, because screen activity is a desktop capability and a mobile-only paid plan did not buy it. BYOK does not grant it either: BYOK means the user supplies their own LLM keys, but the vector store is ours, and so is the cost being avoided. Enforced server-side at ingest rather than on the client. The client cannot be trusted to know its own entitlement, and gating there would also have to disable local embedding to save anything, which would break on-device search for free users. Fails OPEN on a lookup error, matching should_defer_desktop_processing: a Firestore blip must never silently strip a paying user's screen search. The failure mode is a small overspend, not a lost capability. Entitlement is cached for 5 minutes because sync runs on a 60s cadence. One correction to this PR's cost framing. The Gemini embedding spend (~$0.32/user/month) is NOT attributable to sync: embeddings are computed for local Rewind search on every capture regardless of whether the row ever syncs, through our own proxy. So this gate saves the Pinecone half (~$0.20/user/month) and not the embedding half. Tiering the embedding too would mean tiering on-device search, which is a separate product decision and is not made here. Verified: 11 backend tests, including that an unentitled user still stores the row and its text, that an entitled user still gets vectors, and that a lookup failure fails open. Failure-Class: none Co-Authored-By: Claude Opus 5 <[email protected]>
|
Folded into #11865 so beta gets one merge rather than two. Everything here is carried over verbatim, plus one gap that only showed up on merge: the No work is lost; this branch stays pushed for reference. |
|
Hey @Git-on-my-level 👋 Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request. After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:
Before your next PR, please skim:
If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing. Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out. Thank you for being part of the Omi community! |
…enabled in beta only (#11865) Turns the conversation notes v2 rollout on for the beta ring only. Production stays dark. ## Why the dev environment is the beta lever Beta is a deployment, not a cohort. The mobile `mobile_beta` profile and the beta desktop bundle `com.omi.computer-macos.beta` are both pinned to `api.omiapi.com` — the dev backend — while authenticating against the production Firebase project, and dev's `data_plane_project` is `based-hardware`. Setting the rollout flags in the dev runtime environment therefore reaches beta users, on their real data, without reaching production users. This is also the only mechanism available: `_flag_enabled` reads process environment, so the backend has no per-user flag evaluation. ## The gap this closes `#11834` declared the three `CONVERSATION_*` flags on `backend-listen` only. `process_conversation` runs in two services — backend-listen finalizes a live conversation, and the Cloud Run `backend` service runs it inline for `POST /v1/conversations/{id}/reprocess`. With the flags on one host, `os.getenv` falls through to the `False` default on the other, so a meeting would summarize under v2 and then regenerate under the legacy pipeline. Both return a well-formed summary, so the discrepancy reads as model nondeterminism rather than as missing configuration. Declared `false` in `_base.yaml` (no production behaviour change) and `true` in the dev overlay. The deploy validator already enforces this. Adding the flags to the Cloud Run service made three existing validator tests fail, because their Cloud Run state fixtures did not carry the variables — the validator correctly reporting that a deploy would omit them. The fixtures now carry them, scoped to the `backend` service. ## The desktop half The two client features are gated by PostHog, which targets users and cannot express "the bundle pointed at the dev backend". A cohort wide enough to include beta would also match stable users, whose backend has the consuming flags off — they would be prompted for calendar access to produce uploads nothing reads. So beta defaults on and keeps a kill-switch flag, letting a bad build be disarmed without shipping a new one; stable still requires its own positive flag. The decision is a pure function of its inputs, so it is exercised without a bundle, a process environment, or a PostHog client. ## Resulting state | | dev (beta) | prod | | --- | --- | --- | | `CONVERSATION_NOTES_V2_ENABLED` | true | false | | `CONVERSATION_CALENDAR_CONTEXT_READ_ENABLED` | true | false | | `CONVERSATION_OCR_CONTEXT_ENABLED` | true | false | Asserted on **both** summary-pipeline services, and the Helm values file is checked against the composed manifest, since Helm reads the values file rather than `runtime_env.yaml`. ## Verification - 89 backend tests: `test_backend_runtime_env_validator.py` (85) and the new `test_conversation_notes_v2_beta_rollout.py` (4). - A real `swift build` of the macOS SwiftPM package — build complete, not a typecheck. - 19 Swift tests via `swift test`, including the 6 new gating cases. Not verified: no deploy was run, so the dev rollout is asserted from the composed manifest and chart values rather than from a live service. Prod values are asserted unchanged. --- # Part 2 — lossless screen-activity sync Previously [#11868](#11868), folded in here so beta gets one merge rather than two. Screen-activity sync silently discards ~99% of what it captures. This makes it lossless, and cheaper per delivered row than the broken version is per delivered row. ## The defect `ScreenActivitySyncService` selected `WHERE id > ? AND embedding IS NOT NULL` and advanced a monotonic cursor past everything it shipped. Embeddings are computed asynchronously after insert, so any row whose vector had not landed when the sweep passed was skipped **permanently** — not retried, not queued, not reported. Measured on a live store: **705 of 26,822 rows over 30 days** ever left the device. It reads as a working sync, because rows keep arriving. Three further mechanisms independently denied a row its embedding, so repairing the cursor alone recovers little: - cross-batch content-hash dedup returned early without ever queueing the row, - gated or failed embedding batches were dropped rather than requeued, - the backfill that comments describe as the safety net had been stuck `completed=1, processedCount=0` since 2026-04-16. ## What changed **Durable per-row delivery state** (`pending → textSynced → fullySynced`, plus `compacted`) on an indexed column, replacing the cursor. A row that was not ready when a sweep passed is picked up by a later sweep. OCR-bearing rows ship without waiting for a vector; the vector attaches afterwards. Migration is safe on a populated store and starts existing rows `pending`, so history is recoverable. **Bucket-aligned eligibility.** Compaction keeps the longest OCR text per `(app, window, 5-min bucket)`. The original implementation tested each row's own timestamp against `now - slack`, which makes eligibility *slide*: the early rows of a bucket become ready while its later rows do not, so a bucket is ranked more than once and ships more than one winner. Replayed over 7,346 real OCR-bearing rows, the sliding form ships **5,517** where bucket-aligned ranking ships **3,842** — 44% more than the design intends, which is most of the compaction saving. The same alignment now applies to the embedding flush and the backfill queries, so all three agree on what a bucket is. **A closed bucket's winner waits up to 15 minutes for its embedding** before shipping text-only. Without that wait almost every row shipped twice: sync sweeps at 5 minutes, and the embedding flush also buffers to 5 minutes and then batches on a 60s timer, so the vector reliably lost the race. The second push wrote a byte-identical Firestore document and rewrote all of its index entries for no data change. Losslessness is preserved — the grace period is a delay, not a gate. **`ocrText`, `windowTitle`, `deviceName`, `clientDeviceId` exempted from Firestore single-field indexing.** Firestore auto-indexes every field in both directions, and nothing queries these — `ocrText` is only ever read back, never filtered or ordered on; semantic search goes through Pinecone. Measured per document, index bytes were ~75% of this collection's storage and the `ocrText` index alone was the majority of it. The one composite index is unaffected. **Bounded deferred buffer.** Requeueing gated batches fixes real data loss but restores an unbounded buffer for a user whose backend gates every call. Oldest deferred items are shed first. **Re-armed backfill** for the stranded history, capped per launch so it cannot stampede. ## The timestamp check, which came back negative All 26,797 measured local rows already use the space-separated `%Y-%m-%d %H:%M:%S.%f` form that the backend's lexicographic range filters assume; **zero** use ISO `T`/`Z`. So no production date-range query over screen activity is currently returning wrong results. Two latent paths are closed anyway: the client had a live ISO fallback, and `upsert_screen_activity_vectors` computed the Pinecone timestamp for a naive string in the *process* timezone rather than UTC (inert wherever the container runs UTC, wrong everywhere else). Both now canonicalize at the boundary. ## Cost Independently modelled from the live store rather than asserted. Per user per month, at this store's capture volume: | | rows delivered | month 1 | month 12 | |---|---:|---:|---:| | today (broken) | 705 | $0.11 | $0.14 | | this change | 3,842 | $0.36 | $0.54 | | lossless without compaction | 7,213 | $1.09 | $1.48 | Rows delivered go up **5.3x** and spend goes up about **5x**. That increase is real and permanent — it is the cost of not throwing the data away. The dominant term is per-row flow (embedding + vector writes), which does not compound; permanent storage accrual is ~$0.017/user/month. This store is a heavy dogfooder (26.8k captures over 19 active days), so treat per-user figures as an upper bound. Unit prices are list prices, not billed rates. **Not addressed here, deliberately:** truncating OCR to 1,000 chars before embedding would cut the embedding bill by more than half, and Firestore already stores only the first 1,000 chars. But the embedding is what makes text *searchable*, and nothing has measured retrieval quality past that point — so it is a product call, not a cleanup, and it is left out. **There is still no server-side retention of any kind.** The only deletion path is account deletion. Volume is unbounded and losslessness makes that more pressing, not less. Out of scope here; it needs its own decision. ## Tiering: cloud vectors are a paid desktop capability Second commit. Free-tier desktop users sync their rows without vectors — they keep cloud screen history readable by time and app, and they keep **on-device** semantic search, which reads embeddings from the local store and never touches Pinecone. The OCR text is still stored, so vectors can be backfilled on upgrade: the gate defers the cost rather than destroying the ability to recover. Gated on the desktop access tier, not `is_paid_plan` — screen activity is a desktop capability and a mobile-only paid plan did not buy it. BYOK does not grant it either: BYOK covers the user's own LLM keys, but the vector store is ours. Enforced server-side at ingest, since the client cannot be trusted about its own entitlement. Fails **open** on a lookup error, matching `should_defer_desktop_processing`. **Correction to the cost table above.** The Gemini embedding spend (~$0.32/user/month) is *not* attributable to sync. Embeddings are computed for local Rewind search on every capture regardless of whether the row ever syncs, through our own proxy — sync merely piggybacks on them. So this gate saves the Pinecone half (~$0.20/user/month), not the embedding half, and the "this change" row above overstates what tiering can recover. Tiering the embedding as well would mean tiering on-device search; that is a separate product decision and is not made here. ## Verification - `swift build` of the macOS package — a real build, not a typecheck. - 9 Swift tests: migration on a populated store, a row unready at sweep time delivered later, an open bucket shipping nothing, a closed bucket shipping exactly one winner and never shipping again, the embedding wait and its expiry, compaction keeping the longest text, and gated/failed requeue. - 8 backend tests covering timestamp canonicalization at ingest and the Pinecone UTC fix. Not verified: no deploy was run; no production Firestore sample was read (network and credentials unavailable); the Pinecone index configuration is not in the repo, so its storage class is unconfirmed. --- ## Part 3 — closing the beta gap between the two Merging the two exposed a gap. The lossless-sync flag was PostHog-only for every production-family bundle, so beta — the channel it exists to be exercised on — would have shipped it dark while the rest of the rollout was live there. The gating helper is renamed `BetaDogfoodRollout` and now backs all three client features: system calendar context, on-device meeting identity, and lossless screen sync. Beta is on unless killed; stable still requires its own positive PostHog flag; dev bundles keep their environment override. A test asserts all three share one decision and that each kill switch is derivable from its flag name, so a feature added past this helper fails the suite instead of going silently missing on beta. ## What is live where, after this merges | | beta | prod | | --- | --- | --- | | `CONVERSATION_NOTES_V2_ENABLED` (+ calendar, OCR reads) | on | off | | `system_calendar_meeting_context` | on (kill switch) | PostHog flag | | `on_device_meeting_identity` | on (kill switch) | PostHog flag | | `screen_activity_lossless_sync` | on (kill switch) | PostHog flag | | Firestore field-index exemptions | on | on | | Timestamp canonicalization | on | on | | Cloud screen vectors gated to paid desktop | on | on | The last three are not flagged: two are corrections with no behaviour change to gate, and the vector gate is a cost boundary that should not differ by environment. ## Combined verification - `swift build` of the macOS package, and 29 Swift tests. - 109 backend tests across five suites. Not verified: no deploy was run; no production Firestore sample; the Pinecone index configuration is not in the repo. ## One deferred definition The failure-class protocol admits exactly one added class definition per PR, and consolidating brings two. `FC-high-water-cursor-skips-unready-row` is kept — the cursor defect that silently discarded 99% of captured screen rows. `FC-rollout-flag-absent-from-a-cohost-of-its-code-path` is deferred to its own PR, not dropped. Its guard ships here regardless: `test_conversation_notes_v2_beta_rollout.py` still asserts that backend-listen and the Cloud Run backend can never disagree on a summary rollout flag, which is the behaviour the class protects. Only the prose definition moves. ## Product invariants affected - INV-AUTH-1 — touched only by adding one migration to `RewindDatabase`'s ledger. Ownership is unchanged: the migration registers after every existing component migration and runs inside the pool the owner transition already configures. Embedding writes keep taking an owner-bound `LocalMutationAuthorization` lease, and the requeue paths still check `generation == ownerGeneration` before returning items to the buffer, so a batch spanning a retarget is dropped rather than seeding the next owner's buffer with the previous owner's rowids. Failure-Class: new Line-Count-Exception: desktop/macos/Desktop/Sources/Rewind/Core/RewindDatabase.swift | 3450 -> 3470 | the schema migration and its callable boundary belong with the other migrations in the ledger; splitting the file to add one column would separate this migration from the ones it must stay ordered after Line-Count-Exception: backend/utils/subscription.py | 1491 -> 1535 | the entitlement helper belongs beside `should_defer_desktop_processing`, whose tier semantics and fail-open contract it deliberately mirrors; splitting it out would separate two gates that must stay consistent
Screen-activity sync silently discards ~99% of what it captures. This makes it lossless, and cheaper per delivered row than the broken version is per delivered row.
The defect
ScreenActivitySyncServiceselectedWHERE id > ? AND embedding IS NOT NULLand advanced a monotonic cursor past everything it shipped. Embeddings are computed asynchronously after insert, so any row whose vector had not landed when the sweep passed was skipped permanently — not retried, not queued, not reported.Measured on a live store: 705 of 26,822 rows over 30 days ever left the device. It reads as a working sync, because rows keep arriving.
Three further mechanisms independently denied a row its embedding, so repairing the cursor alone recovers little:
completed=1, processedCount=0since 2026-04-16.What changed
Durable per-row delivery state (
pending → textSynced → fullySynced, pluscompacted) on an indexed column, replacing the cursor. A row that was not ready when a sweep passed is picked up by a later sweep. OCR-bearing rows ship without waiting for a vector; the vector attaches afterwards. Migration is safe on a populated store and starts existing rowspending, so history is recoverable.Bucket-aligned eligibility. Compaction keeps the longest OCR text per
(app, window, 5-min bucket). The original implementation tested each row's own timestamp againstnow - slack, which makes eligibility slide: the early rows of a bucket become ready while its later rows do not, so a bucket is ranked more than once and ships more than one winner. Replayed over 7,346 real OCR-bearing rows, the sliding form ships 5,517 where bucket-aligned ranking ships 3,842 — 44% more than the design intends, which is most of the compaction saving. The same alignment now applies to the embedding flush and the backfill queries, so all three agree on what a bucket is.A closed bucket's winner waits up to 15 minutes for its embedding before shipping text-only. Without that wait almost every row shipped twice: sync sweeps at 5 minutes, and the embedding flush also buffers to 5 minutes and then batches on a 60s timer, so the vector reliably lost the race. The second push wrote a byte-identical Firestore document and rewrote all of its index entries for no data change. Losslessness is preserved — the grace period is a delay, not a gate.
ocrText,windowTitle,deviceName,clientDeviceIdexempted from Firestore single-field indexing. Firestore auto-indexes every field in both directions, and nothing queries these —ocrTextis only ever read back, never filtered or ordered on; semantic search goes through Pinecone. Measured per document, index bytes were ~75% of this collection's storage and theocrTextindex alone was the majority of it. The one composite index is unaffected.Bounded deferred buffer. Requeueing gated batches fixes real data loss but restores an unbounded buffer for a user whose backend gates every call. Oldest deferred items are shed first.
Re-armed backfill for the stranded history, capped per launch so it cannot stampede.
The timestamp check, which came back negative
All 26,797 measured local rows already use the space-separated
%Y-%m-%d %H:%M:%S.%fform that the backend's lexicographic range filters assume; zero use ISOT/Z. So no production date-range query over screen activity is currently returning wrong results.Two latent paths are closed anyway: the client had a live ISO fallback, and
upsert_screen_activity_vectorscomputed the Pinecone timestamp for a naive string in the process timezone rather than UTC (inert wherever the container runs UTC, wrong everywhere else). Both now canonicalize at the boundary.Cost
Independently modelled from the live store rather than asserted. Per user per month, at this store's capture volume:
Rows delivered go up 5.3x and spend goes up about 5x. That increase is real and permanent — it is the cost of not throwing the data away. The dominant term is per-row flow (embedding + vector writes), which does not compound; permanent storage accrual is ~$0.017/user/month.
This store is a heavy dogfooder (26.8k captures over 19 active days), so treat per-user figures as an upper bound. Unit prices are list prices, not billed rates.
Not addressed here, deliberately: truncating OCR to 1,000 chars before embedding would cut the embedding bill by more than half, and Firestore already stores only the first 1,000 chars. But the embedding is what makes text searchable, and nothing has measured retrieval quality past that point — so it is a product call, not a cleanup, and it is left out.
There is still no server-side retention of any kind. The only deletion path is account deletion. Volume is unbounded and losslessness makes that more pressing, not less. Out of scope here; it needs its own decision.
Tiering: cloud vectors are a paid desktop capability
Second commit. Free-tier desktop users sync their rows without vectors — they keep cloud screen history readable by time and app, and they keep on-device semantic search, which reads embeddings from the local store and never touches Pinecone. The OCR text is still stored, so vectors can be backfilled on upgrade: the gate defers the cost rather than destroying the ability to recover.
Gated on the desktop access tier, not
is_paid_plan— screen activity is a desktop capability and a mobile-only paid plan did not buy it. BYOK does not grant it either: BYOK covers the user's own LLM keys, but the vector store is ours. Enforced server-side at ingest, since the client cannot be trusted about its own entitlement. Fails open on a lookup error, matchingshould_defer_desktop_processing.Correction to the cost table above. The Gemini embedding spend (
$0.32/user/month) is not attributable to sync. Embeddings are computed for local Rewind search on every capture regardless of whether the row ever syncs, through our own proxy — sync merely piggybacks on them. So this gate saves the Pinecone half ($0.20/user/month), not the embedding half, and the "this change" row above overstates what tiering can recover. Tiering the embedding as well would mean tiering on-device search; that is a separate product decision and is not made here.Verification
swift buildof the macOS package — a real build, not a typecheck.Not verified: no deploy was run; no production Firestore sample was read (network and credentials unavailable); the Pinecone index configuration is not in the repo, so its storage class is unconfirmed.
Failure-Class: new
Line-Count-Exception: desktop/macos/Desktop/Sources/Rewind/Core/RewindDatabase.swift | 3450 -> 3470 | the schema migration and its callable boundary belong with the other migrations in the ledger; splitting the file to add one column would separate this migration from the ones it must stay ordered after
Product invariants affected
RewindDatabase's ledger. Ownership is unchanged: the migration registers after every existing component migration and runs inside the pool the owner transition already configures. Embedding writes keep taking an owner-boundLocalMutationAuthorizationlease, and the requeue paths still checkgeneration == ownerGenerationbefore returning items to the buffer, so a batch that spans a retarget is dropped rather than seeding the next owner's buffer with the previous owner's rowids.Line-Count-Exception: backend/utils/subscription.py | 1491 -> 1535 | the entitlement helper belongs beside
should_defer_desktop_processing, whose tier semantics and fail-open contract it deliberately mirrors; splitting it out would separate two gates that must stay consistent