Skip to content

feat(backend): harden the fleet backfill driver and cover completed-fanout indexing - #21141

Merged
Git-on-my-level merged 11 commits into
BasedHardware:mainfrom
Git-on-my-level:lane/fleet-backfill-fixes
Oct 10, 2026
Merged

Git-on-my-level merged 11 commits into
BasedHardware:mainfrom
Git-on-my-level:lane/fleet-backfill-fixes

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 10, 2026 •

Copy link
Copy Markdown
Member

What

Adds scripts/fleet_backfill_summary_vectors.py: a retry-safe fleet driver for the per-user backfill_summary_vectors.py operator tool, plus --all-users enumeration from conversation_finalization_jobs (created_at ascending, uid+created_at projection only).

Why

The chat-vector freshness repair (#21111) fixed new conversations; the pre-repair backlog needs the per-user backfill run for every affected account. Doing that by hand for ~27.6k uids is error-prone; the driver adds durable per-uid state (atomic tmp+rename), resume-on-rerun, failed-uid quarantine with --retry-failed, and a 10%-per-batch error budget inherited from the per-user script.

Cost/execution notes

  • Dry-run by default; --apply refuses without a configured vector index.
  • Per conversation: one embedding + the existing metadata-extraction LLM call. Fleet-scale cost was estimated at ~$40-230 for 50k-300k conversations before execution is authorized.
  • Designed to run inside the production backend environment (Cloud Run job or an attended operator shell); no secrets are read by this repo change.

Tests

  • Offline behavioral test of the driver: dry-run totals, resume skips done uids, error-budget stop marks the uid failed and continues, --retry-failed recovers only failed uids (writes verified per uid).
  • tests/unit/test_backfill_summary_vectors.py still green (16 passed).
  • --all-users enumeration verified against an independent REST enumeration of conversation_finalization_jobs since 2026-08-25 (27,595 vs 27,596, +1 from boundary drift; missing=0).

Failure-Class: none

UI-Evidence: none -- generated desktop Swift DTO regeneration only (no UI source change); required by the Public Developer API contract check after main's spec drift (#21129 messaging spec).

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-10T18:47:34.911551Z 8731038 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: 13f73a4413

ℹ️ 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 not done and not failed:
continue
col.document(shard_id).set(
{'done': done, 'failed': failed, 'updated_at': state.get('updated_at')},

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 Avoid writing empty maps into shared state shards

When two fleet executions overlap on the same two-character shard, a writer whose local snapshot has no done or no failed entries still sends that field as an empty map; Firestore merge semantics replace that map, so it can erase progress or quarantine entries that the other execution added after this process loaded. This defeats retry safety and can repeat expensive vector writes, so omit each empty map from the payload (or update only the dirty UID leaf paths).

Useful? React with 👍 / 👎.

Comment on lines +325 to +327
except Exception as error:
OMI_CONVERSATION_SUMMARY_VECTOR_UPSERTS_TOTAL.labels(outcome='error').inc()
logger.warning('summary_vector outcome=error exception_type=%s', type(error).__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.

P2 Badge Record reread failures through fallback telemetry

When the completed-fanout conversation reread or deserialization raises, this catch converts the failure into a successful finalization after only incrementing a metric and logging, so the skipped vector repair is invisible to the repository's standard fallback monitoring. Mirror the record_fallback call used by the claimed-fanout path before returning completed.

AGENTS.md reference: backend/AGENTS.md:L312-L312

Useful? React with 👍 / 👎.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Round-3 review blocker fixed (9d17564): shard saves now omit empty maps (no parent-field replace erasing the other map) and mirror writes are skipped entirely for a run whose initial mirror read failed (partial local state can no longer erase remote entries). Nits: completed-branch guard skips count skipped_no_structured; docstring points at --retry-failed; unused import removed.

@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: 9d175647e5

ℹ️ 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 +265 to +267
if not args.apply:
# A cost preview must never poison the resume state: a later
# --apply has to revisit every previewed uid.

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 Ignore legacy preview records before apply

When an operator reuses a state file created by the released driver after the required dry run, its done records contain apply: false. This early return prevents new previews from being persisted, but those existing entries have already been excluded by pending_uids, so a subsequent --apply silently runs zero UIDs and reports the previewed users as done; normalize loaded done entries by their apply flag (or version the state) before computing pending work.

Useful? React with 👍 / 👎.

and getattr(latest, 'structured', None)
and latest.structured == getattr(conversation, 'structured', None)
):
await run_blocking(postprocess_executor, _save_summary_vector_fail_soft, uid, latest)

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 Fence recovery upserts against conversation deletion

If a user deletes a conversation after this reread but while embedding/metadata generation is running, DELETE /v1/conversations/{conversation_id} can hard-delete the Firestore row and then delete its Pinecone vector before this new upsert executes, allowing the upsert to recreate derived data for a deleted conversation. Unlike backfill_summary_vectors.write_summary, this path never rereads/deletes after the write, so it needs the same post-write or tombstone fence before acknowledging the completed fanout.

Useful? React with 👍 / 👎.

Comment on lines +306 to +310
# Re-finalization of a row whose fanout already completed (e.g.
# server_recovery picking up a row finalized elsewhere). The
# summary-vector emission below the claim branch is unreachable on
# this path, so run the same fail-soft freshness guard here; a
# summary-vector failure never fails finalization (#21111 gap).

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 Document completed-fanout indexing in the lifecycle contract

This new branch emits a vector after fanout['status'] == 'completed', but backend/docs/listen_pusher_pipeline.mdx lines 618-625 still define vector emission as requiring a winning fanout claim and explicitly state that completed-fanout replays do not repeat the write. Update that lifecycle contract to describe this fail-soft recovery exception so operators and future changes are not guided by the opposite invariant.

AGENTS.md reference: backend/AGENTS.md:L157-L157

Useful? React with 👍 / 👎.



def save_state(path: Path, state: dict) -> None:
state.pop('_mirror_read_ok', None)

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 mirror read-failure guard across saves

When the initial mirror read fails and the run processes at least two users, the first save_state_durable captures _mirror_read_ok=False, but this call removes the marker from the in-memory state; the next save therefore defaults it back to True and resumes Firestore writes despite the message saying writes are disabled for the run. Because that run never loaded a complete remote snapshot, it can publish conflicting done/failed state for work another execution already recorded, so serialize a copy without the marker rather than popping it from the live state.

Useful? React with 👍 / 👎.

Comment on lines +181 to +183
if failed:
payload['failed'] = failed
col.document(shard_id).set(payload, merge=True)

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 Clear the mirrored failure after a successful retry

When --retry-failed later succeeds for a UID, main removes that UID from the local failed map, but this merge=True write only adds the done leaf and absence from the payload does not delete the existing remote failed.<uid> leaf. A fresh execution consequently loads the UID into both maps, permanently reports it in failed_total, and cannot clear it because the done entry prevents another retry; send an explicit leaf deletion for the dirty UID on success.

Useful? React with 👍 / 👎.



def load_state_durable(path: Path) -> dict:
MIRROR_COLLECTION = '_meta_summary_vector_backfill'

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 Migrate applied progress from the legacy mirror

When a fresh Cloud Run execution resumes progress written by the previously released driver, its local /tmp state is empty and successful records still live at _meta/summary_vector_backfill_state. This change reads only _meta_summary_vector_backfill, and a repo-wide search finds no migration or legacy read, so every already-completed UID is selected again and repeats the paid embedding/metadata calls; import legacy records whose summary has apply: true into the new shards before relying exclusively on this collection.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@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: 2f1fe57cec

ℹ️ 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".

let raw = try c.decode(String.self)
let normalized = raw.split(separator: ".").last.map(String.init) ?? raw
self = GoalType(rawValue: normalized) ?? ._unknown
self = GoalType(rawValue: raw) ?? ._unknown

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 qualified GoalType decoding

When a goal response carries a qualified legacy value such as "GoalType.scale", this initializer now maps it to ._unknown rather than .scale. The unchanged GoalProgressTests.testGeneratedGoalMetricDecodesQualifiedGoalType (lines 55-66) exercises exactly this backend compatibility case and now fails, while affected goal metrics lose their type at runtime; keep the dot-suffix normalization in the generator and generated output.

Useful? React with 👍 / 👎.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Round-4 review blocker resolved (e8ac475): the GoalType decode hunk came from my regen running an older generator — it was reverting main's newer normalization. Dropped; desktop/generated now matches origin/main verbatim (diff = 0). Prior five driver defects confirmed fixed by your review; nits (mirror-read flag persistence, ghost failed entries, skipped_stale counting, docstring) addressed in ff05b51/1bc854a53b. CI re-scoring on the new head.

@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: e8ac475d2a

ℹ️ 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".

and getattr(latest, 'structured', None)
and latest.structured == getattr(conversation, 'structured', None)
):
await run_blocking(postprocess_executor, _save_summary_vector_fail_soft, uid, latest)

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 Revalidate ownership before completed-fanout writes

When a delivery resumes after its 1,500-second job lease has been reclaimed, this upsert can still execute: _claim_finalization_fanout_txn returns completed before _is_current_lease (backend/database/conversation_finalization_jobs.py:978-981), so that status neither fences the caller's lease_epoch nor revalidates the conversation binding. The stale delivery can therefore issue duplicate paid embedding/metadata calls and race the current delivery's deterministic upsert even though its eventual job-completion write will be rejected; require a current lease/binding before allowing this recovery write.

Useful? React with 👍 / 👎.

):
await run_blocking(postprocess_executor, _save_summary_vector_fail_soft, uid, latest)
else:
OMI_CONVERSATION_SUMMARY_VECTOR_UPSERTS_TOTAL.labels(outcome='skipped_no_structured').inc()

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 Record structured mismatches as stale

When the summary changes between _load_admitted_conversation and this reread, every predicate is true except the final equality, so this shared else increments skipped_no_structured even though latest.structured is nonempty. The claimed path classifies the same race as skipped_stale at lines 371-374, so completed-fanout traffic now corrupts the bounded outcome breakdown used to monitor vector freshness; split the mismatch case and increment skipped_stale.

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: 873103834b

ℹ️ 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".

and not latest_data.get('deleted', False)
and not getattr(latest, 'discarded', False)
and getattr(latest, 'structured', None)
and latest.structured == getattr(conversation, 'structured', None)

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 Index current edits instead of completing the repair

When a user edits the title or summary between the admission read and this reread, latest is still the authoritative eligible row but this equality rejects it and the completed-fanout delivery then returns successfully, so it will not retry. update_conversation_title and update_conversation_summary only refresh the Typesense projection (backend/database/conversations.py:1730-1799) and never refresh the Pinecone summary vector, leaving the vector this recovery was meant to create absent or stale indefinitely; distinguish a same-revision user edit from a superseding finalization and index the former using latest.

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit 74dbe88 into BasedHardware:main Oct 10, 2026
50 of 52 checks passed
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