Skip to content

revert(gmail): sync sent hiring-thread messages - #4610

Merged
strelov1 merged 2 commits into
mainfrom
revert/gmail-sent-delivery-4604
Nov 14, 2026
Merged

strelov1 merged 2 commits into
mainfrom
revert/gmail-sent-delivery-4604

Conversation

@superplanefreehie

Copy link
Copy Markdown
Contributor

This reverts commit d319fcf.

Why: the first Gmail sync run on the build carrying "sync sent hiring-thread messages" (#4604) disconnected users' Gmail. With no sent-mail cursor yet, the worker re-read every known thread of every connected mailbox in one burst. Google answered some of those reads with 403, and the sync treats any 403 as a revoked grant, so it marked the connection "needs reconnect". In that one run 4 of 18 connected mailboxes were switched to needs-reconnect, all of them mailboxes whose sync had succeeded minutes earlier, against roughly one such case every couple of hours before. The release was rolled back and automatic deploys are held until this revert (or a fix) is on main.

The migration that adds the message direction and sent cursor columns came in with #4603 and stays: this revert changes no migration, and the old code ignores the extra columns.

Re-landing the sent-mail sync needs, at least: the first scan per mailbox paced or bounded (not every known thread at once), and a 403 that is a rate limit (reason in the response body) not treated as a revoked grant.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 14, 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-14T19:05:50.772286Z 6b3619f Draft marked ready
ℹ️ 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: ebf431d34c

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +207 to 209
if strings.EqualFold(msg.FromAddr, u.Email) {
return
}

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 provider labels when disabling sent discovery

When a candidate sends from a Gmail alias, or a draft appears during thread expansion, FromAddr does not necessarily equal the connected primary address, so this check allows the message through. Because the revert also stops parsing Gmail's SENT/DRAFT labels, the insert uses the schema's incoming default and the message can be classified as an employer reply, linked, and used to advance the application stage. Sent-mail discovery can remain disabled while retaining provider-label parsing and skipping sent/draft siblings here.

Useful? React with 👍 / 👎.

-- snippet already detoasts body_text, so the extra column costs no extra read;
-- it is guarded only to keep the web inbox's payload small.
SELECT emails.id, emails.source, emails.external_id, emails.thread_id, emails.direction, emails.to_addrs, emails.cc_addrs, emails.from_addr, emails.from_name, emails.subject,
SELECT emails.id, emails.source, emails.external_id, emails.from_addr, emails.from_name, emails.subject,

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 handling for already-stored outgoing messages

For mailboxes that completed the rolled-back sync before this revert, emails can already contain rows with direction = 'outgoing'; the migration and those rows are intentionally retained. This query still returns those rows but no longer exposes their direction, so the API and web UI render the candidate's own messages as ordinary inbound mail, while related unclassified counts can remain permanently nonzero because the classifier correctly refuses outgoing rows. Keep the direction-aware reader behavior, filter these rows, or explicitly clean up the stored outgoing data during rollback.

Useful? React with 👍 / 👎.

@superplanefreehie superplanefreehie Bot changed the title Revert "feat(gmail): sync sent hiring-thread messages" revert(gmail): sync sent hiring-thread messages Nov 14, 2026
@github-actions

Copy link
Copy Markdown
Contributor

OpenCodeReview — commit ebf431d34c76

Review incomplete. Retry with @codereview; diagnostics are kept private.

medium · web/src/lib/components/InboxView.svelte:629
With direction gone from the API, every row here renders as inbound mail from from_name || from_addr. But the gmail-outgoing feature this reverts (migration 0267) already shipped, so deployed databases still hold legacy direction='outgoing' rows whose from_name/from_addr are the user's own identity (that's how the old worker classified them), and ListEmails has no direction filter and no purge migration removes them. Failure scenario: a user who synced during that rollout permanently sees their own sent messages in the inbox list and reading pane as ordinary incoming mail 'from' themselves — the 'Sent' marker that distinguished them is removed and the UI can no longer tell them apart. The fix is on the backend side (a cleanup migration deleting direction = 'outgoing' rows, or excluding them in the inbox listing queries), and should land with or before this UI change; otherwise those rows are mislabeled forever.

low · web/src/lib/components/JobDrawerEmailList.svelte:56
Same legacy-data exposure as the inbox list: ListJobEmails never filtered on direction, so emails stored as outgoing while the now-reverted gmail-outgoing feature was live — sender = the candidate's own name/address, possibly linked to an application via the link picker — still feed this list and now render as ordinary inbound mail from the candidate themselves. The unconditional status-chip branch is safe today (the old upsert path nulled status_signal for outgoing rows, and StatusChip self-hides on an empty label), but the sender display is silently wrong for those rows. Covered if the companion cleanup migration removes legacy direction='outgoing' rows; otherwise consider filtering them out of the query.

high · internal/application/gmailsync/worker.go:241
Removing sawFailure = true from the thread-expansion error path lets the watermark advance past a thread whose siblings were never fetched. Concrete failure: a transient threads API error (rate limit, 5xx, reset connection) while expanding a newly discovered thread is now only logged, so SetSynced stores newest — the anchor's ReceivedAt. On the next run the search (after:cursor) no longer re-lists that anchor, the thread is never re-expanded, and its non-ATS siblings (the plain recruiter replies this feature exists to ingest) are silently lost until some later searchable message happens to re-anchor the thread. This also contradicts the documented contract in the fetch comment above ('once any message in the wave fails, it is reset to u.Cursor'), which GetMessage/UpsertEmail failures still honor. Restore the failure marking so a failed expansion keeps the cursor in place and the thread is retried next run.

medium · internal/application/gmailsync/worker.go:192
The 404 tolerance (missingMessage) was removed, so a permanently deleted message now fails the entire sync. A listed id can 404 when the user deletes mail between listing and GetMessage, and thread expansion can surface ids of trashed/spam messages purged after 30 days. Consequence: one such 404 sets sawFailure, resets the watermark to u.Cursor, and returns outcomeFailed — and because the frozen cursor re-lists the same anchors every run, a recurring 404 (e.g. a purged sibling still exposed by threads.get) makes the user's sync fail on every run forever, re-fetching the same window each time. The deleted code documented exactly this: 'A permanently removed provider resource has no content left to synchronize.' Restore the 404 skip (e.g. errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound) so a deleted resource is skipped instead of failing the wave.

medium · internal/platform/db/queries/gmail.sql:364
The unclassified filters/counts dropped direction = 'incoming', but legacy rows from the removed outgoing pipeline still exist: replies stored as direction = 'outgoing' before this change have classified_at IS NULL and no migration cleans them up. Those rows now count toward CountEmailsByState's unclassified badge and match the listing's unclassified filter, yet EnqueuePendingEmailClassification and ClaimEmailClassificationBatch (mail_classification.sql) still select only direction = 'incoming' — so these items can never be classified and the badge/listing shows permanently stuck entries. (New Gmail inserts are unaffected: the column default fills direction = 'incoming'.) Either keep excluding outgoing rows in these inbox queries (as applications.sql, nudges.sql etc. still do) or ship a migration that deletes/normalizes the legacy outgoing rows; as written, the inbox counts disagree with the classifier's actual backlog.

medium · internal/application/gmailsync/senders.go:145
Dropping -in:sent -in:drafts leaves only address-based exclusion (-from:selfAddr here, and the FromAddr == u.Email skip in the worker), which matches only the primary connected address. Gmail "send as" aliases are common: a candidate's own reply sent (or drafted) from an alias — which the comment above already notes matches the recall phrases as readily as an employer's, e.g. "next steps", "schedule a call" — is returned by the phrase clauses, passes -from:, passes the EqualFold(FromAddr, u.Email) check, and is stored as inbound, unread mail (the SENT/DRAFT labels are no longer read either, so parseMessage cannot catch it). The user then sees their own outgoing reply in the inbox as employer mail, classified and suggested. The label exclusions cost one query operator and caught this at listing time; restore them (or skip on the SENT/DRAFT labels when fetching).

#4609 only extended the sent-mail sync that #4604 added, so it goes out
with it. A unit test covers the restored Gmail message pagination.
@strelov1 strelov1 added large-pr Bypass the PR size check: change cannot be split and removed large-pr Bypass the PR size check: change cannot be split labels Nov 14, 2026
@strelov1
strelov1 marked this pull request as ready for review November 14, 2026 19:03
@strelov1
strelov1 merged commit 7bd5212 into main Nov 14, 2026
51 of 55 checks passed
@strelov1
strelov1 deleted the revert/gmail-sent-delivery-4604 branch November 14, 2026 19:04

@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: 6b3619f85d

ℹ️ 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 241 to 242
log.Printf("gmail-sync: user %d: thread %s: %v", u.UserID, tid, err)
sawFailure = true
continue

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 sync cursor when thread expansion fails transiently

If ListThreadMessageIDs returns a transient error, such as a 503, this path now continues without setting sawFailure, so SetSynced advances the cursor despite never fetching that thread's siblings. When another successfully fetched message moves the watermark past the failed thread's anchor, subsequent BuildQueryFor searches exclude that anchor, and this revert also removes the stored-thread scan that could revisit it. Recruiter replies without hiring-search markers can therefore be permanently missed after a temporary Gmail failure. Retain the previous cursor on transient thread-list failures so the next sync retries the expansion.

Useful? React with 👍 / 👎.

strelov1 added a commit that referenced this pull request Nov 14, 2026
strelov1 added a commit that referenced this pull request Nov 14, 2026
… connected

The first sync on #4604 re-read every stored thread of every mailbox at
once; Google answered part of the burst with 403 rateLimitExceeded, which
RevokedGrant read as a revoked grant, so 4 of 18 mailboxes were flagged
needs_reconsent and the release was rolled back (#4610).

- APIError now carries Google's error reason; a 403 whose reason is a rate
  limit or quota is not a revocation (Gmail and Calendar readers).
- The first sent-mail scan expands only the 50 newest stored conversations.
strelov1 added a commit that referenced this pull request Nov 14, 2026
…-limit handling (#4611)

* Revert "revert(gmail): sync sent hiring-thread messages (#4610)"

This reverts commit 7bd5212.

* fix(gmail): bound the first sent-mail scan and keep rate-limited 403s connected

The first sync on #4604 re-read every stored thread of every mailbox at
once; Google answered part of the burst with 403 rateLimitExceeded, which
RevokedGrant read as a revoked grant, so 4 of 18 mailboxes were flagged
needs_reconsent and the release was rolled back (#4610).

- APIError now carries Google's error reason; a 403 whose reason is a rate
  limit or quota is not a revocation (Gmail and Calendar readers).
- The first sent-mail scan expands only the 50 newest stored conversations.

* fix(mentorship): read the Google error reason on calendar and Meet calls

The free/busy and Meet event calls share the grant flag, so a rate-limited
403 there must not read as a revocation either.

* fix(gmail): stop a sync run when Google rate-limits it

A rate-limited 403 or 429 no longer reads as a revocation, so the wave must stop on it by itself instead of issuing every remaining call into the same limit.

* fix(mail): hide deleted linked emails from a job's list

Also documents the 50-thread bound of the first sent-mail backfill in the OpenSpec change.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

large-pr Bypass the PR size check: change cannot be split

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants