Repository navigation
feat[Go]: implement data source gmail and test prune - #17969
Conversation
📝 WalkthroughWalkthroughThe PR adds a Gmail connector with sync and prune sessions, removes persistent prune snapshots in favor of in-memory document IDs, registers Gmail with the syncer, and adds task duration logging. ChangesGmail sync and prune flow
Estimated code review effort: 4 (Complex) | ~45 minutes Possibly related PRs
Suggested labels: Sequence Diagram(s)sequenceDiagram
participant TaskWorker
participant Syncer
participant GmailConnector
participant GmailAPI
participant PruneRunner
participant SyncPruneService
TaskWorker->>Syncer: execute sync task
Syncer->>GmailConnector: open sync or prune session
GmailConnector->>GmailAPI: list and load Gmail threads
GmailAPI-->>GmailConnector: thread data
GmailConnector-->>PruneRunner: prune documents
PruneRunner->>SyncPruneService: pass retained document IDs
SyncPruneService-->>TaskWorker: delete stale documents
TaskWorker-->>TaskWorker: log execution duration
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 7
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/service/sync_prune_service.go (1)
48-56: 🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick winGuard against an empty snapshot before deletion.
DeleteStaledeletes every existing document that is not indocuments. Ifdocumentsis empty,retainis empty and the loop deletes all documents of the connector in the knowledgebase. An empty slice arrives whenever the prune session returnsio.EOFon the first call, for example when a Gmail mailbox is temporarily disabled or when a token refresh silently yields zero threads. The Gmail prune session ininternal/syncer/connector/gmail.go(Line 375) returnsio.EOFwith no documents in exactly that case.The snapshot DAO removal makes this path easier to reach, because no persisted completeness marker remains. Reject the empty snapshot explicitly.
🛡️ Proposed guard
func (s *SyncPruneService) DeleteStale(ctx context.Context, taskContext SyncTaskContext, documents []syncerconnector.SlimDocument) (int64, error) { + if len(documents) == 0 { + return 0, nil + } sourceIDs := make([]string, 0, len(documents))If an empty source snapshot must delete everything, add a caller-supplied flag so the intent is explicit.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/sync_prune_service.go` around lines 48 - 56, Update SyncPruneService.DeleteStale to reject an empty documents snapshot before calling RetainDocumentIDs or deleting any existing IDs, returning an appropriate error and zero deletion count. Preserve normal pruning for non-empty snapshots; if empty snapshots are intentionally destructive, require an explicit caller-supplied flag instead of allowing the current implicit behavior.
🧹 Nitpick comments (8)
internal/syncer/prune_runner.go (1)
43-43: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove or correct the comment.
The comment says "Get the run session". The call opens the prune session. The statement below it is self-explanatory, so deletion is the simplest fix.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/syncer/prune_runner.go` at line 43, Remove the misleading “Get the run session” comment immediately before the prune-session-opening call, leaving the self-explanatory statement unchanged.internal/syncer/connector/gmail.go (5)
140-146: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winUse
errors.Asfor the Google error checks.
getUserEmails,isGmailDisabled, andisGoogleForbiddenOrNotFounduse the direct type assertionerr.(googleHTTPError). The assertion fails if any caller wraps the error with%w.errors.Askeeps the checks correct after future wrapping.Also consider treating HTTP 403 from the Directory API as the personal-account fallback. Google returns 403 for accounts that are not Workspace admins, not only 404.
♻️ Proposed change for the helpers
func isGmailDisabled(err error) bool { - if httpErr, ok := err.(googleHTTPError); ok { + var httpErr googleHTTPError + if errors.As(err, &httpErr) { return httpErr.status == http.StatusBadRequest && (strings.Contains(httpErr.body, "Mail service not enabled") || strings.Contains(httpErr.body, "failedPrecondition")) } return false } // isGoogleForbiddenOrNotFound reports item-level Google visibility failures. func isGoogleForbiddenOrNotFound(err error) bool { - if httpErr, ok := err.(googleHTTPError); ok { + var httpErr googleHTTPError + if errors.As(err, &httpErr) { return httpErr.status == http.StatusForbidden || httpErr.status == http.StatusNotFound } return false }Add the
errorsimport.Also applies to: 666-680
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/syncer/connector/gmail.go` around lines 140 - 146, Update getUserEmails, isGmailDisabled, and isGoogleForbiddenOrNotFound to use errors.As when extracting googleHTTPError so wrapped errors are handled correctly. In the Directory API handling within getUserEmails, treat both HTTP 403 and 404 as the personal-account fallback returning primaryAdminEmail; preserve other errors unchanged.
64-64: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the Python-compatibility wording from the comments.
Three doc comments describe the code by reference to the Python implementation: "Python-compatible config", "Python-compatible Gmail time range query text", and "mirrors Python's sanitized filename intent". Describe the current behavior instead.
Based on learnings from the coding guidelines: "Do not add new compatibility wording in comments or documentation."
Also applies to: 606-606, 656-656
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/syncer/connector/gmail.go` at line 64, Update the doc comments near NewGmailConnector and the referenced time-range query and sanitized-filename logic to remove Python-compatibility references. Describe the actual current behavior directly, without mentioning Python, compatibility, or mirroring another implementation.Source: Coding guidelines
568-589: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winVerify the intended MIME handling and the duplicated extraction logic.
gmailPayloadTextandgmailPartTextcontain the identical extraction rule for two structurally identical types.gmailPayloadandgmailPartdiffer only by theHeadersfield. Consider one recursive function overgmailPartand one small adapter, which removes the duplication.Also confirm the
text/plain-only rule. Messages that carry onlytext/htmlproduce an empty blob, which matches the FIXME on Line 51.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/syncer/connector/gmail.go` around lines 568 - 589, Consolidate the duplicated text extraction in gmailPayloadText and gmailPartText by routing payload handling through a single recursive gmailPart-based implementation, using a small adapter for gmailPayload. Preserve the existing recursive traversal and text/plain-only behavior, including empty output for HTML-only messages as documented by the FIXME.Source: Coding guidelines
49-51: 📐 Maintainability & Code Quality | 🔵 TrivialResolve or track the three FIXME notes before merge.
The repository guidelines require removal of "move later" notes instead of preserving them. Two of the three notes have identifiable root causes in this same file:
- "update all file's Metadata" on every sync:
toTextSection(Line 537) builds the document body by ranging over a Go map. Map iteration order is randomized, so the blob bytes change on every sync and the document looks modified.- "no content":
gmailPayloadTextandgmailPartTextonly extracttext/plain. Messages that carry onlytext/htmlproduce an empty blob.I can open an issue that tracks these two root causes, or generate the fixes directly. Tell me which you prefer.
Based on learnings from the coding guidelines: "Remove dead tests, commented-out code, stale documentation, and 'move later' notes instead of preserving them."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/syncer/connector/gmail.go` around lines 49 - 51, Remove the three FIXME comments in the Gmail connector and fix the identified causes: make toTextSection produce deterministic output by sorting map keys before building the document body, and update gmailPayloadText/gmailPartText to extract text/html when text/plain is unavailable. Do not preserve the “move later” notes; ensure messages with HTML-only content yield non-empty text.Source: Coding guidelines
271-353: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoffConsolidate the duplicated session implementations.
gmailSyncSessionandgmailPruneSessionhold the same fields and run the same batching, buffering, and user-advance algorithm. Only the element type and the page-to-document conversion differ. A generic session type parameterized on the document type removes about 70 duplicated lines.The repository guidelines ask for collapsed duplicate implementations.
Also applies to: 355-428
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/syncer/connector/gmail.go` around lines 271 - 353, Consolidate gmailSyncSession and gmailPruneSession into one generic session type parameterized by document type, preserving the shared fields and batching, buffering, user advancement, and Close behavior. Extract the common NextBatch and advanceUser logic into the generic implementation, while allowing each caller’s page-fetching logic to supply its document conversion. Update both Gmail sync and prune flows to use the shared session and remove their duplicate session implementations.Source: Coding guidelines
internal/syncer/connector/gmail_test.go (1)
14-72: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd coverage for the batch-buffer path.
The fixture returns one thread for one user, and
batch_sizeis 1. The buffer branch ingmailSyncSession.NextBatch(gmail.goLines 284-305) and the multi-useradvanceUserpath never execute. That branch splits a page across batches and is the most error-prone logic in the session.Add a case with several users and a page that holds more threads than
batch_size. Assert that the secondNextBatchreturns the buffered remainder before the connector issues another list call.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/syncer/connector/gmail_test.go` around lines 14 - 72, Add a focused test alongside TestGmailConnectorOpenSync using multiple users and a page containing more threads than batch_size. Exercise gmailSyncSession.NextBatch and advanceUser by asserting the first batch is limited to batch_size, the second returns the buffered remainder, and no additional Gmail list call occurs before that buffered batch is consumed.internal/syncer/syncer_test.go (1)
458-473: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd the positive prune test for the new in-memory path.
This test proves that a failing source deletes nothing. The refactor also changed the success path: the runner now unions all batches in memory and passes them to
DeleteStaleonce. No test in this range covers that path.Add two cases:
- Several successful
PruneBatchesfollowed byio.EOF. Assert that a document present in the store but absent from the union is deleted, and that a document present in the union survives. This confirms the accumulation across batches.- A session that returns
io.EOFon the first call. Assert the expected behavior for the empty snapshot. This pins the decision raised oninternal/service/sync_prune_service.goLine 48.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/syncer/syncer_test.go` around lines 458 - 473, Extend the prune tests around TestPruneSourceFailureDoesNotDelete with success cases for the in-memory batch path: configure multiple successful PruneBatches followed by io.EOF, then assert DeleteStale removes store-only documents while preserving documents present in the accumulated union. Add a first-call io.EOF case and assert the intended empty-snapshot behavior, covering the decision implemented in the prune runner and DeleteStale flow.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/service/sync_task_service.go`:
- Around line 110-111: Remove the unscoped TODO comment near the sync task
service functions. Do not leave a vague refactoring note; either perform the
specific refactor now or remove the comment and track any remaining work
separately.
In `@internal/syncer/connector/gmail.go`:
- Around line 629-635: Update parseGmailAddress to parse address lists with
mail.ParseAddressList, selecting the appropriate parsed address for the returned
email and name; if list parsing fails, fall back to mail.ParseAddress before
retaining the existing trimmed-value fallback.
- Around line 164-212: Update GmailConnector and clientForUser to cache
authenticated HTTP clients by user email, returning the existing client when
available and creating/storing one only on a cache miss. Ensure listThreads and
loadThread continue using clientForUser so requests for the same mailbox reuse
the cached client while different users remain isolated.
- Around line 251-269: Update GmailConnector.getJSON to stop assigning
client.Timeout, since the supplied http.Client may be shared; instead derive a
request-scoped context with a gmailRequestTimeout deadline before creating or
sending the request, preserving cancellation and ensuring the derived context is
released.
- Around line 535-542: Update the metadata-appending logic in the function
containing builder and gmailPayloadText so it emits headers using a fixed,
deterministic order instead of ranging directly over metadata. Preserve the
existing exclusion of updated_at and formatting, and ensure missing metadata
keys are handled without changing the output contract.
- Around line 461-494: Update the message aggregation loop around metadata
assignment and updatedAt parsing so per-message headers do not overwrite earlier
values unintentionally; preserve the intended representative metadata while
processing all messages. When parsing updated_at, compare each valid timestamp
with the current updatedAt and retain the maximum value, rather than always
assigning the last parsed date.
In `@internal/syncer/prune_runner.go`:
- Around line 54-66: The prune runner currently accumulates every SlimDocument
in memory before calling DeleteStale. Update the loop around session.NextBatch
and the pruneService API usage to retain only the minimal identifiers or hash
set required by RetainDocumentIDs, avoiding storage of complete SlimDocument
values; preserve the existing prune behavior while keeping memory usage bounded
per document.
---
Outside diff comments:
In `@internal/service/sync_prune_service.go`:
- Around line 48-56: Update SyncPruneService.DeleteStale to reject an empty
documents snapshot before calling RetainDocumentIDs or deleting any existing
IDs, returning an appropriate error and zero deletion count. Preserve normal
pruning for non-empty snapshots; if empty snapshots are intentionally
destructive, require an explicit caller-supplied flag instead of allowing the
current implicit behavior.
---
Nitpick comments:
In `@internal/syncer/connector/gmail_test.go`:
- Around line 14-72: Add a focused test alongside TestGmailConnectorOpenSync
using multiple users and a page containing more threads than batch_size.
Exercise gmailSyncSession.NextBatch and advanceUser by asserting the first batch
is limited to batch_size, the second returns the buffered remainder, and no
additional Gmail list call occurs before that buffered batch is consumed.
In `@internal/syncer/connector/gmail.go`:
- Around line 140-146: Update getUserEmails, isGmailDisabled, and
isGoogleForbiddenOrNotFound to use errors.As when extracting googleHTTPError so
wrapped errors are handled correctly. In the Directory API handling within
getUserEmails, treat both HTTP 403 and 404 as the personal-account fallback
returning primaryAdminEmail; preserve other errors unchanged.
- Line 64: Update the doc comments near NewGmailConnector and the referenced
time-range query and sanitized-filename logic to remove Python-compatibility
references. Describe the actual current behavior directly, without mentioning
Python, compatibility, or mirroring another implementation.
- Around line 568-589: Consolidate the duplicated text extraction in
gmailPayloadText and gmailPartText by routing payload handling through a single
recursive gmailPart-based implementation, using a small adapter for
gmailPayload. Preserve the existing recursive traversal and text/plain-only
behavior, including empty output for HTML-only messages as documented by the
FIXME.
- Around line 49-51: Remove the three FIXME comments in the Gmail connector and
fix the identified causes: make toTextSection produce deterministic output by
sorting map keys before building the document body, and update
gmailPayloadText/gmailPartText to extract text/html when text/plain is
unavailable. Do not preserve the “move later” notes; ensure messages with
HTML-only content yield non-empty text.
- Around line 271-353: Consolidate gmailSyncSession and gmailPruneSession into
one generic session type parameterized by document type, preserving the shared
fields and batching, buffering, user advancement, and Close behavior. Extract
the common NextBatch and advanceUser logic into the generic implementation,
while allowing each caller’s page-fetching logic to supply its document
conversion. Update both Gmail sync and prune flows to use the shared session and
remove their duplicate session implementations.
In `@internal/syncer/prune_runner.go`:
- Line 43: Remove the misleading “Get the run session” comment immediately
before the prune-session-opening call, leaving the self-explanatory statement
unchanged.
In `@internal/syncer/syncer_test.go`:
- Around line 458-473: Extend the prune tests around
TestPruneSourceFailureDoesNotDelete with success cases for the in-memory batch
path: configure multiple successful PruneBatches followed by io.EOF, then assert
DeleteStale removes store-only documents while preserving documents present in
the accumulated union. Add a first-call io.EOF case and assert the intended
empty-snapshot behavior, covering the decision implemented in the prune runner
and DeleteStale flow.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: dc37ebbb-97b3-406e-9b21-8adc319eb9e1
📒 Files selected for processing (9)
internal/dao/sync_prune_snapshot.gointernal/service/sync_prune_service.gointernal/service/sync_task_service.gointernal/syncer/connector/gmail.gointernal/syncer/connector/gmail_test.gointernal/syncer/prune_runner.gointernal/syncer/syncer.gointernal/syncer/syncer_test.gointernal/syncer/task_worker.go
💤 Files with no reviewable changes (1)
- internal/dao/sync_prune_snapshot.go
Summary
As title