Skip to content

feat: migrate POST /api/v1/datasets/<dataset_id>/documents/stop to Go - #4

Closed
xugangqiang wants to merge 9 commits into
mainfrom
feat/go-stop-parse-documents
Closed

xugangqiang wants to merge 9 commits into
mainfrom
feat/go-stop-parse-documents

Conversation

@xugangqiang

Copy link
Copy Markdown
Owner

Summary

Migrate the stop parse documents endpoint from Python to Go.

Python endpoint

POST /api/v1/datasets/<dataset_id>/documents/stop — api/apps/restful_apis/document_api.py:1542-1641

Changes

File Change
internal/dao/task.go Add GetByDocID method
internal/dao/task_test.go 3 DAO tests (new file)
internal/service/document.go Add StopParseDocuments + refactor shared helpers
internal/service/document_test.go 8 service tests
internal/handler/document.go Add handler + request struct + interface
internal/handler/document_test.go 5 handler tests
internal/router/router.go Add POST /:dataset_id/documents/stop route

How it works

  1. Validates all document IDs belong to the dataset
  2. For each document in RUNNING/CANCEL state (or with unfinished tasks):
    • Sets Redis cancel signal {task_id}-cancel for each associated task
    • Updates document.run to CANCEL ("2")
  3. Returns {"success_count": N, "errors": [...]}

Test strategy

  • DAO/Service: SQLite in-memory DB, zero mocks. Redis is nil-safe by design.
  • Handler: fakeDocumentService implementing documentServiceIface interface.

🤖 Generated with Claude Code

xugangqiang and others added 9 commits June 3, 2026 21:17
Migrate the batch document deletion endpoint from Python to Go.
Two modes supported: explicit ids list, and delete_all.

Changes:
- dao/file2document: add GetByDocumentID, DeleteByDocumentID
- dao/kb: add DecrementCounters (already existed) with tests
- service/document: add deleteDocumentFull (per-doc cleanup) + DeleteDocuments (batch orchestration)
- handler/document: add DeleteDocuments handler with request validation
- router: register DELETE /:dataset_id/documents route
- cmd/server_main: support RAGFLOW_DICT_PATH env var for tokenizer dict path
- binding/rag_analyzer: use -lpcre2-8 dynamic linking (fixes host dev)
- dao/database: skip Error 1091/1138 during migration (coexist with Python schema)
- service/llm: fix non-constant format string vet warning

Per-document cleanup includes:
- Task deletion from DB
- Document hard-delete + KB counter decrement
- Chunk deletion from document engine (nil-guarded)
- Metadata deletion from document engine (nil-guarded)
- File2document mapping + file record + storage blob removal

Unit tests: 24 passing (7 DAO + 10 service + 7 handler)
Tested with SQLite :memory: + gin.TestMode, no external deps.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
A single file_id can be shared across multiple documents via
file2document rows with different document_id. Before deleting the
file record and its storage blob, check whether any other document
still references the same file_id. Only delete file/blob when no
other references remain.

Add TestDeleteDocumentFull_SharedFilePreserved to verify shared file
survives when one referencing document is deleted.
-lpcre2-8 linker flag finds either .a or .so automatically.
Update the build-time library checks to match.
- Add GetByDocID to TaskDAO for querying tasks by document ID
- Add StopParseDocuments to DocumentService with Redis cancel signal support
- Add StopParseDocuments handler with request validation and access check
- Add POST /:dataset_id/documents/stop route
- Add unit tests: 3 DAO + 8 service + 5 handler tests

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Extract five sub-methods from deleteDocumentFull:
- resolveDocAndKB      — load document + knowledgebase
- deleteDocTasks       — delete task rows
- deleteDocEngineData  — delete chunks + metadata from engine
- deleteDocRecordWithCounters — hard-delete doc + decrement KB
- cleanupFileReferences — delete f2d + file + blob (shared-safe)

deleteDocumentFull is now a thin orchestrator.
Add 10 targeted unit tests for the sub-methods.
validateDocsInDataset is shared between DeleteDocuments and
StopParseDocuments, removing duplicate validation logic.

cancelDocParse encapsulates per-document parse cancellation:
Redis cancel signal + run status update.

StopParseDocuments is now a thin orchestrator, same pattern as
deleteDocumentFull.
…hCounters

DocumentDAO.Delete now returns (int64, error). deleteDocRecordWithCounters
wraps the delete + counter decrement in a transaction and only decrements
KB counters when RowsAffected > 0, preventing permanent dataset stat skew
on retries or concurrent deletes.
…ferences

If DeleteByIDs returns an error the file row is still live; removing
the blob anyway would leave a dangling file record. Bail out to keep
the blob intact so the record remains usable on retry.
Single-line wrapper with no extra logic beyond the DAO call + log.
Task deletion is already covered by TestDeleteDocumentFull_Basic.
@xugangqiang xugangqiang closed this Jun 3, 2026
xugangqiang added a commit that referenced this pull request Jul 27, 2026
- token.go Update: guard overlapped_percent behind key presence so a partial config update preserves the previously configured value instead of resetting it to 0 (finding #3).

- schema clampOverlappedPercent: clamp to [0,90] BEFORE the float->int truncation so huge inputs (e.g. 1e300, math.MaxFloat64) normalize to 90, matching Python's normalize_overlapped_percent, instead of 0 (finding #4).

- Tests: add overflow cases to TestNormalizeOverlappedPercent and a new TestTokenChunkerParam_UpdatePreservesOverlappedPercent regression test.

Refs infiniflow#17396
xugangqiang added a commit that referenced this pull request Aug 14, 2026
Align three Go DLA / PDF post-processing behaviors with the Python
deepdoc reference so the Go pipeline converges on real documents.

1. DLA annotation tie-break (#4): when a text box overlaps multiple
   same-type regions with equal box-coverage, prefer the region with the
   higher region-coverage ratio. Mirrors Python's (ov, _ov) tuple
   comparison in LayoutRecognizer.__call__.

2. header/footer filtering (#5): match header|footer|number as a
   substring (regex (?i)header|footer|number) instead of the anchored
   ^(header|footer|number)$, so composite labels such as "page-footer"
   and page numbers are stripped, matching Python's filterPDFHeaderFooter.

3. per-class NMS (#6): apply greedy per-class non-maximum suppression
   (IoU 0.45, +1 overlap convention) to DLA regions before annotation,
   matching Python's layout post-process and removing duplicate
   same-type detections.

Tests:
- table/table_annotate_parity_test.go: new unit tests for #4 tie-break
  and #6 NMS (RED -> GREEN).
- parser/pdf_postprocess_test.go: substring header/footer match test (#5).
- table/table_annotate_test.go: adjust TestAnnotateBoxLayouts_SyntheticFigure
  expected coordinates for the corrected Y-sort order.
- tool/compare_test.go: fix missing `common` import so the golden
  comparator test compiles.

Validated with the golden comparison harness (TestBatchCompareWithPython)
against the Python reference on a real PDF: DLA region counts and text
content converge.
xugangqiang added a commit that referenced this pull request Aug 18, 2026
Python's construct_table (table_structure_recognizer.py:336-348) detects
header rows via three signals combined per row with a >0.5 majority:
geometric overlap (box overlaps a header region by >=0.3, the "H" flag),
blockType (numeric-dominant tables only), and no model-agnostic label
fallback. Go's HeaderSetWithBlockType diverged in three ways:

1. The production TSR path ignored the geometric 0.3 overlap signal
   entirely (only the box-fallback path used it).
2. The label fallback had no 0.5 majority vote, so a single mislabeled
   cell promoted a whole data row to a header.
3. The label fallback was gated by blockType, so once blockType found
   any header, label-only headers elsewhere were dropped.

Fix:
- HeaderSetWithBlockType now takes the annotated boxes and combines THREE
  ADDITIVE signals (geometric via BoxHeaderSet, blockType, and TSR label),
  each with a per-row >0.5 majority. The mutually-exclusive gate is removed.
- AnnotateTableBoxes now stores header overlap as idx+1 instead of idx, so
  a box matching the FIRST header cell (idx==0) is distinguishable from
  "no overlap" (default H==0). All readers use H>0, so this is a
  compatible, boolean-preserving change that also fixes single-column /
  first-column header detection in the box-fallback path.

Tests: table_header_parity_test.go adds four unit tests (geometric-vs-label
divergence, label over-detection, exclusive-gate drop, non-numeric
unlabeled header) that go red->green with this change. Full
build.sh --test ./internal/deepdoc/parser/pdf/ passes with no regression.
xugangqiang added a commit that referenced this pull request Oct 30, 2026
- prefer worker-claim time (doc.ProcessBeginAt) for wait duration (#2)
- omit zero-value times from the JSON log line instead of emitting
  0001-01-01, and guard the logger with atomic.Pointer for a safe swap (#8, #7)
- populate DurationMS from ParseDurationS so consumers need not recompute (#11)
- drop the unused IngestLog.Code field (#Nit)
- thread the failure reason through MarkFailed into the emitted event's
  ErrorInfo, so failed runs are no longer logged with an empty reason (#4)
- persist process_end_at idempotently (WHERE process_end_at IS NULL) so
  overlapping terminal events cannot rewrite the recorded completion
  instant (#12)

All changes covered by unit tests in internal/common, internal/observability
and internal/service.
xugangqiang added a commit that referenced this pull request Nov 2, 2026
- prefer worker-claim time (doc.ProcessBeginAt) for wait duration (#2)
- omit zero-value times from the JSON log line instead of emitting
  0001-01-01, and guard the logger with atomic.Pointer for a safe swap (#8, #7)
- populate DurationMS from ParseDurationS so consumers need not recompute (#11)
- drop the unused IngestLog.Code field (#Nit)
- thread the failure reason through MarkFailed into the emitted event's
  ErrorInfo, so failed runs are no longer logged with an empty reason (#4)
- persist process_end_at idempotently (WHERE process_end_at IS NULL) so
  overlapping terminal events cannot rewrite the recorded completion
  instant (#12)
- emit the running lifecycle event from PrepareValidatedRun AFTER the
  worker-claim time is stamped, so BeginTime and wait_duration_s reflect
  this run instead of a zero or previous-run value (#A)
- only emit user_name when set, so the always-empty key is not logged and
  the JSON field uses omitempty (#C)
- correct the ingestor.log sink docs: it always writes to stdout;
  ingestor.log.path only adds an optional rotated file on top (#B)
- drop the redundant SetIngestLog/SyncIngestLog calls from admin and
  syncer, which never emit ingestion events (#D)

All changes covered by unit tests in internal/common, internal/observability
and internal/service.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant