diff --git a/internal/datasource/connector/notion/client.go b/internal/datasource/connector/notion/client.go index d5d07171..fc5f3a07 100644 --- a/internal/datasource/connector/notion/client.go +++ b/internal/datasource/connector/notion/client.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -341,13 +342,23 @@ func (c *notionClient) getBlockChildrenRecursive(ctx context.Context, blockID st // QueryDatabaseAll retrieves all records from a database via POST /v1/data_sources/{id}/query. // Accepts either a data_source_id (from search) or a database_id (from child_database blocks). // For database_ids, resolves to data_source_id via GET /v1/databases/{id}. +// The record set is read through created_time windows, so a data source holding +// more rows than one vendor query can return is still read in full. func (c *notionClient) QueryDatabaseAll(ctx context.Context, id string) ([]notionPage, error) { // Try as data_source_id directly - records, err := c.paginatePages(ctx, http.MethodPost, fmt.Sprintf("/v1/data_sources/%s/query", id)) + records, err := c.queryDataSourceAll(ctx, fmt.Sprintf("/v1/data_sources/%s/query", id)) if err == nil { return records, nil } + // An incomplete walk reached the data source successfully. Resolving the ID as + // a database container would only repeat the same capped query and would bury + // the truncation error behind a misleading lookup failure, so surface it here + // together with the rows fetched so far. + if errors.Is(err, errQueryResultTruncated) { + return records, err + } + // If 404, id might be a database container ID — resolve to data_source_id info, dbErr := c.GetDatabaseInfo(ctx, id) if dbErr != nil { @@ -356,7 +367,7 @@ func (c *notionClient) QueryDatabaseAll(ctx context.Context, id string) ([]notio if info.DataSourceID == "" { return nil, fmt.Errorf("database %s has no data sources", id) } - return c.paginatePages(ctx, http.MethodPost, fmt.Sprintf("/v1/data_sources/%s/query", info.DataSourceID)) + return c.queryDataSourceAll(ctx, fmt.Sprintf("/v1/data_sources/%s/query", info.DataSourceID)) } // ResolveBlock re-fetches a single block to resolve file_upload URLs. @@ -429,7 +440,19 @@ func (c *notionClient) DownloadFile(ctx context.Context, fileURL string) ([]byte // --- Shared pagination helper --- -// paginatePages fetches all pages from a paginated Notion API endpoint. +// errQueryResultTruncated reports that a paginated response was cut short by a +// vendor-side limit, so the rows collected so far are a prefix of the result set +// rather than all of it. Notion signals this with has_more=false plus +// request_status.type="incomplete" (for a data source query at the 10,000-row +// limit: incomplete_reason="query_result_limit_reached"), which without this +// check is indistinguishable from a complete result set. Callers must not treat +// rows missing from such a result as deleted at source. +var errQueryResultTruncated = errors.New("notion paginated response incomplete: vendor limit reached") + +// paginatePages fetches all pages from a cursor-paginated Notion API endpoint +// (POST /v1/search). Endpoints that can return more rows than a single query +// allows — data source queries — go through queryDataSourceAll instead, which +// splits the walk into created_time windows when the vendor caps a query. func (c *notionClient) paginatePages(ctx context.Context, method, path string) ([]notionPage, error) { var allPages []notionPage var startCursor string @@ -473,6 +496,16 @@ func (c *notionClient) paginatePages(ctx context.Context, method, path string) ( allPages = append(allPages, pages...) + // The vendor marks a capped page as incomplete while still reporting + // has_more=false, so this per-page check is the only way to tell "cut + // short" from "read to the end". Keep the rows this page did return, then + // surface the sentinel so callers can use the partial data without reading + // absence from it as a source-side deletion. + if resp.isIncomplete() { + return allPages, fmt.Errorf("%w: %s (path %s, %d records fetched)", + errQueryResultTruncated, resp.RequestStatus.IncompleteReason, path, len(allPages)) + } + if !resp.HasMore || resp.NextCursor == "" { break } @@ -482,6 +515,161 @@ func (c *notionClient) paginatePages(ctx context.Context, method, path string) ( return allPages, nil } +// --- Data source query: read past the per-query result limit --- + +// dataSourceQueryPageSize is the page size requested for every data source query page. +const dataSourceQueryPageSize = 100 + +// errWindowNotAdvancing reports that an incomplete window could not be followed +// by a later one: no returned row carried a created_time, or every row in the +// window shares the timestamp the window started at. Both mean the remaining +// rows cannot be reached by moving the created_time boundary, so the walk stops +// instead of re-querying the same window forever. +var errWindowNotAdvancing = errors.New("created_time window cannot advance") + +// queryDataSourceAll reads every row of a data source query, splitting the walk +// into created_time windows whenever the vendor caps a query at its per-query +// result limit. +// +// A capped query answers has_more=false together with +// request_status.type="incomplete", so a caller that only follows next_cursor +// stops at the limit without noticing. The vendor's recipe for reading past it is +// to sort by created_time ascending and, each time a window comes back +// incomplete, to re-query with filter.created_time.on_or_after set to the +// created_time of the last row seen; rows sitting exactly on that boundary are +// returned by both windows and are de-duplicated here by row ID. created_time is +// used deliberately instead of last_edited_time: it never changes, so a window +// boundary stays valid while the walk is in progress, whereas last_edited_time +// moves rows between windows as they are edited. +// See https://developers.notion.com/guides/data-apis/query-large-data-sources +// +// When a window cannot advance, the walk stops and the rows collected so far are +// returned together with errQueryResultTruncated, so callers still learn that the +// result set is incomplete instead of reading absence from it as deletion. +func (c *notionClient) queryDataSourceAll(ctx context.Context, path string) ([]notionPage, error) { + var allRows []notionPage + seen := make(map[string]bool, dataSourceQueryPageSize) + var windowStart *time.Time + + for { + rows, lastCreatedTime, incompleteReason, err := c.queryDataSourceWindow(ctx, path, windowStart) + if err != nil { + return nil, err + } + for i := range rows { + if id := rows[i].ID; id != "" { + if seen[id] { + continue + } + seen[id] = true + } + allRows = append(allRows, rows[i]) + } + + if incompleteReason == "" { + return allRows, nil + } + + // The vendor capped this window, so the rows past the limit are only + // reachable from a later window. The next window must start strictly after + // the current one, otherwise it would return the same rows again. + if lastCreatedTime.IsZero() { + logger.Warnf(ctx, "[Notion] query %s is incomplete (%s) but returned no row carrying created_time; "+ + "stopping with %d records instead of re-querying the same window", + path, incompleteReason, len(allRows)) + return allRows, fmt.Errorf("%w: %s: %w: %s returned an incomplete window "+ + "without any created_time (%d records fetched)", + errQueryResultTruncated, incompleteReason, errWindowNotAdvancing, path, len(allRows)) + } + if windowStart != nil && !lastCreatedTime.After(*windowStart) { + logger.Warnf(ctx, "[Notion] query %s is still incomplete (%s) at created_time %s, which does not advance "+ + "the window start; stopping with %d records: more rows than the vendor per-query limit share "+ + "one created_time", path, incompleteReason, + lastCreatedTime.UTC().Format(time.RFC3339Nano), len(allRows)) + return allRows, fmt.Errorf("%w: %s: %w: %s did not advance past created_time %s (%d records fetched)", + errQueryResultTruncated, incompleteReason, errWindowNotAdvancing, path, + lastCreatedTime.UTC().Format(time.RFC3339Nano), len(allRows)) + } + + // Keep the truncation visible: the first window hit the vendor limit, and + // the log line records where the next window starts. + logger.Warnf(ctx, "[Notion] query %s hit the vendor per-query result limit (%s); "+ + "continuing from created_time %s (%d records fetched so far)", path, incompleteReason, + lastCreatedTime.UTC().Format(time.RFC3339Nano), len(allRows)) + start := lastCreatedTime + windowStart = &start + } +} + +// queryDataSourceWindow drains one created_time window: it follows next_cursor +// until the window is exhausted, and reports the created_time of the last row it +// saw plus the vendor's incomplete_reason when any page of the window was marked +// incomplete (an empty reason means the window was read to the end). +// A nil windowStart reads the first, unfiltered window. +func (c *notionClient) queryDataSourceWindow( + ctx context.Context, path string, windowStart *time.Time, +) (rows []notionPage, lastCreatedTime time.Time, incompleteReason string, err error) { + var startCursor string + + for { + body := map[string]interface{}{ + "page_size": dataSourceQueryPageSize, + "sorts": []map[string]string{ + {"timestamp": "created_time", "direction": "ascending"}, + }, + } + if windowStart != nil { + body["filter"] = map[string]interface{}{ + "timestamp": "created_time", + "created_time": map[string]string{ + "on_or_after": windowStart.UTC().Format(time.RFC3339Nano), + }, + } + } + if startCursor != "" { + body["start_cursor"] = startCursor + } + + respBody, doErr := c.doRequest(ctx, http.MethodPost, path, body) + if doErr != nil { + return nil, time.Time{}, "", fmt.Errorf("paginate %s: %w", path, doErr) + } + + var resp paginatedResponse + if unmarshalErr := json.Unmarshal(respBody, &resp); unmarshalErr != nil { + return nil, time.Time{}, "", fmt.Errorf("unmarshal paginated response: %w", unmarshalErr) + } + + var pageRows []notionPage + if unmarshalErr := json.Unmarshal(resp.Results, &pageRows); unmarshalErr != nil { + return nil, time.Time{}, "", fmt.Errorf("unmarshal page results: %w", unmarshalErr) + } + for i := range pageRows { + pageRows[i].Title = extractTitle(&pageRows[i]) + // Rows arrive sorted by created_time ascending, so the last row + // carrying a timestamp is this window's boundary. + if !pageRows[i].CreatedTime.IsZero() { + lastCreatedTime = pageRows[i].CreatedTime + } + } + rows = append(rows, pageRows...) + + // The marker is latched for the whole window: it can appear on any page + // of a capped query, including before the last page received. + if resp.isIncomplete() { + incompleteReason = resp.RequestStatus.IncompleteReason + if incompleteReason == "" { + incompleteReason = "incomplete" + } + } + + if !resp.HasMore || resp.NextCursor == "" { + return rows, lastCreatedTime, incompleteReason, nil + } + startCursor = resp.NextCursor + } +} + // --- Title extraction helpers --- func extractTitle(page *notionPage) string { diff --git a/internal/datasource/connector/notion/connector.go b/internal/datasource/connector/notion/connector.go index 268fae56..9a224e0e 100644 --- a/internal/datasource/connector/notion/connector.go +++ b/internal/datasource/connector/notion/connector.go @@ -3,6 +3,7 @@ package notion import ( "context" "encoding/json" + "errors" "fmt" "sort" "strings" @@ -147,13 +148,14 @@ func (c *Connector) FetchAll(ctx context.Context, config *types.DataSourceConfig for _, resourceID := range resourceIDs { page, err := client.GetPage(ctx, resourceID) if err == nil { - allItems = append(allItems, c.fetchPage(ctx, client, page, visited)...) + pageItems, _ := c.fetchPage(ctx, client, page, visited) + allItems = append(allItems, pageItems...) continue } // Not a page — treat as database/data_source. // fetchDatabase handles both data_source IDs (from search) and // database container IDs (from child_database blocks). - items := c.fetchDatabase(ctx, client, resourceID, visited) + items, _ := c.fetchDatabase(ctx, client, resourceID, visited) if len(items) == 0 { logger.Warnf(ctx, "[Notion] failed to fetch resource %s as page or database", resourceID) } @@ -235,6 +237,10 @@ func (c *Connector) FetchIncremental(ctx context.Context, config *types.DataSour var changedItems []types.FetchedItem changedCount := 0 + // queryTruncated records whether any query this round came back capped by a + // vendor limit. A capped query only reports a prefix of its records, so the + // deletion pass must be skipped for the whole round. + var queryTruncated bool for pageID, newTime := range newEditTimes { prevTime, existed := prevCursor.PageEditTimes[pageID] @@ -253,14 +259,18 @@ func (c *Connector) FetchIncremental(ctx context.Context, config *types.DataSour if pg.isDatabase() { // Incremental database sync: query records, diff against cursor, // only fetch blocks for records whose edit time actually changed. - items, recordEditTimes := c.fetchDatabaseIncremental(ctx, client, pg.ID, prevCursor.PageEditTimes, fetchVisited) + items, recordEditTimes, truncated := c.fetchDatabaseIncremental( + ctx, client, pg.ID, prevCursor.PageEditTimes, fetchVisited) + queryTruncated = queryTruncated || truncated changedItems = append(changedItems, items...) // Merge record-level edit times into the cursor for rid, rt := range recordEditTimes { newEditTimes[rid] = rt } } else { - changedItems = append(changedItems, c.fetchPage(ctx, client, pg, fetchVisited)...) + items, truncated := c.fetchPage(ctx, client, pg, fetchVisited) + queryTruncated = queryTruncated || truncated + changedItems = append(changedItems, items...) } } @@ -269,21 +279,36 @@ func (c *Connector) FetchIncremental(ctx context.Context, config *types.DataSour // are still visible but no longer reachable from any selected root (i.e. the // user deselected their ancestor) live in fetchVisited as the "excluded" set // returned by discoverAllResources, and must NOT be reported as deletions. - for pageID := range prevCursor.PageEditTimes { - if _, exists := newEditTimes[pageID]; exists { - continue + // + // A truncated query reports only a prefix of its records, so a record absent + // from it is not evidence of a source-side deletion. When any query this + // round hit a vendor limit, skip deletion detection entirely instead of + // deleting live documents (same direction as aborting incremental sync when + // resource discovery fails, #3682). + if queryTruncated { + logger.Warnf(ctx, "[Notion] skipping deletion detection: at least one query was truncated at the vendor limit") + } else { + for pageID := range prevCursor.PageEditTimes { + if _, exists := newEditTimes[pageID]; exists { + continue + } + if fetchVisited[pageID] { + continue + } + changedItems = append(changedItems, types.FetchedItem{ + ExternalID: pageID, + IsDeleted: true, + Metadata: map[string]string{"channel": types.ChannelNotion}, + }) } - if fetchVisited[pageID] { - continue - } - changedItems = append(changedItems, types.FetchedItem{ - ExternalID: pageID, - IsDeleted: true, - Metadata: map[string]string{"channel": types.ChannelNotion}, - }) } - logger.Infof(ctx, "[Notion] incremental: %d changed, %d total items", changedCount, len(changedItems)) + if queryTruncated { + logger.Warnf(ctx, "[Notion] incremental: %d changed, %d total items, result set truncated by the vendor", + changedCount, len(changedItems)) + } else { + logger.Infof(ctx, "[Notion] incremental: %d changed, %d total items", changedCount, len(changedItems)) + } return changedItems, buildCursor(newEditTimes), nil } @@ -307,17 +332,21 @@ func buildCursor(editTimes map[string]time.Time) *types.SyncCursor { // fetchPage fetches a single page's content and attachments. // If page is nil, it will be fetched from the API. -func (c *Connector) fetchPage(ctx context.Context, client *notionClient, page *notionPage, visited map[string]bool) []types.FetchedItem { +// The second result reports whether any query issued for this page (including +// child databases) was truncated at a vendor limit. +func (c *Connector) fetchPage( + ctx context.Context, client *notionClient, page *notionPage, visited map[string]bool, +) ([]types.FetchedItem, bool) { if page == nil { - return nil + return nil, false } if visited[page.ID] { - return nil + return nil, false } visited[page.ID] = true if page.InTrash { - return nil + return nil, false } // Database records store content in properties, not blocks — delegate to @@ -333,15 +362,15 @@ func (c *Connector) fetchPage(ctx context.Context, client *notionClient, page *n } propNames := extractPropertySchema(*page) if item := c.buildRecordItem(ctx, client, *page, propNames, dbTitle); item != nil { - return []types.FetchedItem{*item} + return []types.FetchedItem{*item}, false } - return nil + return nil, false } blocks, err := client.GetBlockChildrenAll(ctx, page.ID) if err != nil { logger.Warnf(ctx, "[Notion] failed to get blocks for page %s: %v", page.ID, err) - return nil + return nil, false } resolveFileUploads(ctx, client, blocks) @@ -407,6 +436,7 @@ func (c *Connector) fetchPage(ctx context.Context, client *notionClient, page *n }) } + truncated := false for _, block := range blocks { switch block.Type { case "child_page": @@ -415,30 +445,40 @@ func (c *Connector) fetchPage(ctx context.Context, client *notionClient, page *n logger.Warnf(ctx, "[Notion] failed to get child page %s: %v", block.ID, err) continue } - items = append(items, c.fetchPage(ctx, client, childPage, visited)...) + childItems, childTruncated := c.fetchPage(ctx, client, childPage, visited) + truncated = truncated || childTruncated + items = append(items, childItems...) case "child_database": - items = append(items, c.fetchDatabase(ctx, client, block.ID, visited)...) + dbItems, dbTruncated := c.fetchDatabase(ctx, client, block.ID, visited) + truncated = truncated || dbTruncated + items = append(items, dbItems...) } } - return items + return items, truncated } // fetchDatabase syncs each database record as an individual knowledge item (full sync). // Accepts either a data_source_id (from search) or database_id (from child_database blocks). -func (c *Connector) fetchDatabase(ctx context.Context, client *notionClient, id string, visited map[string]bool) []types.FetchedItem { +// The second result reports whether the record query was truncated at a vendor limit. +func (c *Connector) fetchDatabase( + ctx context.Context, client *notionClient, id string, visited map[string]bool, +) ([]types.FetchedItem, bool) { if visited[id] { - return nil + return nil, false } visited[id] = true - records, dbTitle, queryID, err := c.queryDatabaseRecords(ctx, client, id) - if err != nil || len(records) == 0 { - return nil + records, dbTitle, queryID, truncated, err := c.queryDatabaseRecords(ctx, client, id) + if err != nil { + return nil, false + } + if len(records) == 0 { + return nil, truncated } if queryID != "" && queryID != id { if visited[queryID] { - return nil + return nil, truncated } visited[queryID] = true } @@ -447,28 +487,36 @@ func (c *Connector) fetchDatabase(ctx context.Context, client *notionClient, id visited[record.ID] = true // Mark records as visited to avoid duplicate fetchPage calls } + if truncated { + logger.Warnf(ctx, "[Notion] database %s full sync used a truncated record set (%d records): "+ + "records past the vendor query limit are missing from this run", id, len(records)) + } + item := c.buildDatabaseItem(ctx, client, id, dbTitle, records) if item != nil { - return []types.FetchedItem{*item} + return []types.FetchedItem{*item}, truncated } - return nil + return nil, truncated } // fetchDatabaseIncremental syncs only changed records by comparing edit times against cursor. -// Returns fetched items and a map of record_id → edit_time for cursor update. -func (c *Connector) fetchDatabaseIncremental(ctx context.Context, client *notionClient, id string, prevEditTimes map[string]time.Time, visited map[string]bool) ([]types.FetchedItem, map[string]time.Time) { +// Returns fetched items, a map of record_id → edit_time for cursor update, and whether the +// record query was truncated at a vendor limit (in which case absence proves nothing). +func (c *Connector) fetchDatabaseIncremental( + ctx context.Context, client *notionClient, id string, prevEditTimes map[string]time.Time, visited map[string]bool, +) ([]types.FetchedItem, map[string]time.Time, bool) { if visited[id] { - return nil, nil + return nil, nil, false } visited[id] = true - records, dbTitle, queryID, err := c.queryDatabaseRecords(ctx, client, id) + records, dbTitle, queryID, truncated, err := c.queryDatabaseRecords(ctx, client, id) if err != nil { - return nil, nil + return nil, nil, false } if queryID != "" && queryID != id { if visited[queryID] { - return nil, nil + return nil, nil, truncated } visited[queryID] = true } @@ -490,26 +538,41 @@ func (c *Connector) fetchDatabaseIncremental(ctx context.Context, client *notion } } - logger.Infof(ctx, "[Notion] database %s incremental: %d changed out of %d records", id, changedCount, len(records)) + if truncated { + logger.Warnf(ctx, "[Notion] database %s incremental: %d changed out of %d records "+ + "(truncated at the vendor query limit: result set incomplete)", id, changedCount, len(records)) + } else { + logger.Infof(ctx, "[Notion] database %s incremental: %d changed out of %d records", + id, changedCount, len(records)) + } // Rebuild the entire database table if any record changed, or if we don't have previous times (first sync) if changedCount > 0 || len(prevEditTimes) == 0 { item := c.buildDatabaseItem(ctx, client, id, dbTitle, records) if item != nil { - return []types.FetchedItem{*item}, recordEditTimes + return []types.FetchedItem{*item}, recordEditTimes, truncated } } - return nil, recordEditTimes + return nil, recordEditTimes, truncated } // queryDatabaseRecords resolves the database ID and queries all records. -// Returns the records, the database title, and the canonical data_source_id used for the query. -func (c *Connector) queryDatabaseRecords(ctx context.Context, client *notionClient, id string) ([]notionPage, string, string, error) { +// Records are read through created_time windows, so a data source holding more +// rows than one vendor query can return is still read in full. +// Returns the records, the database title, the canonical data_source_id used for the +// query, whether the result set is incomplete, and an error. An incomplete result +// still returns the rows fetched so far, with truncated set and a nil error, because +// the partial data remains usable as long as callers do not read absence as deletion. +// Truncation is only reported when windowed reading cannot complete (see +// notionClient.queryDataSourceAll). +func (c *Connector) queryDatabaseRecords( + ctx context.Context, client *notionClient, id string, +) ([]notionPage, string, string, bool, error) { dbInfo, err := getDatabaseOrDataSourceInfo(ctx, client, id) if err != nil { logger.Warnf(ctx, "[Notion] failed to get database/data_source info %s: %v", id, err) - return nil, "", "", err + return nil, "", "", false, err } queryID := dbInfo.DataSourceID @@ -517,13 +580,19 @@ func (c *Connector) queryDatabaseRecords(ctx context.Context, client *notionClie queryID = id } records, err := client.QueryDatabaseAll(ctx, queryID) - if err != nil { + truncated := errors.Is(err, errQueryResultTruncated) + if err != nil && !truncated { logger.Warnf(ctx, "[Notion] failed to query database %s: %v", id, err) - return nil, "", "", err + return nil, "", "", false, err } - logger.Infof(ctx, "[Notion] database %s (%s): %d records", id, dbInfo.Page.Title, len(records)) - return records, dbInfo.Page.Title, queryID, nil + if truncated { + logger.Warnf(ctx, "[Notion] database %s (%s): %d records, the vendor query limit was hit and the "+ + "created_time window could not advance: result set incomplete", id, dbInfo.Page.Title, len(records)) + } else { + logger.Infof(ctx, "[Notion] database %s (%s): %d records", id, dbInfo.Page.Title, len(records)) + } + return records, dbInfo.Page.Title, queryID, truncated, nil } // buildRecordItem converts a single database record into a FetchedItem diff --git a/internal/datasource/connector/notion/query_truncation_test.go b/internal/datasource/connector/notion/query_truncation_test.go new file mode 100644 index 00000000..d1169184 --- /dev/null +++ b/internal/datasource/connector/notion/query_truncation_test.go @@ -0,0 +1,238 @@ +package notion + +import ( + "context" + "encoding/json" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/stretchr/testify/require" +) + +// A Notion data source query stops at 10,000 results and reports has_more=false +// together with request_status.type="incomplete". A capped query is no longer the +// end of the read: the client continues in created_time windows (see +// query_windows_test.go). These tests pin down what a window that cannot advance +// does instead — stop, stay visible, and never drive deletions. +// See https://developers.notion.com/guides/data-apis/query-large-data-sources + +const truncationReason = "query_result_limit_reached" + +func truncationIncomplete() map[string]interface{} { + return map[string]interface{}{"type": "incomplete", "incomplete_reason": truncationReason} +} + +func truncationRecord(id string) map[string]interface{} { + return map[string]interface{}{ + "id": id, + "object": "page", + "url": "https://notion.so/" + id, + "last_edited_time": "2026-01-02T10:00:00.000Z", + "in_trash": false, + "parent": map[string]interface{}{"type": "data_source_id", "data_source_id": "ds-1"}, + "properties": map[string]interface{}{ + "Name": map[string]interface{}{ + "type": "title", + "title": []interface{}{map[string]interface{}{"plain_text": "Row " + id}}, + }, + }, + } +} + +func truncationDataSourceRow() map[string]interface{} { + return map[string]interface{}{ + "id": "ds-1", + "object": "data_source", + "url": "https://notion.so/ds-1", + "last_edited_time": "2026-01-02T10:00:00.000Z", + "in_trash": false, + "parent": map[string]interface{}{"type": "workspace", "workspace": true}, + "title": []interface{}{map[string]interface{}{"plain_text": "Large Database"}}, + } +} + +func truncationPrevCursor() *types.SyncCursor { + jan1 := time.Date(2026, 1, 1, 10, 0, 0, 0, time.UTC) + return buildCursor(map[string]time.Time{ + "ds-1": jan1, + "r1": jan1, + "r2": jan1, + "r3": jan1, + "r4": jan1, + }) +} + +func TestPaginatedResponseParsesRequestStatus(t *testing.T) { + t.Run("incomplete", func(t *testing.T) { + var resp paginatedResponse + require.NoError(t, json.Unmarshal([]byte(`{"object":"list","results":[],"has_more":false,`+ + `"next_cursor":null,"request_status":{"type":"incomplete",`+ + `"incomplete_reason":"`+truncationReason+`"}}`), &resp)) + require.True(t, resp.isIncomplete()) + require.Equal(t, truncationReason, resp.RequestStatus.IncompleteReason) + }) + + t.Run("absent", func(t *testing.T) { + var resp paginatedResponse + require.NoError(t, json.Unmarshal([]byte(`{"object":"list","results":[],"has_more":false}`), &resp)) + require.False(t, resp.isIncomplete()) + require.Nil(t, resp.RequestStatus) + }) + + t.Run("explicit complete", func(t *testing.T) { + var resp paginatedResponse + require.NoError(t, json.Unmarshal([]byte(`{"results":[],"has_more":false,`+ + `"request_status":{"type":"complete"}}`), &resp)) + require.False(t, resp.isIncomplete()) + }) +} + +func TestQueryDatabaseAllStopsWhenWindowCannotAdvance(t *testing.T) { + logs := captureNotionLogs(t) + // More rows than one query returns share a single created_time, so the second + // window starts where the first one did and would return the same rows again. + server := newWindowQueryServer(t, windowQueryFake{ + rows: []windowTestRow{ + {id: "r1", createdTime: "2026-01-01T10:00:00Z"}, + {id: "r2", createdTime: "2026-01-01T10:00:00Z"}, + }, + queryLimit: 1, + }) + client := mustTestClient(t, "test-token", server.URL) + + records, err := client.QueryDatabaseAll(context.Background(), "ds-1") + require.ErrorIs(t, err, errQueryResultTruncated, "an unwalkable window must still surface the truncation") + require.ErrorIs(t, err, errWindowNotAdvancing) + require.Contains(t, err.Error(), truncationReason) + require.Equal(t, []string{"r1"}, recordIDs(records), "rows already read stay available to the caller") + require.Equal(t, int32(2), server.queryCalls(), + "the walk must stop as soon as the window stops advancing instead of repeating the same query") + require.Contains(t, logs.String(), "does not advance", "the stop must be explained in a warning") +} + +func TestQueryDatabaseAllStopsWhenRowsCarryNoCreatedTime(t *testing.T) { + logs := captureNotionLogs(t) + server := newWindowQueryServer(t, windowQueryFake{ + rows: []windowTestRow{{id: "r1"}, {id: "r2"}}, + queryLimit: 1, + }) + client := mustTestClient(t, "test-token", server.URL) + + records, err := client.QueryDatabaseAll(context.Background(), "ds-1") + require.ErrorIs(t, err, errQueryResultTruncated) + require.ErrorIs(t, err, errWindowNotAdvancing) + require.Equal(t, []string{"r1"}, recordIDs(records)) + require.Equal(t, int32(1), server.queryCalls(), + "a window without any created_time cannot start another one") + require.Contains(t, logs.String(), "no row carrying created_time") +} + +func TestQueryDatabaseAllStopsOnEmptyIncompleteWindow(t *testing.T) { + logs := captureNotionLogs(t) + server := newWindowQueryServer(t, windowQueryFake{alwaysIncomplete: true}) + client := mustTestClient(t, "test-token", server.URL) + + records, err := client.QueryDatabaseAll(context.Background(), "ds-1") + require.ErrorIs(t, err, errQueryResultTruncated) + require.ErrorIs(t, err, errWindowNotAdvancing) + require.Empty(t, recordIDs(records)) + require.Equal(t, int32(1), server.queryCalls(), "an empty incomplete window must not be re-queried") + require.Contains(t, logs.String(), "no row carrying created_time") +} + +func TestFetchIncrementalTruncatedQuerySkipsDeletions(t *testing.T) { + server := newWindowQueryServer(t, windowQueryFake{ + searchResults: []interface{}{truncationDataSourceRow()}, + rows: []windowTestRow{ + {id: "r1", createdTime: "2026-01-01T10:00:00Z"}, + {id: "r2", createdTime: "2026-01-01T10:00:00Z"}, + }, + queryLimit: 1, + }) + config := makeNotionConfig(&Config{APIKey: "test-token"}, server.URL, []string{"ds-1"}) + + items, next, err := NewConnector().FetchIncremental(context.Background(), config, truncationPrevCursor()) + require.NoError(t, err, "a truncated round is a partial success, not a failed sync") + require.NotNil(t, next, "a truncated round still returns a cursor") + require.Len(t, items, 1) + require.Equal(t, "ds-1", items[0].ExternalID) + require.False(t, items[0].IsDeleted) + for _, item := range items { + require.False(t, item.IsDeleted, + "row %s was missing only because the query was capped and must not be deleted", item.ExternalID) + } +} + +func TestFetchIncrementalCompleteQueryStillDetectsDeletions(t *testing.T) { + server := newWindowQueryServer(t, windowQueryFake{ + searchResults: []interface{}{truncationDataSourceRow()}, + rows: createdTimeRows("r1", "r2"), + }) + config := makeNotionConfig(&Config{APIKey: "test-token"}, server.URL, []string{"ds-1"}) + + items, next, err := NewConnector().FetchIncremental(context.Background(), config, truncationPrevCursor()) + require.NoError(t, err) + require.NotNil(t, next) + + deleted := map[string]bool{} + for _, item := range items { + if item.IsDeleted { + deleted[item.ExternalID] = true + } + } + require.Equal(t, map[string]bool{"r3": true, "r4": true}, deleted, + "a complete result set must keep reporting genuinely absent rows as deleted") +} + +func TestFetchIncrementalWindowedQueryKeepsDeletionDetection(t *testing.T) { + // The data source holds more rows than one query returns, but every window + // advances, so the round ends complete: r4 is genuinely gone and must still be + // reported as deleted. This guards against "never delete anything as soon as + // windowing is involved". + server := newWindowQueryServer(t, windowQueryFake{ + searchResults: []interface{}{truncationDataSourceRow()}, + rows: createdTimeRows("r1", "r2", "r3"), + queryLimit: 2, + pageSize: 2, + }) + config := makeNotionConfig(&Config{APIKey: "test-token"}, server.URL, []string{"ds-1"}) + + items, next, err := NewConnector().FetchIncremental(context.Background(), config, truncationPrevCursor()) + require.NoError(t, err) + require.NotNil(t, next) + + deleted := map[string]bool{} + for _, item := range items { + if item.IsDeleted { + deleted[item.ExternalID] = true + } + } + require.Equal(t, map[string]bool{"r4": true}, deleted, + "rows read across windows prove the rows that are absent at source are deleted") +} + +func TestFetchPagePropagatesTruncationFromChildDatabase(t *testing.T) { + server := newWindowQueryServer(t, windowQueryFake{ + rows: []windowTestRow{ + {id: "r1", createdTime: "2026-01-01T10:00:00Z"}, + {id: "r2", createdTime: "2026-01-01T10:00:00Z"}, + }, + queryLimit: 1, + blocks: map[string][]interface{}{ + "page-1": {map[string]interface{}{ + "id": "ds-1", "type": "child_database", "has_children": true, + "child_database": map[string]interface{}{"title": "Embedded Database"}, + }}, + }, + }) + client := mustTestClient(t, "test-token", server.URL) + page := ¬ionPage{ + ID: "page-1", + Object: "page", + Parent: notionParent{Type: parentTypeWorkspace}, + } + + _, truncated := NewConnector().fetchPage(context.Background(), client, page, map[string]bool{}) + require.True(t, truncated, "a capped child database query must reach the incremental round") +} diff --git a/internal/datasource/connector/notion/query_windowing_test.go b/internal/datasource/connector/notion/query_windowing_test.go new file mode 100644 index 00000000..61496f36 --- /dev/null +++ b/internal/datasource/connector/notion/query_windowing_test.go @@ -0,0 +1,412 @@ +package notion + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/logger" + "github.com/stretchr/testify/require" +) + +// A single data source query returns at most 10,000 rows; the vendor's recipe for +// reading a larger data source is to sort by created_time ascending and to start a +// new window (filter created_time.on_or_after = the last row of the previous +// window) every time a query comes back with request_status.type="incomplete", +// de-duplicating rows by ID. +// See https://developers.notion.com/guides/data-apis/query-large-data-sources +// +// The fake server below answers queries that way, with the vendor's per-query +// limit, the page size and the window boundaries scaled down to test size, and it +// records every request body so tests can assert on the window filter and on the +// created_time sort. + +type windowTestRow struct { + id string + createdTime string // RFC3339; empty emulates a row without created_time +} + +// createdTimeRows builds rows one minute apart, in created_time ascending order. +func createdTimeRows(ids ...string) []windowTestRow { + rows := make([]windowTestRow, 0, len(ids)) + base := time.Date(2026, 1, 1, 10, 0, 0, 0, time.UTC) + for i, id := range ids { + createdTime := base.Add(time.Duration(i) * time.Minute).Format(time.RFC3339) + rows = append(rows, windowTestRow{id: id, createdTime: createdTime}) + } + return rows +} + +type windowQueryFake struct { + // rows is the whole data source, in created_time ascending order. + rows []windowTestRow + // queryLimit is how many rows one query returns before the vendor marks it + // incomplete; 0 means every query returns all matching rows. + queryLimit int + // pageSize is how many rows one page of a query holds; 0 means 100. + pageSize int + // markerFirstPageOnly models the vendor caveat that the incomplete marker can + // appear before the last page received for a capped query instead of on it. + markerFirstPageOnly bool + // alwaysIncomplete marks every query incomplete, even one that matched nothing. + alwaysIncomplete bool + // omitCompleteMarker answers a complete window without request_status at all. + omitCompleteMarker bool + + // searchResults is served from POST /v1/search when set. + searchResults []interface{} + // blocks is served from GET /v1/blocks/{id}/children when set. + blocks map[string][]interface{} +} + +type windowQueryServer struct { + *httptest.Server + + mu sync.Mutex + requests []map[string]interface{} + calls int32 +} + +func (s *windowQueryServer) queryCalls() int32 { + s.mu.Lock() + defer s.mu.Unlock() + return s.calls +} + +// queryRequests returns the decoded body of every data source query served so far. +func (s *windowQueryServer) queryRequests() []map[string]interface{} { + s.mu.Lock() + defer s.mu.Unlock() + return append([]map[string]interface{}(nil), s.requests...) +} + +func (s *windowQueryServer) serveQuery(w http.ResponseWriter, r *http.Request, fake windowQueryFake) { + raw, err := io.ReadAll(r.Body) + if err != nil { + http.Error(w, "read query request", http.StatusBadRequest) + return + } + var request map[string]interface{} + if err := json.Unmarshal(raw, &request); err != nil { + http.Error(w, "unmarshal query request", http.StatusBadRequest) + return + } + + s.mu.Lock() + s.calls++ + s.requests = append(s.requests, request) + s.mu.Unlock() + + response, errText := fake.answer(request) + if errText != "" { + http.Error(w, errText, http.StatusBadRequest) + return + } + _ = json.NewEncoder(w).Encode(response) +} + +// answer builds the response the vendor would send for one query request. The +// second result is a non-empty error text when the request cannot be served. +func (f windowQueryFake) answer(request map[string]interface{}) (map[string]interface{}, string) { + lower, errText := requestWindowStart(request) + if errText != "" { + return nil, errText + } + + // The filter is applied before the per-query limit is. + var matching []windowTestRow + for _, row := range f.rows { + if lower.IsZero() { + matching = append(matching, row) + continue + } + created, err := time.Parse(time.RFC3339, row.createdTime) + if err != nil { + return nil, "test row " + row.id + " has no parsable created_time" + } + if !created.Before(lower) { + matching = append(matching, row) + } + } + + // A capped query ends the window with has_more=false even though the data + // source holds more rows. + window := matching + capped := f.alwaysIncomplete + if f.queryLimit > 0 && len(window) > f.queryLimit { + window = window[:f.queryLimit] + capped = true + } + + offset, errText := requestCursorOffset(request) + if errText != "" { + return nil, errText + } + if offset > len(window) { + return nil, "start_cursor points past the end of the window" + } + size := f.pageSize + if requested, ok := request["page_size"].(float64); ok && int(requested) < size { + size = int(requested) + } + end := offset + size + if end > len(window) { + end = len(window) + } + page := window[offset:end] + + results := make([]interface{}, 0, len(page)) + for _, row := range page { + results = append(results, windowRecord(row)) + } + + hasMore := end < len(window) + response := map[string]interface{}{ + "object": "list", "results": results, "has_more": hasMore, "next_cursor": nil, + } + if hasMore { + response["next_cursor"] = strconv.Itoa(end) + } + switch { + case capped && (!f.markerFirstPageOnly || offset == 0): + response["request_status"] = truncationIncomplete() + case !capped && !f.omitCompleteMarker: + response["request_status"] = map[string]interface{}{"type": "complete"} + } + return response, "" +} + +func requestWindowStart(request map[string]interface{}) (time.Time, string) { + filter, _ := request["filter"].(map[string]interface{}) + if filter == nil { + return time.Time{}, "" + } + created, _ := filter["created_time"].(map[string]interface{}) + if created == nil { + return time.Time{}, "query filter is missing created_time" + } + raw, _ := created["on_or_after"].(string) + if raw == "" { + return time.Time{}, "query filter is missing created_time.on_or_after" + } + start, err := time.Parse(time.RFC3339, raw) + if err != nil { + return time.Time{}, "unparsable created_time.on_or_after: " + raw + } + return start, "" +} + +func requestCursorOffset(request map[string]interface{}) (int, string) { + raw, _ := request["start_cursor"].(string) + if raw == "" { + return 0, "" + } + offset, err := strconv.Atoi(raw) + if err != nil { + return 0, "unparsable start_cursor: " + raw + } + return offset, "" +} + +func windowRecord(row windowTestRow) map[string]interface{} { + record := truncationRecord(row.id) + if row.createdTime != "" { + record["created_time"] = row.createdTime + } + return record +} + +func windowDataSourceInfo() map[string]interface{} { + return map[string]interface{}{ + "id": "ds-1", "object": "data_source", + "title": []interface{}{map[string]interface{}{"plain_text": "Large Database"}}, + } +} + +func newWindowQueryServer(t *testing.T, fake windowQueryFake) *windowQueryServer { + t.Helper() + if fake.pageSize <= 0 { + fake.pageSize = 100 + } + server := &windowQueryServer{} + server.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.URL.Path == "/v1/search": + _ = json.NewEncoder(w).Encode(map[string]interface{}{ + "object": "list", "results": fake.searchResults, "has_more": false, "next_cursor": nil, + }) + case r.URL.Path == "/v1/data_sources/ds-1" && r.Method == http.MethodGet: + _ = json.NewEncoder(w).Encode(windowDataSourceInfo()) + case r.URL.Path == "/v1/data_sources/ds-1/query": + server.serveQuery(w, r, fake) + case strings.HasPrefix(r.URL.Path, "/v1/blocks/"): + id := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/v1/blocks/"), "/children") + _ = json.NewEncoder(w).Encode(map[string]interface{}{ + "object": "list", "results": fake.blocks[id], "has_more": false, "next_cursor": nil, + }) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(server.Close) + return server +} + +// --- Assertions on recorded requests --- + +func recordIDs(records []notionPage) []string { + ids := make([]string, 0, len(records)) + for _, record := range records { + ids = append(ids, record.ID) + } + return ids +} + +// assertCreatedTimeSort pins the recipe's first step: every query sorts by +// created_time ascending, which is what gives each window a stable order. +func assertCreatedTimeSort(t *testing.T, request map[string]interface{}) { + t.Helper() + require.Equal(t, []interface{}{ + map[string]interface{}{"timestamp": "created_time", "direction": "ascending"}, + }, request["sorts"], "every query must sort by created_time ascending") +} + +// windowFilterStart returns filter.created_time.on_or_after from a recorded +// request, or "" when the request carries no window filter (the first window). +func windowFilterStart(t *testing.T, request map[string]interface{}) string { + t.Helper() + filter, ok := request["filter"].(map[string]interface{}) + if !ok { + return "" + } + require.Equal(t, "created_time", filter["timestamp"], "the window filter must be a created_time filter") + created, ok := filter["created_time"].(map[string]interface{}) + require.True(t, ok, "the window filter must carry a created_time object") + start, ok := created["on_or_after"].(string) + require.True(t, ok, "the window filter must carry created_time.on_or_after") + return start +} + +// --- Log capture --- + +type syncBuffer struct { + mu sync.Mutex + buf strings.Builder +} + +func (b *syncBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *syncBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +// captureNotionLogs redirects the logger into a buffer for the duration of the +// test so warnings about capped queries can be asserted on. +func captureNotionLogs(t *testing.T) *syncBuffer { + t.Helper() + buffer := &syncBuffer{} + logger.SetOutput(buffer) + t.Cleanup(func() { logger.SetOutput(os.Stdout) }) + return buffer +} + +// --- Tests --- + +func TestQueryDatabaseAllReadsPastTheLimitInCreatedTimeWindows(t *testing.T) { + logs := captureNotionLogs(t) + server := newWindowQueryServer(t, windowQueryFake{ + rows: createdTimeRows("r1", "r2", "r3", "r4", "r5"), + queryLimit: 2, + pageSize: 2, + }) + client := mustTestClient(t, "test-token", server.URL) + + records, err := client.QueryDatabaseAll(context.Background(), "ds-1") + require.NoError(t, err, "a data source larger than one query must still be read in full") + require.Equal(t, []string{"r1", "r2", "r3", "r4", "r5"}, recordIDs(records), + "boundary rows are returned by two windows and must be kept once, in created_time order") + require.Equal(t, int32(4), server.queryCalls(), "every capped window must start a new query") + + requests := server.queryRequests() + require.Len(t, requests, 4) + for _, request := range requests { + assertCreatedTimeSort(t, request) + } + require.Empty(t, windowFilterStart(t, requests[0]), "the first window is read without a filter") + for i, want := range []string{"2026-01-01T10:01:00Z", "2026-01-01T10:02:00Z", "2026-01-01T10:03:00Z"} { + require.Equal(t, want, windowFilterStart(t, requests[i+1]), + "window %d must continue from the last row of the previous window", i+2) + } + require.Contains(t, logs.String(), "hit the vendor per-query result limit", + "continuing past the limit must stay visible in the logs") +} + +func TestQueryDatabaseAllDeduplicatesRowsByID(t *testing.T) { + server := newWindowQueryServer(t, windowQueryFake{ + rows: []windowTestRow{ + {id: "r1", createdTime: "2026-01-01T10:00:00Z"}, + {id: "r1", createdTime: "2026-01-01T10:00:00Z"}, + {id: "r2", createdTime: "2026-01-01T10:01:00Z"}, + }, + }) + client := mustTestClient(t, "test-token", server.URL) + + records, err := client.QueryDatabaseAll(context.Background(), "ds-1") + require.NoError(t, err) + require.Equal(t, []string{"r1", "r2"}, recordIDs(records), "a row returned twice must be kept once") + require.Equal(t, int32(1), server.queryCalls()) +} + +func TestQueryDatabaseAllIncompleteMarkerBeforeLastPageStartsNextWindow(t *testing.T) { + server := newWindowQueryServer(t, windowQueryFake{ + rows: createdTimeRows("r1", "r2", "r3", "r4"), + queryLimit: 2, + pageSize: 1, + markerFirstPageOnly: true, + }) + client := mustTestClient(t, "test-token", server.URL) + + records, err := client.QueryDatabaseAll(context.Background(), "ds-1") + require.NoError(t, err) + require.Equal(t, []string{"r1", "r2", "r3", "r4"}, recordIDs(records)) + require.Equal(t, int32(6), server.queryCalls(), + "a marker seen on a non-final page makes the whole window incomplete, so the walk must continue") +} + +func TestQueryDatabaseAllCompleteWindowUnchanged(t *testing.T) { + cases := map[string]windowQueryFake{ + "request_status complete": {rows: createdTimeRows("r1", "r2", "r3")}, + "no request_status": {rows: createdTimeRows("r1", "r2", "r3"), omitCompleteMarker: true}, + } + for name, fake := range cases { + t.Run(name, func(t *testing.T) { + server := newWindowQueryServer(t, fake) + client := mustTestClient(t, "test-token", server.URL) + + records, err := client.QueryDatabaseAll(context.Background(), "ds-1") + require.NoError(t, err, "a result set that fits in one query must not start a second window") + require.Equal(t, []string{"r1", "r2", "r3"}, recordIDs(records)) + require.Equal(t, int32(1), server.queryCalls()) + + requests := server.queryRequests() + require.Len(t, requests, 1) + require.Empty(t, windowFilterStart(t, requests[0]), "the first window is read without a filter") + assertCreatedTimeSort(t, requests[0]) + }) + } +} diff --git a/internal/datasource/connector/notion/types.go b/internal/datasource/connector/notion/types.go index 8280fed8..61212aab 100644 --- a/internal/datasource/connector/notion/types.go +++ b/internal/datasource/connector/notion/types.go @@ -68,6 +68,11 @@ type notionPage struct { // Only present on data_source objects (API 2025-09-03+). For example, if a database // is inside a page, this will be {type: "page_id", page_id: "..."}. DatabaseParent *notionParent `json:"database_parent,omitempty"` + + // CreatedTime is the vendor's immutable creation timestamp for a row + // (created_time). Data source queries sort and window by it, so unlike + // LastEditedTime it never moves when the row is edited. + CreatedTime time.Time `json:"created_time"` } // Parent type constants for notionParent.Type @@ -263,10 +268,29 @@ type attachment struct { // --- Pagination --- +// notionRequestStatus is the vendor's completeness marker on a paginated response. +// Notion sets Type to "incomplete" when it capped the returned set for a vendor-side +// reason — for example IncompleteReason "query_result_limit_reached" once a data +// source query reaches the 10,000-row per-query limit — and still reports +// has_more=false, so a capped page is otherwise indistinguishable from the last one. +// See https://developers.notion.com/guides/data-apis/query-large-data-sources +type notionRequestStatus struct { + Type string `json:"type"` // "complete" | "incomplete" + IncompleteReason string `json:"incomplete_reason"` // set when Type is "incomplete" +} + // paginatedResponse is the common response wrapper for paginated Notion API responses. type paginatedResponse struct { - Object string `json:"object"` // "list" - Results json.RawMessage `json:"results"` - HasMore bool `json:"has_more"` - NextCursor string `json:"next_cursor,omitempty"` + Object string `json:"object"` // "list" + Results json.RawMessage `json:"results"` + HasMore bool `json:"has_more"` + NextCursor string `json:"next_cursor,omitempty"` + RequestStatus *notionRequestStatus `json:"request_status,omitempty"` +} + +// isIncomplete reports whether the vendor marked this page as cut short. +// It must be checked on every page, not only the last one: the marker can show up +// before pagination stops. +func (r *paginatedResponse) isIncomplete() bool { + return r.RequestStatus != nil && r.RequestStatus.Type == "incomplete" }