Skip to content

fix(task-intelligence): retry candidate integration exports and dead-letter the stale backlog - #21394

Merged
Git-on-my-level merged 14 commits into
mainfrom
lane/obs-integrations-retry
Oct 13, 2026
Merged

Git-on-my-level merged 14 commits into
mainfrom
lane/obs-integrations-retry

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Summary

  • Add a bounded sweeper for candidate_integration_outbox so a failed or abandoned export of an accepted desktop Suggested task is retried, while the accept path still dispatches once inline and returns before the provider finishes.
  • Rows older than 7 days, missing created_at, or stamped with a stale account_generation are transactionally dead-lettered (stale_abandoned, missing_created_at, generation_mismatch) with zero provider calls. Age uses redriven_at when an operator redrive stamped one. Generation mismatch is rechecked against the control document inside the dead-letter transaction. That is how the 2026-10-13 backlog (3,287 failed, 1 processing lease abandoned for 58.7 days) is discarded.
  • A row is retried only when the recorded provider outcome is not_sent or definite_error (no credentials, token refresh failure, a definite provider error, or no provider call). Timeout after the create was sent, a failed exported write, and unclassified legacy failures are dead-lettered in_doubt with no second provider call. A recorded external id is written onto the task as exported instead. The sweep skips provider dispatch when account_deletions/{uid} blocks access.
  • POST /v2/candidate-integrations/sweep uses the same Cloud Scheduler OIDC guard as the other backend-sync internal jobs. The manifest entry is lifecycle: planned and ENABLED for prod only, every 15 minutes. Dev has no entry: its data plane is production Firestore. backend/AGENTS.md stays unchanged because it is already at its 39000-byte budget.

Why

Accept claims a 300s lease and schedules auto_sync_action_item on the postprocess executor, then returns. Nothing walks failed, expired processing, or pending rows afterward, so a provider error or a crashed worker leaves the export there forever. The durable-queue policy is unchanged (max_attempts=5, backoff 30s–1800s). A younger due row is claimed again through a new blocking dispatch that finishes before the sweeper moves on. A row whose integration is not connected still completes, as the inline path does today.

The sweeper reclaims a processing row only when claimed_at is older than one hour (SWEEP_RECLAIM_AFTER). The 300s lease stays the claim protocol. When the inline job actually starts, and again at the start of the blocking dispatch, the worker transactionally re-stamps claimed_at only if its lease token still owns a processing row. If ownership was lost, it returns without calling the provider, so an export that outlives the 300s lease is not created twice.

The scan is an equality-only collection-group query on status, ordered by document name, with a metadata field mask. It is already served by candidate_integration_outbox_status_group_ascending (__name__ is the index suffix). A single cursor document continues the next pass after rows that stay in the same status. No new composite index.

Rollout

Deploy backend-sync first, then reconcile the scheduler job. The sweep stops itself at 200 rows and 50s; the route timeout is 90s and the Scheduler attempt deadline is 120s.

The job is lifecycle: planned, so a full manifest check does not treat a missing job as drift and a full apply skips it. .github/workflows/gcp_scheduler_reconcile.yml is workflow_dispatch over the full manifest and does not pass --jobs. No workflow's scoped --jobs list includes candidate-integration-sweep, and no workflow file was edited. After backend-sync is serving the route, create the prod job explicitly:

python3 backend/scripts/scheduler_reconcile.py --environment prod --project based-hardware --apply --jobs candidate-integration-sweep

Rollout creates only the prod job. Prod is ENABLED. Dev has no manifest entry: based-hardware-dev's data plane is production Firestore, and a dev tick would dead-letter and retry production exports. Do not reconcile candidate-integration-sweep against the dev project.

Expected backlog cleanup: about 3.3k rows older than 7 days are dead-lettered with no provider call. At 200 rows every 15 minutes that is a few hours (about 17 ticks, roughly four hours). Younger due rows are retried under the existing five-attempt budget. A row that has already used its attempts is skipped until it ages into stale_abandoned. The existing omi-queue-oldest-ready alert is unchanged.

Verification

scripts/pr-preflight --pr-body-file .agent-pr-body.md passed 35 checks.

python backend/scripts/scan_async_blockers.py on the new route, sweeper, and candidate service: 0 blocking findings.

BACKEND_UNIT_TEST_FILE_LIST via backend/test.sh (not bare pytest), exit 0:

  • tests/unit/test_candidate_integration_sweeper.py — 16 passed
  • tests/unit/test_candidate_lifecycle.py — 67 passed
  • tests/unit/test_scheduler_reconcile.py — 11 passed
  • tests/unit/test_monitoring_telemetry_contract.py — 28 passed
  • tests/unit/test_monitoring_stt_stream_close_zero_init.py — 4 passed
  • tests/unit/test_monitoring_stt_metric_zero_init.py — 2 passed
  • tests/unit/test_monitoring_notification_contract.py — 6 passed
  • tests/unit/test_monitoring_dashboard_query_budget.py — 5 passed
  • tests/unit/test_monitoring_dashboard_absence_contract.py — 4 passed
  • tests/unit/test_monitoring_cost_contract.py — 6 passed
  • tests/unit/test_monitoring_alert_rule_contract.py — 49 passed
  • tests/unit/test_monitoring_alert_backtest.py — 19 passed
  • tests/unit/test_monitoring_adapter_hpa_contract.py — 24 passed
  • tests/unit/test_firestore_outside_query_contract.py — 28 passed
  • tests/unit/test_firestore_query_shapes.py — 459 passed, 1 deselected

Covered cases: stale and missing created_at dead-letter with zero provider calls; generation mismatch dead-letter; a young failed due row claimed and completed before return; a disconnected integration completed; future available_at and a young pending row skipped; a 10-minute processing row left alone and a 2-hour one reclaimed; an inline job delayed past 300s while a sweep runs is the only provider call; an inline job that lost its lease makes no provider call; the blocking dispatch makes none if the lease is taken before the provider call; row and wall-clock budgets stop the pass; the sweep counter zero-inits its closed disposition set; the route returns 403 for a missing, wrong-audience, wrong-identity, or unverified token; the scheduler job exists only for prod.

Product invariants affected

  • INV-TASK-2: preserved. The sweeper acts only on outbox rows for Candidates the user already accepted; it never creates a Candidate or an action item. Its one action-item write sets exported on the existing accepted task, using a recorded provider id, and is now registered under canonical_candidate_resolution in task_intelligence_sources_v1.json.

Failure-Class: none

Line-Count-Exception: backend/utils/metrics.py | 1514 -> 1540 | The closed sweep-disposition counter and its zero-init stay beside the other OMI counters.

Review

Independent Grok review found two Medium issues: a double export after the 300 s lease expired, and a dev scheduler job that could fire once against production before being paused. Both are fixed in 1955600: a lease re-stamp before every provider call, a 1-hour reclaim horizon, and no dev job.

Codex review on the same commit is fixed here. Ambiguous creates are not retried: the dispatch records in_doubt before the provider call and replaces it only with not_sent or definite_error when the failure is known to be pre-accept. Legacy rows with no outcome are dead-lettered in_doubt. A stored external id marks the task exported and completes the outbox. The sweep checks account_deletion_blocks_access(get_user_deletion_wipe_status(uid)) and skips with skipped_account_deleting when the marker blocks or the read fails. Generation mismatch is confirmed in the dead-letter transaction. redrive_patch stamps redriven_at, and the 7-day rule ages from that. The status scan orders by document name and start_afters the persisted cursor, bounded by the same 200-row budget. New transactional helpers take the call-time Firestore client.

A second Grok review of those fixes found two more ways to create a task twice, and both are fixed:

  • High: the Asana/Google Tasks resend after a 401 refresh could time out and still be recorded as token_refresh_failed → not_sent. That resend now raises into the create's in_doubt path; only a refresh that fails before any resend stays not_sent.
  • Medium: any non-2xx was a retryable definite_error. A 5xx can follow a committed create, so only <500 responses are definite; 5xx is in_doubt.

The public result of auto_sync_action_item is byte-for-byte what origin/main returns: same keys and same error strings for conversation batch sync and HTTP callers. Only the candidate dispatch reads the provider outcome, through the internal auto_sync_action_item_with_outcome. Existing contract suites (test_task_sync_batch_isolation, test_task_sync_cloud_export_dedup, test_task_sync_apple_async_boundary, test_task_integrations_ops) pass unedited apart from added cases.

Codex review on 166026a is fixed here. Duplicate-create safety is in the outbox claim transaction, so the sweeper, POST /v1/candidates/integrations/drain, repeated acceptance, and inline dispatch all share it. A row with provider_attempt_outcome=in_doubt is dead-lettered in that transaction (same disposition as the sweeper) and is not sent again; a live processing lease is left alone. A recorded external id marks the existing action item exported, including export_platform when the outbox has one, and completes the row. Fresh rows and not_sent / definite_error still claim. One sweep reads each status once: an empty page after a cursor clears that cursor for the next pass and moves on, so 200 future-due failed rows cannot hide a processing row that is due for reclaim. dispatch_task_integration_blocking threads its Firestore client through claim, lease refresh, and completion. The cloud create records export_platform on the outbox before the provider call, and recovery writes that platform back onto the action item with the external id.

🤖 Generated with Claude Code

Git-on-my-level and others added 4 commits October 13, 2026 17:59
…letter the stale backlog

Accept still dispatches once inline. A bounded sweeper now reclaims failed and expired-lease rows, and dead-letters exports older than seven days without calling a provider.

Co-authored-by: Cursor <[email protected]>
… policy

The scheduler endpoint is an internal OIDC route with the same reviewed policy shape as the other backend-sync sweeps.

Co-authored-by: Cursor <[email protected]>
The sweeper is named by the scheduler manifest and the route. A service-map line pushed backend/AGENTS.md over its 39000-byte budget.

Co-authored-by: Cursor <[email protected]>
…e expires

The sweeper reclaims a processing row only after one hour, and both the inline job and the blocking dispatch re-stamp the lease before calling the provider. Dev has no scheduler entry because its data plane is production Firestore.

Co-authored-by: Cursor <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 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-13T16:17:12.566924Z 05c6a2e 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: 1955600116

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

try:
recorded = await run_blocking(
postprocess_executor,
candidate_service.dispatch_task_integration_blocking,

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 Make retried provider creates idempotent

When a provider accepts a Todoist/Asana/ClickUp/Google Tasks create but the response times out, or the subsequent exported Firestore update fails, auto_sync_action_item reports failure and this new blocking dispatch leaves the outbox eligible for another attempt. _sync_to_cloud_service only suppresses another POST when the local exported marker exists, and create_task_internal sends no provider idempotency key, so the scheduled retry can create a duplicate external task for the user. Add provider-side idempotency or avoid automatically retrying ambiguous create outcomes.

Useful? React with 👍 / 👎.

client.collection_group(CANDIDATE_INTEGRATION_OUTBOX_COLLECTION)
.where(filter=FieldFilter('status', '==', status))
.select(list(SWEEP_METADATA_FIELDS))
.limit(limit)

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 Paginate past rows that remain skipped

The limited collection-group query has no cursor, while dispositions such as skipped_not_due, skipped_live_lease, error, and skipped_attempt_budget leave each row in the same queried status. Once the first 200 documents for a status are all unchanged—for example, after a provider outage gives them the same future backoff, or generation reads repeatedly fail—every invocation returns that same prefix, consumes the global row budget, and never reaches later due rows or subsequent statuses. Add stable ordering and a continuation strategy, or query only rows eligible for processing.

Useful? React with 👍 / 👎.

Comment on lines +129 to +130
outbox_ref = _integration_outbox_ref(uid, candidate_id)
transaction = db.transaction()

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 Resolve the Firestore client at the helper boundary

The new transactional helpers still create references and transactions through the legacy module-level db, while the scan accepts an injected call-time client. This can make a sweep read from the supplied client but mutate through the global client, and it prevents the required per-call test/runtime client selection. Pass a call-time get_firestore_client() result through the reference and transaction helpers, with an optional keyword-only client seam.

AGENTS.md reference: backend/AGENTS.md:L173-L175

Useful? React with 👍 / 👎.

Comment on lines +116 to +117
if row_generation != generation:
wrote = await _abandon(uid, candidate_id, 'generation_mismatch', 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 Recheck the generation in the dead-letter transaction

The current generation is read and cached separately from the transaction that applies generation_mismatch. If the account advances generations during a sweep—especially between the failed, processing, and pending status queries—the cache can still hold the old generation while a new-generation outbox row appears; _abandon checks only status and will permanently dead-letter that now-valid row. Read the control document and verify that the row is still mismatched in the same transaction as the terminal write.

Useful? React with 👍 / 👎.

Comment on lines +99 to +101
if _aware(created_at) < now - STALE_AFTER:
wrote = await _abandon(uid, candidate_id, 'stale_abandoned', now)
_bump(counts, 'dead_letter_stale_abandoned' if wrote else 'skipped_not_claimed')

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 explicit redrives of old dead letters

An operator can redrive a dead-lettered integration through redrive_candidate_integration_dead_letter, but its redrive_patch resets status, attempts, and available_at without changing the original created_at. For any item older than seven days, this new check therefore dead-letters the row again before dispatch, making the existing redrive operation ineffective unless another caller races the scheduler. Treat a recent explicit redrive as fresh, or record and honor a separate redrive timestamp.

Useful? React with 👍 / 👎.

Comment on lines +153 to +159
recorded = await run_blocking(
postprocess_executor,
candidate_service.dispatch_task_integration_blocking,
uid,
candidate_id,
task_id,
account_generation=generation,

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 retries once account deletion starts

This background dispatch bypasses the request authentication fence and never checks the authoritative account_deletions/{uid} marker. During the interval after a deletion intent becomes pending or running but before the recursive Firestore wipe reaches action items and task-integration credentials, the scheduled sweep can therefore create a new task in an external provider for an account whose access is already blocked for deletion. Check account_deletion_blocks_access(get_user_deletion_wipe_status(uid)) fail-closed before loading the task or invoking the provider, and suppress the outbox item instead.

Useful? React with 👍 / 👎.

Git-on-my-level and others added 5 commits October 13, 2026 20:18
A timeout or a lost export marker can mean the external task already exists, so those rows are dead-lettered instead of posted again. The sweep also skips deleting accounts, honors a redrive timestamp, and continues past unchanged outbox rows.

Co-authored-by: Cursor <[email protected]>
…der 5xx as in doubt

The Asana/Google Tasks resend after a 401 may reach the provider, so its failure
raises into the create's in_doubt path instead of reading as token_refresh_failed.
A 5xx can follow a committed create, so only <500 responses are definite errors.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…the provider outcome internally

The public auto-sync dict is what conversation batch sync and HTTP callers already depend on, so the provider-attempt outcome now travels only on the candidate dispatch path.

Co-authored-by: Cursor <[email protected]>
…path

Narrow the sweep age anchor with isinstance, drop always-true str checks, and make
the outcome-carrying auto-sync entry point public for its one cross-module caller.

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: 166026a067

ℹ️ 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 +375 to +379
if not rows and cursor:
cursors.pop(status, None)
rows, reached_end = await _page(
status,
limit=page_limit,

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 Advance to the next status before wrapping the cursor

When the first status contains exactly max_rows unchanged documents—for example, 200 failed rows whose available_at is still in the future—the first pass stores the last path, and the next pass finds no rows after it. This branch then clears the cursor and immediately reloads the same failed prefix, consuming the entire global budget again, so processing and pending are never inspected. The newly added cursor is fresh evidence that pagination was addressed, but wrapping within the same status and invocation preserves this starvation case; continue to the next status before restarting that status.

Useful? React with 👍 / 👎.

"""
if provider_dispatch_blocked_by_account_deletion(uid):
return False
lease_token, task = _claim_task_integration(uid, candidate_id, task_id, account_generation=account_generation)

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 Thread the sweep client through the claim

When dispatch_task_integration_blocking is called with an injected firestore_client, this claim still runs through _claim_task_integration, whose outbox claim uses the legacy global db; the following lease refresh uses the injected client, and completion switches back to the global client. Thus a sweep can scan a row in client A, claim client B, and then report a lost lease in A. Fresh evidence in the revised code is that the new blocking dispatcher exposes the client seam but does not pass it into its claim or completion path; thread the same call-time client through the entire operation.

AGENTS.md reference: backend/AGENTS.md:L173-L175

Useful? React with 👍 / 👎.

"""Accept path: claim, then schedule the provider sync. Returns before it finishes."""
if provider_dispatch_blocked_by_account_deletion(uid):
return False
lease_token, task = _claim_task_integration(uid, candidate_id, task_id, account_generation=account_generation)

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 Honor provider-attempt safety in every dispatch path

When an ambiguous create leaves a row failed with provider_attempt_outcome='in_doubt' or a recorded external ID, a repeated candidate acceptance or the existing authenticated /v1/candidates/integrations/drain route still enters this helper directly. _claim_task_integration then calls the claim transaction, which resets the outcome to not_sent and clears the external ID before scheduling another provider call, bypassing the sweeper's new recovery and _provider_retry_allowed checks and potentially creating a duplicate task. Fresh evidence beyond the earlier retry finding is the unchanged in-tree drain and idempotent acceptance paths still calling this newly modified dispatcher; apply the same safety policy before every claim.

AGENTS.md reference: AGENTS.md:L34-L34

Useful? React with 👍 / 👎.

Comment on lines +147 to +151
{
'exported': True,
'export_date': now,
'external_task_id': external_id,
},

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 provider during recorded-ID recovery

When a provider create succeeds but the original action-item marker write fails—the exact case this recovery path handles—the normal success path would have written export_platform, but this patch restores only exported, the date, and the external ID. The recovered action item therefore permanently reports an unknown platform even though the API model and action-item identity logic expose and preserve that field. Record the attempted provider in the outbox and restore it alongside the external ID.

Useful? React with 👍 / 👎.

Git-on-my-level and others added 3 commits October 13, 2026 21:45
Ambiguous outbox rows are dead-lettered or recovered inside the claim transaction, each sweep status is scanned once per pass, and blocking dispatch keeps one Firestore client from claim through completion.

Co-authored-by: Cursor <[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: 6e31be9040

ℹ️ 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 +262 to +264
if payload.get('provider_attempt_outcome') == PROVIDER_ATTEMPT_IN_DOUBT:
write_transaction.update(outbox_ref, _in_doubt_dead_letter_patch(claim_time))
return _ClaimApply()

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 Reject unclassified provider outcomes at claim time

For legacy failed rows where provider_attempt_outcome is absent or unrecognized, this condition falls through and claims the row for another provider POST. The sweeper deliberately treats those same rows as ambiguous, but a repeated candidate acceptance or the authenticated drain path calls this claim directly, so the pre-migration backlog can still create duplicate external tasks. Fresh evidence after the earlier dispatch-path comment is that the new gate handles only the literal in_doubt value; apply the retry-safe allowlist here as well, with the pristine pending/zero-attempt exception.

Useful? React with 👍 / 👎.

Comment on lines 265 to 267
lease_token = uuid4().hex
write_transaction.update(
outbox_ref,

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 Enforce the attempt budget when reclaiming a row

When the fifth claim crashes or its queued worker is lost before recording an outcome, the row remains processing with attempt_count == 5 and provider_attempt_outcome == 'not_sent'. After its 300-second lease expires, a repeated acceptance or drain reaches this unconditional increment and schedules attempt 6, while the sweeper separately considers the row over budget and refuses it. Check the policy limit transactionally and dead-letter the row rather than allowing direct dispatch paths to exceed max_attempts.

Useful? React with 👍 / 👎.

)
if lease_token is None:
return None, None
task = action_items_db.get_action_item(uid, task_id)

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 Load the claimed task from the injected client

When the blocking sweep supplies firestore_client, the outbox claim and completion now use that client, but this task lookup still goes through action_items_db's legacy global db. If the supplied client contains the row and task while the global client does not, the dispatch incorrectly records task_not_found instead of exporting it. Fresh evidence after the earlier client-threading comment is that the newly factored claim helper retains this split-client read; add a call-time client seam to the action-item helper and pass it here.

AGENTS.md reference: backend/AGENTS.md:L173-L175

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not changing this here. In production every path resolves to the same Firestore client; the injected client is a test seam. Threading a client parameter through action_items_db is a wider refactor of a shared module, and it's out of scope for this retry worker.

external_task_id=external_id,
export_platform=export_platform,
)
return action_items_db.update_action_item(uid, task_id, fields)

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 Fence recorded-ID recovery with the current generation

If the account generation advances after _generation returns but before this write, recorded-ID recovery still marks the old task exported and then complete_candidate_integration_recorded_export completes the outbox without rereading the control document or validating the row generation. Fresh evidence beyond the earlier generation-mismatch finding is that this success-recovery path remains nontransactional, whereas normal dispatch rechecks generation during its claim; move the action-item and outbox recovery into one transaction that also reads the current control generation.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Accepting this residual. The account generation advances only on account reset or deletion, and the sweep checks the deletion marker before this path. In the remaining window, a recovery could mark a task exported that the user has just reset. No provider call is made and no duplicate task is created. Making recovery one transaction that also reads the control document can come later if the window shows up in practice.

…dget at claim time

A legacy failed row with no recorded outcome may already have created the task,
and direct dispatch paths could exceed max_attempts. Both now dead-letter in the
claim transaction every path shares; a pristine pending row still claims.

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

patch = {
'status': 'dead_letter' if decision.terminal else 'failed',
'completed_at': None,
'lease_token': None,
'updated_at': completion_time,
'last_error_text': decision.error_text,
'dead_letter_reason': decision.reason if decision.terminal else None,

P2 Badge Recover recorded provider IDs before terminalizing the row

When the fifth provider attempt succeeds but the local action-item export-marker write fails, completion receives succeeded=False together with the recorded external ID; this branch nevertheless marks the row dead_letter because the attempt budget is exhausted. The sweeper scans only failed/processing/pending rows and claims reject terminal rows, so the safe recorded-ID recovery can never run, leaving the local task unmarked even though the provider task exists. Preserve a scannable recovery state or apply the recorded export instead of terminalizing this case.

ℹ️ 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 +136 to +142
noted = integration_outbox_db.note_candidate_integration_provider_attempt(
uid,
candidate_id,
lease_token=lease_token,
outcome='in_doubt',
firestore_client=firestore_client,
)

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 Keep pre-provider crashes retryable

If the worker is terminated after this write but before auto_sync_action_item_with_outcome reaches _record_attempted_provider, no provider request has occurred, yet the outbox is left in_doubt; after the lease expires, the sweeper permanently dead-letters it instead of exporting the accepted task. The claim already records not_sent, and the callback at the actual provider boundary records in_doubt, so avoid widening the ambiguous window here.

Useful? React with 👍 / 👎.

Comment on lines +265 to +268
attempts = int(payload.get('attempt_count', 0) or 0)
pristine = attempts == 0 and payload.get('status') == 'pending'
if not pristine and payload.get('provider_attempt_outcome') not in PROVIDER_ATTEMPT_RETRY_SAFE:
write_transaction.update(outbox_ref, _in_doubt_dead_letter_patch(claim_time))

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 Keep redriven ambiguous creates out of the provider path

When an operator redrives an in_doubt dead letter without a recorded external ID, redrive_patch preserves that outcome while resetting the row to pending with zero attempts. This pristine test then bypasses the retry-safe allowlist, so the next claim issues another non-idempotent provider create even though the previous attempt may already have succeeded. Restrict the pristine exception to rows with no prior provider outcome, or require an explicit unsafe-redrive mechanism.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is deliberate. redrive_candidate_integration_dead_letter is the explicit operator override: an operator redrives an in_doubt row only after checking the provider and finding no task there, and the reset to pending with zero attempts is how they authorize one more create. Automated paths (accept, drain, sweep) can't produce that state, and they all go through the allowlist at claim time.

The lease check before dispatch records not_sent; the begin_provider callback
marks in_doubt immediately before the create, so a crash before it stays retryable.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level
Git-on-my-level merged commit 7741a1a into main Oct 13, 2026
57 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/obs-integrations-retry branch October 13, 2026 16:42
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