The submit POST carries the whole document in a single multipart body, so
its hardcoded 60s client ceiling failed every scan larger than ~100MB on
the reporter's uplink (#5589 estimates ~1.8MB/s, so 60s ≈ 108MB) — and
the env knobs users reached for (WEKNORA_PADDLEOCR_VL_CLOUD_TIMEOUT,
WEKNORA_DOCREADER_CALL_TIMEOUT) never applied to this stage. Give the
submit client the per-job timeout the polling side already uses, so
WEKNORA_PADDLEOCR_VL_CLOUD_TIMEOUT now bounds the upload and the poll
together (default stays 600s, still capped by WEKNORA_DOCREADER_CALL_TIMEOUT).
Red/green: TestPaddleOCRVLCloudSubmitStopsAtConfiguredTimeout fails
against the hardcoded 60s client (stub responds after the configured
200ms budget; error is expected but got nil) and passes with the fix; a
paired success-path test pins the normal flow.
Out of scope (unchanged): the 30s per-poll request client, the 120s
result-JSONL download and the 60s per-image download in the same file.
Signed-off-by: 李凝炜 <951448078@qq.com>
Record each project's selected paths in the GitLab sync cursor so incremental
syncs (both FetchIncremental and FetchStream) detect directory-selection
expansions instead of skipping untouched existing files in newly added roots.
- When a project's commit is unchanged, walk and import only newly uncovered
roots (keeping unchanged selections incremental).
- When a project's commit also moved (previous != head), emit diff changes
and deletions from compareChanges while skipping new/modified paths already
covered by the newly added roots, then walk the added roots so existing
files are imported once without duplicates and deletions are preserved.
- Reuse gitLabCursor in FetchIncremental and wrap lines to satisfy lll (120).
- Add regression tests covering simultaneous commit advance + scope expansion
and widening to whole-repository selection across incremental and stream modes.
Co-authored-by: NianJiu <180004567+NianJiuZst@users.noreply.github.com>
Evaluate WEKNORA_BOOTSTRAP_SYSTEM_ADMIN_EMAIL during userService.Register so a
matching email is promoted to system admin immediately at sign-up when no
system administrator exists yet, eliminating the restart required on fresh
deployments while retaining cmd/server startup promotion for pre-existing users.
- Share BootstrapSystemAdminEmailEnv between service and cmd/server/bootstrap.go.
- Log promotion only after CreateUser and EnsureOwner succeed (sanitizing the
email), warn and fail closed if ListSystemAdmins fails, and keep all lines
within the 120-character lll lint limit.
- Replace the broken TenantProvisioningNone test stub with real SQLite-backed
registration tests covering case-insensitive matching, non-matching emails,
existing-admin guard, and fail-closed error handling.
- Update bootstrap comments and website-docs to reflect immediate sign-up
promotion alongside startup fallback.
Co-authored-by: NianJiu <180004567+NianJiuZst@users.noreply.github.com>
Follow-up fixes for Tencent/WeKnora#5724:
1. Quiet incremental rounds with lingering isolated failures:
- Previously, after a partial sync synced healthy items into the cursor while
leaving one persistently failing item unadvanced for retry, the very next
quiet incremental round skipped all unchanged items via the cursor fast-path
and emitted only the 1 failing item (Total=1, Failed=1). That tripped
allFetchedItemsFailedError, flipping ds.Status to error, burning 5 Asynq
retries, and permanently disabling future cron ticks.
- Add optional datasource.UnchangedItemRecorder / RecordUnchangedItem on
StreamHandler so per-item-cursor streaming connectors (Feishu Wiki/Drive,
Seafile, Nextcloud, Confluence) report cursor-verified unchanged items.
When unchangedItems > 0 and the stream completed without aborting,
processSyncStreaming records partial/active instead of failing the source.
Global errors (quota/cancel), circuit-breaker trips, RetryOnFailure, and
total-failure rounds (unchangedItems == 0) still fail and set error.
2. Scheduler recovery after error -> active transition:
- Editing scope while ds.Status == error caused UpdateDataSource to remove
the live cron entry, and a subsequent recovering manual sync restored
ds.Status = active in DB without re-registering the cron job.
- Re-read the persisted row (preserving any concurrent pause) and call
s.scheduler.AddOrUpdate(fresh) when updateSyncRunResult transitions a
source from error back to active.
3. Consistent folder-qualified labels on Feishu fetch failures:
- Populate FileName from the resolved directory path on Feishu Drive/Wiki
fetch-stage error items so fetch failures include folder paths in
SyncItemError.Title just like ingest failures.
4. Tests & docs:
- Add end-to-end tests for quiet rounds (Feishu Drive, Seafile), live
Scheduler error->active cron restoration on SQLite, Feishu fetch-failure
folder paths, Feishu multi-item docx attachment ingest failure with
SubtreeKeep preservation on SQLite, and Confluence/Nextcloud FetchFullStream
isolation + deletion reconciliation.
- Update website-docs/03-features/10-datasource.md sync status rules.
Root cause (Tencent/WeKnora#5724):
1. In streaming sync, any unexpected item ingest error returned from
streamSyncHandler.Emit immediately latched h.ingestErr and aborted the
entire stream. Even for connectors whose cursor tracks each item
independently (Feishu Wiki/Drive, Seafile, Nextcloud, Confluence), a
single failing item at the head of a folder prevented all remaining files
and any newly added folders/resources from ever being processed.
2. Several permanent per-item validation rejections during ingestion
(illegal filename/folder characters via ErrValidation, ErrInvalidURL,
malformed JSON replacement via ValidateJSONUploadContent, and unsupported
file_url extensions) fell through into the generic blocking ingest_failed
path instead of non-blocking rejections.
3. Streaming ingest aborts prefixed ErrorMessage with "Fetch failed:" even
when fetching succeeded and ingestion failed, failed item labels dropped
folder paths for bare-title connectors like Feishu, and ingest error
codes lacked localized frontend syncError strings.
Changes & boundaries:
- Add datasource.ErrItemIngestFailed and optional ItemFailureIsolatingConnector
interface implemented by per-item-cursor streaming connectors (Feishu
Wiki/Drive, Seafile, Nextcloud, Confluence). Linear/commit-level connectors
(such as GitLab) keep abort-on-error semantics to avoid skipping items.
- In streamSyncHandler.Emit, isolate individual unexpected ingest failures
for isolating connectors while keeping global errors (context cancellation,
StorageQuotaExceededError) immediately fatal and capping consecutive
isolated failures (10, reset on successful create/update) to abort early
during systemic storage/DB outages.
- Update Feishu, Seafile, Nextcloud, and Confluence streaming loops to leave
isolated failed items unadvanced in their cursor (preserving prior entries
and deletion identities for retry) while continuing to remaining items and
resources.
- Classify permanent item-level ingest rejections (invalid_item_name,
invalid_url, invalid_json_content, unsupported file_url) as non-blocking,
and surface storage_quota_exceeded without leaking private diagnostics.
- Fix streaming ingest abort ErrorMessage to omit the misleading
"Fetch failed:" prefix, include folder paths in SyncItemError.Title when
available, and localize all ingest syncError codes across all 6 locales.
Why:
- `LoadFromExcel` unconditionally executed `read_xlsx(..., header=true, all_varchar=true)` starting at row 1. For workbooks with a leading cross-column merged title banner, subtitle/metadata notes, or blank rows above the real header, DuckDB locked onto row 1 (even with `header=false`), collapsing the entire sheet to 1 column (`[2026 年度销售统计]`) and propagating the broken schema into `DataTableSummaryService` (`table_summary`/`table_column` chunks), `data_schema`, and SQL execution (#5627).
- `DataAnalysisTool.Execute` returned query rows without checking whether grand-total rows reconciled with detail sums or whether unfiltered partition share columns summed to ~1 / ~100%.
- When `PluginDataAnalysis` failed to load or execute SQL in the chat pipeline, it logged a warning and continued silently without informing the answer prompt, and the `data_analyst` system prompt did not explicitly forbid falling back to manual LLM arithmetic over raw table excerpts on failure.
What:
- Add streaming OOXML header detection (`internal/agent/tools/excel_header.go`, sharing workbook relationship resolution with `excel_sheets.go`) that samples leading non-empty rows, resolves only needed shared strings, inspects `<mergeCells>` and contiguous column bounds only when row 1 is narrower than subsequent rows (O(1) fast path for normal workbooks), and guards against pathological wide columns (e.g. stray `XFD` cells) that would OOM DuckDB.
- Update `LoadFromExcel` and `buildExcelCreateTableSQLWithRanges` to pass per-sheet `range = '<startCol><headerRow>:<endCol>'` with `stop_at_empty=true` (preventing DuckDB from materializing 1M trailing NULL rows when `range` is explicit) only for sheets with preamble rows, keeping legacy SQL byte-for-byte identical for normal sheets, CSVs, and multi-sheet `UNION ALL BY NAME` workbooks. Because `DataTableSummaryService` reuses `LoadFromKnowledge`, ingestion schema chunks and `data_schema` automatically receive the true columns.
- Add advisory SQL result consistency checks (`internal/agent/tools/data_analysis_consistency.go`) to warn when a single grand-total row disagrees with the sum of additive detail rows or when an unfiltered, non-limited partition share column fails to sum to ~1 / ~100%, skipping filtered/limited subsets and non-share rates/weights to avoid false alarms.
- Record `PipelineState.DataAnalysisFailure` in `PluginDataAnalysis.OnEvent` on load/SQL failure and append a sanitized `[Data Analysis Notice: ...]` in `prepareMessagesWithModelContext` (without polluting `MergeResult` citations or leaking UUIDs), and harden the `data_analyst` prompt template to require SQL computation for statistics and explicit failure reporting instead of manual arithmetic.
- Add end-to-end tests against real DuckDB covering merged banners, unmerged notes, multi-row/corner metadata preambles, offset tables, pivot headers, footer exclusion, mixed multi-sheet workbooks, renamed `.xls`, `DataTableSummaryService.Handle`, `PluginDataAnalysis` -> `prepareMessagesWithModelContext`, and consistency warnings.
Why:
- CI `golangci-lint` failed with 4 `lll` (>120 chars) violations in
`internal/handler/system.go`, `internal/agent/operations/system_admin_test.go`,
and `internal/handler/system_user_list_test.go`.
- In `UserManagement.vue`, mutating `appliedQuery` before `listAllUsers()`
resolved left stale pagination buttons enabled and made `refreshUsers()`
retry from the previous page offset instead of `0` whenever a search request
failed from page 2+.
- If a row action or `ResetPasswordDialog` opened during the 250ms search
debounce window, the blocked search was silently dropped and
`hasPendingSearch` stayed `true` permanently after the dialog closed.
- Clearing `search` while the Users tab was inactive could trigger a background
request because the empty-string branch skipped the `props.active` guard.
What:
- Wrap the 4 long Go lines within 120 characters and regenerate
`docs/swagger.json` and `docs/swagger.yaml` so `TestSwaggerDocsSync` stays
exact.
- Extend `TestListUsers_SearchAcrossPagesDisabledWildcardsAndDeleted` to also
pin deterministic `id ASC` tie-breaking across page boundaries and literal
`\` escaping alongside `%` and `_`.
- Commit `appliedQuery` in `UserManagement.vue` only on successful response,
track `inFlightQuery` to invalidate superseded in-flight searches during
typing without dropping trailing-space or Enter-submitted queries, guard the
empty-clear branch on `props.active`, and flush any deferred search once
modal/row locks release.
- Add component tests in `UserManagement.test.ts` covering failed-search retry
from page 2, in-flight invalidation during debounce, deferred flush after
closing `ResetPasswordDialog`, and inactive-tab clear isolation.
Why:
- `GET /api/v1/system/admin/users` only accepted `offset` and `limit`, and
`UserManagement.vue` filtered `users.value` (a single 20-row page) on the
client. Once a deployment exceeded 20 users, accounts created earlier on
page 2+ could not be found from the search box unless the administrator
manually paged to their slice first (#5634).
What:
- Add optional `q` query parameter to `GET /api/v1/system/admin/users`
(`SystemHandler.ListUsers` -> `UserService.ListAllUsers` ->
`UserRepository.ListUsers`) for case-insensitive substring matching on
`username` or `email`, escaping SQL `LIKE` wildcards (`%`, `_`, `\`) across
PostgreSQL (`ILIKE`) and SQLite (`LOWER(...) LIKE LOWER(...) ESCAPE '\'`).
- Keep both active and disabled (`is_active = false`) accounts searchable so
administrators can still locate disabled users to re-enable them, and break
`created_at DESC` ties with `id ASC` for deterministic pagination.
- Sync Swagger specs (`docs/swagger.json`, `docs/swagger.yaml`), the
`system_admin.list_users` `@x-agent` operation catalog metadata, and API /
feature docs in `website-docs/`.
- Switch `UserManagement.vue` and `listAllUsers()` to debounced server-side
search (`q`), resetting `offset` to `0` on query changes, clearing
immediately without debounce, discarding out-of-order stale responses via
request sequence tracking, clamping empty upper pages, and updating all 6
locale bundles to remove outdated "(current page)" copy.
- Replace fake service mocks in `system_user_list_test.go` with full-chain
router -> handler -> service -> SQLite repository tests, and add component
integration tests in `UserManagement.test.ts`.
Fixes#5634
Why:
- Under Lite / Desktop mode's in-process SyncTaskExecutor, enqueueMovedKnowledge dispatches ProcessDocument / ProcessManualUpdate immediately in a goroutine before acknowledgeMovedReparse commits phase="done".
- Two races resulted: (1) if the worker loaded the Knowledge row while _knowledge_transfer.phase was still "reparse_pending", its later full-row UpdateKnowledge saves rolled phase back to "reparse_pending", permanently rejecting any subsequent move of that document with "has an unfinished transfer"; (2) if the worker flipped parse_status before acknowledgeMovedReparse ran UpdateKnowledgeForTransfer, the single-shot CAS failed with "knowledge changed during transfer".
- In addition, internal/router/sync_task_transfer_test.go:316 exceeded the 120-character lll limit in golangci-lint, and tests/lite_smoke lacked KB copy and document move regression coverage.
What:
- Normalize in-memory _knowledge_transfer.phase from "reparse_pending" to "done" inside validateProcessingKnowledge for the target KB's worker, and retry the reload+CAS loop in acknowledgeMovedReparse across concurrent worker parse_status updates.
- Wrap the 137-char JSON string in internal/router/sync_task_transfer_test.go to satisfy golangci-lint (lll <= 120).
- Add TestMoveReparseConcurrentWorkerDoesNotPoisonTransferPhase and extend tests/lite_smoke/lite_e2e_test.go to cover KB copy and multi-document reuse_vectors -> reparse -> reuse_vectors moves without Redis.
Why:
1. Directly selecting a live shortcut inside a Feishu Drive sub-folder (rootFolder:shortcutToken) fell back to WalkDriveTree(rootFolderToken) after 1061002; because ExpandDriveShortcut replaced DriveFile.Token with ShortcutInfo.TargetToken and dropped the shortcut token, filterDriveFileByToken returned empty and falsely classified live nested shortcuts as deleted. DriveConnector.ResolveResourceAncestors also omitted the immediate parent folder (returning root:root instead of root:subFolder) and DataSourceEditorDialog.loadDriveRoot flushed [folderToken] in edit mode before save, overwriting saved sub-selections on cancel.
2. Wiki Connector.ResolveResourceAncestors added spaceID and intermediate ParentNodeIDs before verifying GetWikiNode, causing Step 2 ensureChildrenLoaded to fail with HTTP 400 and abort before syncUnavailableSelections when a selected node or its space was deleted/unshared.
3. DataSourceService.updateSyncRunResult only preserved prior DeletedItems on failed syncs when len(result.DeletedItems) == 0, dropping cached titles for later deleted resource_ids when a sync failed mid-stream, and DataSourceEditorDialog.isSelectionWithin omitted Confluence space covers (page:<spaceId>:<pageId>) and DingTalk workspace/folder covers.
What:
- Retain DriveFile.ShortcutToken in ExpandDriveShortcut, fill missing ParentToken during WalkDriveTree / ListResources, match ShortcutToken before target fallback in filterDriveFileByToken, fix buildDriveAncestorChain to return [root, ..., parentSubFolder] only for resolved selections, and skip premature edit-mode updateDataSource flushes in loadDriveRoot when folder_token is unchanged.
- Defer adding spaceID and parent chain in Wiki Connector.ResolveResourceAncestors until the full ancestor chain resolves cleanly via GetWikiNode.
- Merge unseen prior DeletedItems (up to maxSyncResultErrors) into ds.LastSyncResult whenever status == SyncLogStatusFailed, and cover Confluence (page:<spaceId>:*) and DingTalk (dingtalk:v1?...) in isSelectionWithin.
- Add connector, DataSourceService ProcessSync, and DataSourceEditorDialog tests covering nested Drive shortcuts, deleted-space ancestor resolution, mid-stream failure title retention, edit-mode Drive cancel safety, and Confluence/DingTalk selection covers.
Why:
1. Deleting a Feishu Wiki/Drive docx document that had parsed file attachments
(<nodeToken>#file#<attToken>) removed only the parent row in applyFetchedItem
because Feishu cursors track only parent tokens and IsDeleted items did not
carry ReplacesSubtree or run sweepStaleSubtree, leaving attachment sub-items
orphaned in the KB.
2. Directly selecting a Feishu Drive file (rather than a folder) and deleting it
upstream returns 1061002 ('params error') on the folder-list probe and an
empty root-walk match, which bypassed SelectedResourceDeletedError so
SyncDeletions=false and subsequent sync rounds dropped DeletedItems; meanwhile
deleting a Drive subfolder emitted a spurious extra IsDeleted item for the
folder token itself alongside its child files.
3. Deleting a parent Wiki node with child documents resolved the first child's
title for the parent's SourceResourceID, and an intermediate failed sync
overwrote ds.LastSyncResult with an empty DeletedItems list.
4. In DataSourceEditorDialog Step 2, checking a parent space kept superseded
unavailable child rows visually checked via isSelectionWithin while
uncheckResource could not clear them; Confluence Cloud spaces with
cloud_top_level_containers could misclassify unexpanded folder pages as
unavailable; and DataSourceSyncLogs computed deletedItemsCount from the
50-item sliced array instead of the full deleted_items list.
What:
- Set ReplacesSubtree=true on Feishu engine IsDeleted items, emit
deletedRes.Token only when no prior cursor tokens exist under resourceID, and
invoke sweepStaleSubtree in applyFetchedItem's IsDeleted path.
- Return SelectedResourceDeletedError in listDriveFilesForResource when a
non-folder token (1061002) is absent from a clean root walk, and wrap
ErrResourceNotFound on HTTP-200 error envelopes in ListWikiNodes /
GetDriveFolderMeta.
- Match ExternalID before unique SourceResourceID in resolveDeletedItemTitle and
knownDeletedTitles, and preserve prior DeletedItems on ds.LastSyncResult
across failed sync runs.
- Fix unavailable row check state / coverage in DataSourceEditorDialog, guard
Confluence Cloud folder-limited spaces and Drive root token switches, and use
the unsliced deleted_items length for deletedItemsCount in DataSourceSyncLogs.
- Add Go service+connector E2E tests and Vue component tests covering attachment
sweeps, Drive file/subfolder deletions, parent-subtree titles across failed
syncs, space-selection superseding, and Confluence Cloud folder limits.
Why:
1. When a user directly selects individual Feishu/Lark Wiki documents
(`spaceID:nodeToken`) or Drive sub-resources (`rootToken:fileToken`) in
`config.resource_ids` instead of the parent space/folder, and one selected
document is later deleted in Feishu (`GET /open-apis/wiki/v2/spaces/get_node`
returns HTTP 400 `code=131005: not found: node has been deleted`, or Drive
returns `code=1061003`), `wikiOps.List` / `driveOps.List` treated the 404 as
a fatal total listing failure and aborted `runSync` immediately. Every
selected document ordered after the deleted one never synced, and the whole
data source entered `error` status.
2. Neither the sync history drawer (`DataSourceSyncLogs.vue`) nor the Step 2
resource picker (`DataSourceEditorDialog.vue`) surfaced which source
documents had been deleted or allowed unchecking vanished `resource_ids`
still stored in `config.resource_ids`.
What:
- Unwrap `datasource.ErrResourceNotFound` from `feishuAPIError` (and HTTP 200
error envelopes) strictly for Feishu Wiki `131005` and Drive `1061003`, while
keeping permission/auth/RPC/5xx errors (`131006`, `1061004`, etc.) failing
without deleting KB data.
- Return `core.SelectedResourceDeletedError` from `wikiOps.List` and
`driveOps.List` when a directly selected sub-resource is deleted upstream, so
`runSync` emits `IsDeleted` items for all previously recorded cursor tokens
under that `resourceID`, prunes its cursor entry, checkpoints, and continues
syncing remaining `resourceIDs`.
- Record capped `DeletedItems []SyncDeletedItem` (`external_id`,
`source_resource_id`, `title`) in `SyncResult` across KB deletion, subsequent
idempotent syncs, and `sync_deletions=false` skips (retaining prior resolved
titles across rounds).
- Render `deleted_items` in `DataSourceSyncLogs.vue` and surface vanished saved
`resource_ids` at the top of `DataSourceEditorDialog.vue` Step 2 with a
localized unavailable badge (refreshing stale list snapshots on demand via
`getDataSource`) so users can inspect and uncheck them cleanly.
- Add i18n keys across all 6 locales (`zh-CN`, `zh-TW`, `en-US`, `ja-JP`,
`ko-KR`, `ru-RU`), update `website-docs/03-features/10-datasource.md`, and
add Go + Vue regression tests.
Fixes#5633
Why:
- In Lite / Desktop mode (`REDIS_ADDR` unset, `s.redisClient == nil`, async tasks run via in-memory `SyncTaskExecutor`), all 6 transfer progress methods in `internal/application/service/knowledge_clone_move.go` (`saveKBCloneProgress`, `SaveKBCloneProgress`, `GetKBCloneProgress`, `saveKnowledgeMoveProgress`, `SaveKnowledgeMoveProgress`, `GetKnowledgeMoveProgress`) unconditionally dereferenced `s.redisClient`.
- Calling `POST /api/v1/knowledge-bases/copy`, `POST /api/v1/knowledge/move`, or either progress polling endpoint triggered a nil-pointer panic (HTTP 500), and `ProcessKBClone` / `ProcessKnowledgeMove` panicked inside `SyncTaskExecutor` on their first progress write—tearing multi-document move batches after item 1 and failing all retries.
- In addition, `ProcessKBClone` and `ProcessKnowledgeMove` only read `asynq.GetRetryCount` / `asynq.GetMaxRetry` (`0, false` outside Asynq), ignoring `types.TaskRetryMetadataFromContext(ctx)` injected by `SyncTaskExecutor` and treating attempt 0 of a retryable task as final.
What:
- Add race-safe, value-copied in-memory fallbacks (`memKBCloneProgress`, `memKnowledgeMoveProgress`) with 24h TTL parity, lazy/admission expiry eviction (no per-tick timers), `SetNX` (`onlyIfAbsent`) admission semantics so HTTP admission never clobbers an already-started worker, and `NotFound` errors on missing/expired task IDs.
- Resolve retry counters via `taskRetryState(ctx)` (`types.TaskRetryMetadataFromContext` first, then `asynq.GetRetryCount`/`GetMaxRetry`, plus `asynq.SkipRetry` terminal checks) in `ProcessKBClone` and `ProcessKnowledgeMove`.
- Add end-to-end router + `SyncTaskExecutor` + SQLite (`redisClient == nil`) HTTP tests, service admission-race/expiry/retry-metadata tests, and update `website-docs/02-architecture/05-async-tasks.md`.
Why:
1. Running cleanupKnowledgeResources in ProcessDocument before processChunks bypassed processChunks's abort, source-replaced, attempt-superseded, embedding-model, and vector-store guards, allowing a superseded worker to wipe a newer attempt's indexed content and deleting content before model/store checks ran.
2. Running cleanupKnowledgeResources after bindStoredImages released and deleted content-deduplicated resource:// image handles still referenced by the reparsed chunks.
3. Subtracting StorageSize up front only mutated knowledge.StorageSize in memory, causing retryable BatchIndex failures to subtract quota repeatedly while reparses in >50%-full workspaces failed the quota check; gating cleanup on payload.Attempt > 0 && StorageSize > 0 also leaked images and quota when OpenAttempt fell back (Attempt == 0) or vector indexing was disabled (StorageSize == 0).
4. Flipping enable_status to disabled and overwriting embedding_model_id / description at submission dropped queued or failed-reparse documents out of Graph Search and Agent QA listings and orphaned vectors when KB embedding dimensions changed, while skipping synchronous cleanup in ReplaceKnowledgeFile left retired source chunks searchable under the replacement filename.
What:
- Move obsolete-image and previous-dimension vector cleanup into processChunks after all abort/supersede and model/store guards succeed, filtering out image URLs still referenced by the replacement chunks.
- Account for tenant storage via delta (totalStorageSize - previousStorageSize), discount previousStorageSize during quota checks, and release previousStorageSize only if chunk/index swap fails terminally after deleting old rows.
- Preserve EnableStatus, EmbeddingModelID, StorageSize, Description, and ProcessedAt across in-place reparse submission (!tasksDequeued) while keeping synchronous cleanup for ReplaceKnowledgeFile (tasksDequeued).
- Replace internal helper mocks with SQLite + sqlite-vec + ResourceCatalog end-to-end tests covering batch reparse, DocReader failure, superseded attempt races, and file replacement.
Submitting a reparse deleted every document's chunks, index rows, images
and graph data up front, so the whole batch left retrieval until each
document's own processing task ran, and a document whose parse then failed
stayed empty for good. The swap now happens in ProcessDocument, once the
replacement has been parsed, through the same helper the manual update
worker already uses.