Skip to content

feat[Go]: implement data source gmail and test prune - #17969

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
Haruko386:master
Aug 7, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
Haruko386:master

Conversation

@Haruko386

Copy link
Copy Markdown
Member

Summary

As title

@Haruko386 Haruko386 added the 💞 feature Feature request, pull request that fullfill a new feature. label Aug 7, 2026
@Haruko386
Haruko386 marked this pull request as ready for review August 7, 2026 03:54
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Aug 7, 2026
@Haruko386 Haruko386 added ci Continue Integration and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Aug 7, 2026
@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The 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.

Changes

Gmail sync and prune flow

Layer / File(s) Summary
Gmail connector and API integration
internal/syncer/connector/gmail.go
Adds Gmail configuration validation, OAuth authentication, mailbox discovery, Gmail API access, pagination, and error handling.
Gmail sessions and document conversion
internal/syncer/connector/gmail.go, internal/syncer/connector/gmail_test.go
Adds sync and prune sessions, message decoding, document conversion, metadata extraction, time-range queries, and connector tests.
In-memory stale-document pruning
internal/dao/sync_prune_snapshot.go, internal/service/sync_prune_service.go, internal/syncer/prune_runner.go, internal/syncer/syncer_test.go
Removes the prune snapshot DAO. PruneRunner collects document IDs in memory, and SyncPruneService derives source IDs from those documents.
Syncer registration and duration logging
internal/syncer/syncer.go, internal/syncer/task_worker.go, internal/service/sync_task_service.go
Registers Gmail, updates prune-service construction, logs sync duration, and adds a task-service TODO comment.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

Suggested labels: go

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
Loading

Poem

I’m a rabbit with inbox trails,
Sorting threads through moonlit mails.
Snapshots rest; documents flow,
Stale sources hop where deletions go.
Timers tick, and Gmail sings. 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description only says "As title" and does not provide the required summary or background context. Replace "As title" with a brief summary of the Gmail connector implementation, prune changes, and relevant background for reviewers.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the main changes: adding a Gmail data source and testing prune behavior.

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

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 win

Guard against an empty snapshot before deletion.

DeleteStale deletes every existing document that is not in documents. If documents is empty, retain is empty and the loop deletes all documents of the connector in the knowledgebase. An empty slice arrives whenever the prune session returns io.EOF on 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 in internal/syncer/connector/gmail.go (Line 375) returns io.EOF with 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 value

Remove 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 win

Use errors.As for the Google error checks.

getUserEmails, isGmailDisabled, and isGoogleForbiddenOrNotFound use the direct type assertion err.(googleHTTPError). The assertion fails if any caller wraps the error with %w. errors.As keeps 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 errors import.

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 win

Remove 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 win

Verify the intended MIME handling and the duplicated extraction logic.

gmailPayloadText and gmailPartText contain the identical extraction rule for two structurally identical types. gmailPayload and gmailPart differ only by the Headers field. Consider one recursive function over gmailPart and one small adapter, which removes the duplication.

Also confirm the text/plain-only rule. Messages that carry only text/html produce 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 | 🔵 Trivial

Resolve 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": gmailPayloadText and gmailPartText only extract text/plain. Messages that carry only text/html produce 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 tradeoff

Consolidate the duplicated session implementations.

gmailSyncSession and gmailPruneSession hold 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 win

Add coverage for the batch-buffer path.

The fixture returns one thread for one user, and batch_size is 1. The buffer branch in gmailSyncSession.NextBatch (gmail.go Lines 284-305) and the multi-user advanceUser path 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 second NextBatch returns 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 win

Add 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 DeleteStale once. No test in this range covers that path.

Add two cases:

  • Several successful PruneBatches followed by io.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.EOF on the first call. Assert the expected behavior for the empty snapshot. This pins the decision raised on internal/service/sync_prune_service.go Line 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

📥 Commits

Reviewing files that changed from the base of the PR and between 27c8b1a and cf95933.

📒 Files selected for processing (9)
  • internal/dao/sync_prune_snapshot.go
  • internal/service/sync_prune_service.go
  • internal/service/sync_task_service.go
  • internal/syncer/connector/gmail.go
  • internal/syncer/connector/gmail_test.go
  • internal/syncer/prune_runner.go
  • internal/syncer/syncer.go
  • internal/syncer/syncer_test.go
  • internal/syncer/task_worker.go
💤 Files with no reviewable changes (1)
  • internal/dao/sync_prune_snapshot.go

Comment thread internal/service/sync_task_service.go Resolved
Comment thread internal/syncer/connector/gmail.go Resolved
Comment thread internal/syncer/connector/gmail.go Resolved
Comment thread internal/syncer/connector/gmail.go Resolved
Comment thread internal/syncer/connector/gmail.go Resolved
Comment thread internal/syncer/connector/gmail.go Resolved
Comment thread internal/syncer/prune_runner.go Resolved
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Aug 7, 2026
@Haruko386 Haruko386 removed the ci Continue Integration label Aug 7, 2026
@Haruko386
Haruko386 marked this pull request as draft August 7, 2026 05:10
@Haruko386
Haruko386 marked this pull request as ready for review August 7, 2026 05:10
@Haruko386 Haruko386 added the ci Continue Integration label Aug 7, 2026
@JinHai-CN
JinHai-CN merged commit 615c7d8 into infiniflow:main Aug 7, 2026
7 of 9 checks passed
@Haruko386
Haruko386 deleted the master branch August 10, 2026 08:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants