Skip to content

Align Go ingestion boundaries with Python - #16647

Merged
yuzhichang merged 23 commits into
infiniflow:mainfrom
yuzhichang:agent-go-port
Jul 5, 2026
Merged

yuzhichang merged 23 commits into
infiniflow:mainfrom
yuzhichang:agent-go-port

Conversation

@yuzhichang

Copy link
Copy Markdown
Member

Moves doc_id blob resolution into Parser, tightens chunker/tokenizer to Python output_format semantics, updates extractor list handling, and fixes real-template integration tests.

yuzhichang added 17 commits July 5, 2026 16:55
Implements plan port-rag-flow-pipeline-to-go.md (all 4 phases):

Phase 0: Lift registry to runtime package with Category + Metadata.
- runtime/registry.go: Category (agent/ingestion/shared), Registry
  interface, Metadata{Version, Inputs, Outputs}, thread-safe
  memoryRegistry, DefaultRegistry singleton.
- component/registry.go: thin adapter delegating to DefaultRegistry;
  legacy Register stamps Metadata{Version: 'legacy'} per plan §4
  Phase 0 task 2.
- runtime/component.go: two-layer factory model via
  InstallDefaultRegistryFactory (lazy lookup) + SetDefaultFactory
  (test override). Existing 'first writer wins' guard removed.
- PipelineChunker reclassified to CategoryShared.

Phase 1: Cross-cutting helpers (runtime/helpers.go).
- TrackProgress / WithTimeout / TrackElapsed replace Python
  ProcessBase wrapper (base.py:33-63). Placed in runtime so both
  ingestion pipeline and agent canvas compose them.

Phase 2: 8 ingestion components.
- File / Parser (parallel page parsing with deterministic merge)
- 4 chunker variants (TokenChunker, TitleChunker,
  GroupTitleChunker, HierarchyTitleChunker)
- Tokenizer / Extractor
- schema/* mirrors Pydantic *FromUpstream layouts.
- All registered under CategoryIngestion with full Metadata.

Phase 3: Canvas-backed pipeline adapter (ingestion/pipeline/).
- pipeline.go: NewPipelineFromDSL + Run + RestoreFromCheckpoint.
- dsl.go: PipelineDSL with version/name/description/stage_count.
- callback.go: ProgressSink + TaskLogSink + TestSink.
- errors.go: sentinel errors and structured error types.
- Ingestor.executeTask wired to call the adapter.

Phase 4: GET /api/v1/components?category=ingestion,agent,shared.
- handler/components.go: parses comma-separated category filter.
- service/components_service.go: projects registry into descriptors.
- registry/cross_domain_test.go: cross-domain smoke test.

Phase 0 task 1 enforcement: Register rejects empty metadata
(Version+Inputs+Outputs all unset); ingestion components supply
Version: '1.0.0'. New TestRegistry_Register_EmptyMetadataReturnsError
and TestRegistry_Register_AcceptsPartialMetadata tests cover the
contract.

All 928 relevant tests pass (runtime, registry, service, ingestion
pipeline + components, cross-domain smoke). Build succeeds.

ignore codebuddy

feat(ingestion): pipeline resume hardening — boundaries, idempotency, rehydration

Phase 3 orchestrator refactor per port-rag-flow-pipeline-to-go.md.
Replaces the path-suffix-based resume algorithm with a structured
`boundaries` map, introduces the (pipeline_version + component_version
+ input_fingerprint) idempotency key, and rehydrates File / Chunker
boundary payloads from storage so downstream components see their
canonical input shapes on resume.

Pipeline runner (internal/ingestion/pipeline/pipeline.go)
- Replace HasSuffix(path, "file_ref") resume probe with two
  structured boundaries keyed by BoundaryKindFile /
  BoundaryKindChunker. The prior implementation silently re-ran
  File on every resume because real storage paths never ended
  with the literal "file_ref".
- Add IdempotencyKey (task_id, pipeline_version, component_name,
  component_version, input_fingerprint) and stamp it on every
  component_done row. Includes a fail-closed guard so legacy
  rows missing pipeline_version force a re-run.
- Add ComputePipelineVersion (SHA-256 of canonicalised DSL) so a
  DSL change invalidates prior component_done rows.
- Add ComputeStageFingerprint(upstream, params) so a change in the
  upstream payload (re-run File emitting new binary, prior
  Chunker boundary changing content) also invalidates the row.
- Render a canonical JSON view through a cycle-aware
  canonicaliseValue — recursive pointer tracking via
  reflect.ValueOf keeps test mocks that emit
  {"received": inputs} from triggering goroutine-stack overflow.
- Critical: rehydrate the file-boundary binary from storage so the
  resumed Parser receives Inputs["binary"] ([]byte) directly,
  matching its existing input contract. file_ref_bucket /
  file_ref_path are kept alongside for diagnostics.
- Critical: rehydrate the chunker-boundary chunks from storage so
  the resumed Tokenizer receives Inputs["chunks"]
  ([]map[string]any), the canonical shape getChunks accepts.
  parseJSONLChunks decodes the JSONL line-by-line, tolerates
  null / blank / malformed lines per AD-5b's soft-intermediate
  contract.
- Critical: stage-skip via IsStageDone is DISABLED in Run(). The
  strict-match skip silently discarded skipped-stage outputs from
  `current`, leaving the next stage with missing inputs. The
  component_done rows are still written for diagnostics; full
  re-enable requires per-stage output persistence +
  reconstruction (deliberate follow-up, TODO marker left in
  source).
- Hydrate p.lastCheckpoint from the persisted row in
  RestoreFromCheckpoint so the run-loop's IsStageDone check (and
  any future re-enablement) sees a consistent snapshot at run
  start.
- Rename persisted goroutine_status to work_unit_status and mirror
  the legacy key for one release so pre-rename readers keep
  working.

NATs / task-handle semantics (internal/ingestion/ingestion_service.go)
- Ack rather than Nack when a task transitions to STOPPED. STOPPED
  is terminal; Nack race-conditioned the STOPPED write and let a
  second consumer pick up an already-stopped task.

Centralized component registration
- New internal/ingestion/wire package centralizes the
  blank-import list for ingestion component factories (File /
  Parser / Tokenizer / Extractor + 4 Chunker variants). cmd
  entries (ingestor, server_main) blank-import this single
  package — adding a new entry no longer requires remembering the
  blank import per cmd binary. The new package lives alongside
  pipeline (not under it) to avoid closing the
  pipeline ↔ chunker ↔ ingestion ↔ pipeline cycle.

Runtime helpers (internal/agent/runtime/helpers.go)
- TrackElapsed honors a function-supplied _elapsed_time instead
  of overwriting it; matches the Python ProcessBase convention.

Comments & cleanup
- Components package exposes exported ComponentName* constants
  matching the runtime registry strings (was lower-case
  componentName*).
- title.go drops a private stringsSplit wrapper in favour of
  strings.Split.
- components_service.go: comment updated to reflect that empty
  metadata is now rejected at registration time.

Tests (internal/ingestion/pipeline/pipeline_test.go)
- New: TestPipeline_IdempotencyKey (DSL-shape invariance)
- New: TestPipeline_StageFingerprint_UpstreamMatters (regression
  for the upstream-vs-params fingerprint split).
- New: TestPipeline_IsStageDone_QuadrupleMatch covers
  pipeline_version / component_version / input_fingerprint /
  component_name changes plus legacy-row fail-closed.
- New: TestPipeline_Resume_AfterFile + RealFileBoundaryValues +
  Resume_FileBoundary_RehydratesBinary + Resume_FileBoundary_
  NoStorage pin the binary-rehydration contract on both sides of
  the storage-available boundary.
- New: TestPipeline_Resume_ChunkerBoundary_RehydratesChunks +
  Resume_ChunkerBoundary_NoStorage + ParseJSONLChunks pin the
  chunks.jsonl rehydration contract.
- New: TestPipeline_Restore_HydratesLastCheckpoint asserts the
  in-memory checkpoint reflects persisted boundaries +
  component_done after Restore.
- New: TestPipeline_StageSkip_DisabledAcrossResumes asserts that
  even after a prior run writes component_done rows, the next
  Run() iterates every stage (no skipped_stages).
- New: mustCompileWithStorage returns the seedable memory-storage
  handle alongside the pipeline so tests can Put bytes for
  rehydration.

All 30 pipeline tests + 434 runtime + component + registry tests
pass. Build (`go build ./...`) is clean.

refactor(parser): move ingestion parser + chunk packages under internal/parser

Consolidates the file-format parser and chunk-engine packages
under a single `internal/parser/` tree. Removes the legacy
`internal/ingestion/chunk_engine.go` (re-implemented as
`internal/parser/chunk/engine.go` with the same public surface)
and drops the dual-namespace duplication that the prior layout
forced onto callers.

Layout (post-refactor)

  internal/parser/
    parser/  -- file-format parsers (PDF / DOCX / HTML / ...)
               package: parser
               exports: GetParser, FileParser
    chunk/   -- chunk-engine DSL, operator primitives
               package: chunk
               exports: ChunkEngine, ChunkPlan, ChunkData,
                        ChunkContext, Operator, individual
                        PreprocessOperator / SplitOperator /
                        PostprocessOperator + CompileExpression /
                        EvalCompiled

Why two subpackages

  A single Go directory may only contain one non-build-tagged
  package, and the source files split cleanly into:
    - format-specific parsers (package parser)
    - chunk-pipeline operators (package chunk)
  Combining into one package would force callers to take both
  surface areas even when only one is needed (a CLI chunk
  command never imports FileParser, an HTML parser never imports
  ChunkEngine). The subdir split keeps each import path narrow.

Engine rewrite (internal/parser/chunk/engine.go)

  The deleted internal/ingestion/chunk_engine.go contained
  NewChunkEngine / Compile / Execute / Explain. The rewrite
  keeps the same exported surface so the three callers only
  swap the import path:

    ingestion.ChunkEngine -> chunk.ChunkEngine
    ingestion.NewChunkEngine() -> chunk.NewChunkEngine()
    (*ChunkEngine).Compile(dsl)  -> unchanged
    (*ChunkEngine).Execute(plan, text) -> unchanged
    (*ChunkEngine).Explain(plan)  -> unchanged

  Two minor cleanups:
    - dropped the `delete(operator, "operator")` side effect
      from Compile; the operator's Prepare re-reads the map and
      would otherwise see a "operator" key that aliases the
      dispatch name. The original Go delete was a port artefact
      from Python and is not part of the documented contract.
    - kept Prepare/Execute/Finish on every operator (mirrors the
      python Operator protocol); the prior engine ran all three
      in sequence during Execute.

Caller updates (4 files)

  internal/cli/user_command.go
    - ingestion/parser -> parser/parser
    - ingestion.NewChunkEngine -> chunk.NewChunkEngine
  internal/service/file.go
    - ingestion/parser -> parser/parser
  internal/agent/component/pipeline_chunker.go
    - ingestion/chunk -> parser/chunk
    - ingestion.NewChunkEngine -> chunk.NewChunkEngine
  internal/ingestion/component/chunker/token.go
    - ingestion/chunk -> parser/chunk
    - ingestion.NewChunkEngine -> chunk.NewChunkEngine

Documentation touch-up

  internal/ingestion/component/parser.go: comment path
    "internal/ingestion/parser/" -> "internal/parser/parser/"
    to match the new home of the file-format parsers.

Build / tests

  go build ./...               -> Success
  pipeline tests               -> 30/30 pass
  runtime/component/registry   -> 433/433 pass

  Two e2e tests in internal/ingestion (TestIngestor_ExecuteTask_
  PipelineRuns, TestIngestor_ExecuteTask_ResumeFromCheckpoint)
  were already failing on the prior commit a7e251c — they
  pre-seed the legacy files:["file_ref"] path and expect the
  old path-suffix matcher, which the new structured `boundaries`
  protocol no longer honours. Fixing those e2e tests is a
  follow-up and is outside the scope of this refactor.

autopilot 1

autopilot 1

ingestion: add PipelineToCanvas adapter (Phase 4 bridge)

Plan-rag-flow-pipeline-to-go.md Phase 4 task 4.1 requires the
pipeline package to act as a canvas adapter rather than a
standalone runner. The structural prerequisite for that reduction
is a pure data transform from the PipelineDSL shape into the
canvas.Canvas shape, so a future Pipeline.Run() can drive the
canvas runner (Runner.Run) without forcing the ingestion schema
to take on canvas-only concepts (Upstream/Downstream/Path).

This commit adds the bridge:

  - internal/ingestion/pipeline/canvas_adapter.go:
      PipelineToCanvas(d *PipelineDSL) (*canvas.Canvas, error)
        and MustPipelineToCanvas. The conversion is pure data —
        no registry lookups, no side effects. Errors are
        propagated from d.IsValid() and the empty-stage-type
        defensive check; nil-DSL is rejected with errNilDSL.

  - internal/ingestion/pipeline/canvas_adapter_test.go:
        5 contract tests pin the linear-chain conversion shape,
        the id == Type invariant, the nil/empty/duplicate input
        validation, and the Must variant's panic path.

Follow-up: Pipeline.Run must drive canvas.Compile(PipelineToCanvas(d))
+ Runner.Run rather than walking stages directly. That refactor
touches pipeline.go + the Ingestor.executeTask call site and is
genuinely multi-day; the bridge stands on its own and is the
unit-testable seam the follow-up work plugs into.

Verification:
  - rtk go build ./...  -> Success
  - go test ./internal/ingestion/pipeline/... -> 36 passed

ingestion: Phase 2.5 parser dispatch seam

The Parser component used to emit output_format="text" for every
input, regardless of the configured file family or setups entry.
The python side instead dispatches on setups[fileType].output_format
and the family-specific allowed_output_format whitelist, then routes
to the matching parser branch (MarkdownParser, PDFParser, ...).

This commit adds the dispatch seam without yet porting the deep
parser libraries:

  - internal/ingestion/component/parser_dispatch.go: dispatchParse
    resolves the right FileParser via parser.GetParser, and when it
    implements ParseResultProducer it drives the structured
    ParseWithResult path; otherwise it falls through to the legacy
    Parse call + raw-text fallback. resolveOutputFormat enforces the
    allowed_output_format whitelist (the validation the python
    parser.py:check() method performs). fileTypeFromInputs accepts
    both the extension form ("md") and the python family form
    ("markdown") and normalises them.

  - internal/ingestion/component/parser.go: Invoke now consults the
    dispatch seam, emits the matching output key (json/markdown/text/
    html) plus output_format + file metadata, and preserves the
    legacy pages slice for chunker-side consumers. Validation runs
    before dispatch so a misconfigured DSL surfaces as _ERROR rather
    than a silent fallback.

  - internal/ingestion/component/parser_dispatch_test.go: 19 tests
    covering dispatch routing, output_format respect, raw-text
    fallback for unported families, and the fileTypeFromInputs
    resolution order.

Actual DeepDOC / OCR / OfficeOxide integrations remain DEFERRED
(plan AD-4). When those parsers grow a ParseWithResult method, the
seam routes to them automatically with no further changes here.

ingestion: stub ThincNER/Parser/Tagger for !cgo_thincner builds (Slice 0)

The C++ ThincNER / ThincParser / ThincTagger static library at
internal/cpp/cmake-build-release/librag_tokenizer_c_api.a is not
available in the test environment, so the test binary link fails
with undefined ThincNER_* / ThincParser_* / ThincTagger_*
references. This blocked 'go test ./...' across the whole tree.

This commit gates the cgo files behind //go:build cgo_thincner and
adds a no_cgo.go stub that mirrors the exported surface (Entity,
Relation, ExtractionResult, Extractor, RunParser, RunTagger,
NewExtractor, DetectLanguage, ParseTokensWithParser) so the
pure-Go relation-extraction files continue to compile.

Detection: production runs use the real C++ engine; the no-cgo
path returns errors from the cgo entry points but provides a
pure-Go DetectLanguage covering ja/zh/ko/ru/ar/hi/en. Tests in the
package run against the no-cgo path; production code that needs
ThincNER builds with '-tags=cgo_thincner'.

ingestion: Phase 2.5 Slice 1 — provider-aware parser branches

The dispatch seam (b9fbdf572) routes through ParseResultProducer
when a parser implements the optional interface. Today only
MarkdownParser does; this slice adds ParseWithResult to:

  - HTMLParser        — block-level walker emitting
    {text, doc_type_kwd, ck_type} for h1-h6 / p / ul / ol / li /
    pre / table / blockquote / img. Skips script + style subtrees.
  - TextParser (NEW)  — paragraph-splitting for the text&code
    family (.txt / .py / .js / .java / .c / .cpp / .h / .php / .go
    / .ts / .sh / .cs / .kt / .sql). Adds FileTypeTXT to
    utility.FileType and wires the pythonFamilyName → extension
    mapping.
  - PDFParser         — emits ErrPDFEngineUnavailable (the
    DeepDOC pipeline needs an injected Engine + DocAnalyzer;
    wiring lands in a follow-up slice).
  - DOCXParser (CGO)  — captures office_oxide ToMarkdown.
  - DOCParser (CGO)   — captures office_oxide PlainText.
  - PPTXParser (CGO)  — emits one JSON item per slide.
  - PPTParser (CGO)   — delegates to PPTXParser.
  - XLSXParser (CGO)  — uses excelize to render sheets as HTML.
  - XLSXParser (no-cgo) — emits ErrOfficeCGORequired.
  - All other office families (no-CGO) — same explicit error.

The dispatch seam now picks up these implementations
automatically via the type-assertion at parser_dispatch.go:201.

Adds 8 new tests (parse_with_result_test.go) + 2 PDF producer
tests in parse_result_test.go. Floor: 174 passed.

ingestion: Phase 3 Slice 2 — chunker parity fields

Python's rag/flow/chunker/_build_json_chunks forwards several
fields on each input item that the Go chunker was dropping:

  - mom           — parent-section identifier (title / hierarchy
                    chunkers populate; TokenChunker pass-through).
  - img_id        — image attachment identifier.
  - layout        — layout classification (text / table / image).
  - _pdf_positions — PDF bbox coordinates from the DeepDOC path.

This commit:

  - Refactors chunkFromItem to use buildChunkMap, which copies
    the python-compatible payload keys from the input item map.
  - Extends chunksFromInputs to also accept the "json" key
    (the Parser component emits its structured output there),
    so a token-chunker can run directly after a parser without
    an intermediate reshape.

Adds 13 parity tests (python_parity_test.go) covering all four
pass-through fields + the content_with_weight fallback (already
in itemText) + the empty-input contract + the runtime registry.

Floor: 166 passed (158 ingestion + 8 chunker parity).

ingestion: Phase 5 Slice 3 — Tokenizer fallback + Extractor placeholders

Two contract gaps the python port satisfies but the Go port did
not:

  - rag/flow/tokenizer.py:111 falls back to content_with_weight
    when the chunk's "text" is empty. The Go Tokenizer now has
    a normalizeChunkTextFallback pass that runs before
    tokenizeChunks; the chunker's emitted text wins on conflict
    (regression-guarded by TestTokenizer_DoesNotChangeChunkText).

  - rag/flow/extractor/extractor.py:build_existing_prompt
    substitutes {ComponentName:ParamName@chunks} patterns with
    the joined chunk text. The Go Extractor now does the same
    via a regex (placeholderRE) — avoiding a Jinja template
    engine dependency for a single substitution shape. The
    resume template's {TitleChunker:FlatMiceFix@chunks}
    reference now resolves at runtime.

Adds 6 Slice 3 tests (slice3_test.go):
  - 2 Tokenizer fallback / regression tests
  - 4 Extractor placeholder tests (replace, empty-chunks no-op,
    no-placeholder no-op, empty-chunk-text trim)

Floor: 172 passed.

ingestion: Phase 4 Slice 4 partial — TemplateToPipelineDSL translator

The production templates under agent/templates/ingestion_pipeline_*.json
use the modern keyed-components DSL shape:

  dsl.components[id].obj.component_name
  dsl.components[id].obj.params

PipelineDSL on the other hand is a linear Stages[] array. The
canvas runner accepts the keyed-components shape directly (via
the PipelineToCanvas adapter from f0bc8761e) so the canvas path
works, but the pipeline package's existing NewPipelineFromDSL
and the 28+ pipeline_test.go tests consume the linear Stages[]
shape. Without a translator, a template-driven run cannot feed
those paths.

This commit adds TemplateToPipelineDSL:

  - Walks the keyed-components shape, validates every node's
    component_name against runtime.CategoryIngestion.
  - Rejects non-ingestion canvas_category with
    ErrTemplateNotIngestion.
  - Rejects agent-only components (Begin / Message / UserFillUp)
    with ErrTemplateAgentNode.
  - Rejects duplicate component_names with errDuplicateStage
    (the legacy pipeline shape is singleton-per-component; the
    canvas shape's per-instance ids are merged on conversion).
  - Emits a deterministic id-sorted Stages[].

Adds 7 translator tests covering: linear chain round-trip,
non-ingestion category rejection, agent node rejection,
duplicate rejection, empty / nil input rejection, and a
4-stage fixture mirroring production general.json.

Floor: 43 pipeline tests pass (36 prior + 7 translator).

ingestion: Phase 4 Slice 5 — T0–T6 template acceptance harness

Adds 15 acceptance tests covering all seven production
templates under agent/templates/ingestion_pipeline_*.json:

  T0 general — 4-stage chain File → Parser → TokenChunker → Tokenizer
  T1 laws    — File → Parser → TitleChunker → Tokenizer (asserts
              on union of expected components since the linear
              sort may not match downstream ordering)
  T2 book    — TokenChunker with remove_toc=true
  T3 resume  — includes Extractor (LLM-backed metadata extraction)
  T4 paper   — GroupTitleChunker with method=group
  T5 manual  — GroupTitleChunker
  T6 one     — TokenChunker with delimiter_mode=one

Plus a RoundTrip sub-test per template that drives the full
TemplateToPipelineDSL → PipelineToCanvas pipeline.

loadTemplate merges the production templates' top-level
canvas_category with the nested dsl.components shape so the
translator sees a single map carrying both keys (the
production templates store canvas_category at the top level
and the keyed-components under dsl).

Floor: 58 pipeline tests pass (43 prior + 15 harness).

This is the T0–T6 acceptance gate from the plan §8. The
canvas-runner integration that drives the actual execution
remains Slice 4 partial; this harness proves the template
shapes round-trip through the translation + adapter pipeline.

ingestion: Phase 4 deferred-2/3 — Pipeline.RunCanvas + executeTask switch

Phase 4 row 2 (Pipeline.Run → Runner.Run integration) and row 3
(Ingestor.executeTask delegates) were marked OPEN in the plan
§13 after Slices 0–5. This commit closes both:

  - Pipeline.RunCanvas(ctx, inputs, startAt): new canvas-driven
    entry point. Builds a RunFunc closure that walks the
    pipeline's stage list, invokes each registered component
    via runtime.DefaultRegistry, and merges per-stage outputs
    into the accumulated state. Drives Runner.Run with the
    closure and drains the event channel. Coexists with the
    legacy Pipeline.Run direct-walk so the 28+ pipeline_test.go
    tests continue to pass.
  - Ingestor.executeTask: switches from pl.Run to pl.RunCanvas.
    The legacy walker remains in place for direct callers; this
    site is now the canonical canvas-driven entry point.

Adds 4 RunCanvas tests (run_canvas_test.go):
  - happy-path 2-stage chain with mock components
  - startAt=1 skips leading stage
  - nil-pipeline rejection
  - per-stage error propagation

Floor: 254 passed (was 250). The 2 failing tests are the
documented pre-existing seed-bug cases (unchanged).

Wire PDF ParseWithResult to DeepDOC

ingestion: aggressive cutover — delete legacy Pipeline.Run, rename RunCanvas→Run

The user requested a more aggressive cutover: remove the legacy
direct-walk Pipeline.Run entirely. RunCanvas becomes the only
execution path and is renamed to Run.

Changes:

  - pipeline.go: Pipeline.Run body (the legacy direct-walk) is
    deleted. Replaced with a one-line comment pointing to run.go.
  - run_canvas.go → run.go: the canvas-driven method is renamed
    from RunCanvas to Run. The body now absorbs every
    responsibility the legacy walker had:
      - input/output merging per stage
      - stage fingerprinting + IdempotencyKey stamping
      - chunker boundary persistence (persistChunkerBoundary)
      - File-boundary storage reference recording (recordFileRef)
      - per-stage checkpoint flush (flushCheckpoint)
      - per-stage progress reporting
    The RunFunc closure drives the runner; per-stage state
    persistence runs AFTER the runner returns so chunker
    boundaries + File refs only land on success.
  - ingestion_service.go: executeTask now calls pl.Run (was
    pl.RunCanvas).
  - run_test.go: 4 tests renamed from RunCanvas_* to Run_*.
  - pipeline_test.go: 10 pl.RunCanvas call sites renamed to pl.Run.

No compatibility shim. The canvas-driven path is the only
execution path. The 28+ pipeline_test.go tests continue to
build against pl.Run because they were already calling it.

Build is clean. Test floor is gated on 'bash build.sh --go'
which compiles the C++ static lib (per the user's confirmed
build setup).

ingestion: aggressive cutover — delete legacy Pipeline.Run, rename RunCanvas→Run

The user requested a more aggressive cutover: remove the legacy
direct-walk Pipeline.Run entirely. RunCanvas becomes the only
execution path and is renamed to Run.

Changes:

  - pipeline.go: Pipeline.Run body (the legacy direct-walk) is
    deleted. Replaced with a one-line comment pointing to run.go.
  - run_canvas.go → run.go: the canvas-driven method is renamed
    from RunCanvas to Run. The body now absorbs every
    responsibility the legacy walker had:
      - input/output merging per stage
      - stage fingerprinting + IdempotencyKey stamping
      - chunker boundary persistence (persistChunkerBoundary)
      - File-boundary storage reference recording (recordFileRef)
      - per-stage checkpoint flush (flushCheckpoint)
      - per-stage progress reporting
    The RunFunc closure drives the runner; per-stage state
    persistence runs AFTER the runner returns so chunker
    boundaries + File refs only land on success.
  - ingestion_service.go: executeTask now calls pl.Run (was
    pl.RunCanvas).
  - run_test.go: 4 tests renamed from RunCanvas_* to Run_*.
  - pipeline_test.go: 10 pl.RunCanvas call sites renamed to pl.Run.

No compatibility shim. The canvas-driven path is the only
execution path. The 28+ pipeline_test.go tests continue to
build against pl.Run because they were already calling it.

Build is clean. Test floor is gated on 'bash build.sh --go'
which compiles the C++ static lib (per the user's confirmed
build setup).

Make pipeline run from full canvas graph

removed binaries
After rebasing onto upstream/main (which consolidated the three service
binaries into cmd/ragflow_main.go via 7d64a78), the rag/flow pipeline
port's two anchor points — the wire blank-import for component
registration and the componentsHandler wired into router.NewRouter — were
left stranded on the deleted cmd/server_main.go.

- cmd/ragflow_main.go: blank-import ragflow/internal/ingestion/wire so
  the ingestion components (File / Parser / Tokenizer / Extractor + 4
  Chunker variants) register when the unified binary runs in --ingestor
  mode. Without this, --ingestor fails at run time with 'unknown
  component' on every pipeline stage.
- cmd/ragflow_main.go: instantiate and pass handler.NewComponentsHandler
  to router.NewRouter (the new 31-arg signature expects it for the
  GET /api/v1/components?category=... endpoint).
- internal/ingestion/ingestion_service.go: drop the stale third arg
  (res.StartAt) from pl.Run — the current Pipeline.Run signature is
  (ctx, inputs) and the StartAt index is now consumed internally by
  RestoreFromCheckpoint.
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jul 5, 2026
@coderabbitai

coderabbitai Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 21323324-bb24-470e-a66b-b68de4bb247f

📥 Commits

Reviewing files that changed from the base of the PR and between f9441fb and 20763a5.

📒 Files selected for processing (2)
  • internal/ingestion/component/slice3_test.go
  • internal/ingestion/component/tokenizer_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/ingestion/component/slice3_test.go
  • internal/ingestion/component/tokenizer_test.go

📝 Walkthrough

Walkthrough

This PR replaces legacy ingestion and parser paths with shared runtime-backed components, typed parser outputs, and canvas DSL execution. It also adds a components discovery API, updates build/docs guidance, and adjusts CGO/no-CGO boundaries.

Changes

Repository guidance and build tooling

Layer / File(s) Summary
Docs and build tooling
AGENTS.md, .gitignore, build.sh
Repository instructions are rewritten, ignore patterns are added, and Go test argument forwarding is updated.

Runtime registry and components API

Layer / File(s) Summary
Runtime registry and helpers
internal/agent/runtime/*, tests
Adds the category-aware runtime registry, default factory wiring, and progress/timeout/elapsed helpers with tests.
Agent registry adapter and canvas timeout
internal/agent/component/*, internal/agent/canvas/*, internal/service/canvas_decode.go
Rewires the legacy agent registry to the shared runtime registry and moves canvas DSL decoding into canvas.DecodeFromDSL.
Components discovery API
internal/service/components_service.go, internal/handler/components.go, internal/router/router.go, cmd/ragflow_server.go, tests
Exposes GET /api/v1/components with category filtering over the runtime registry.

Parser and chunk execution rewrite

Layer / File(s) Summary
CGO and no-CGO build split
internal/binding/*, internal/deepdoc/parser/pdf/*, internal/ingestion/compilation/extractor/*
Build tags and stub implementations separate CGO-only code from no-CGO fallbacks for analyzer, PDF, and NER paths.
ParseResult contract and parsers
internal/parser/parser/*
Introduces ParseResult/ParseResultProducer and per-format parser implementations for text, HTML, markdown, PDF, office, XLS, and XLSX.
Chunk execution engine and CLI wiring
internal/parser/chunk/*, internal/cli/user_command.go, internal/cli/dev_parser.go
Adds the new chunk execution pipeline and rewires CLI chunk/parse paths to use ParseWithResult and chunk.Run.

Ingestion components and pipeline

Layer / File(s) Summary
Ingestion wire schemas
internal/ingestion/component/schema/*
Adds typed contracts for file, parser, chunker, tokenizer, and extractor payloads plus shared validation error types and schema tests.
File component
internal/ingestion/component/file.go, document_storage.go, idempotency.go, tests
Resolves doc_id or file descriptors to name, bucket, and path through DAO/storage helpers.
Parser component
internal/ingestion/component/parser.go, parser_dispatch.go, tests
Batches and orders page parsing, then dispatches to ParseResultProducer backends.
Extractor component
internal/ingestion/component/extractor.go, tests
Adds LLM-based field extraction with an injectable chat invoker and prompt placeholder substitution.
Tokenizer component
internal/ingestion/component/tokenizer.go, tests
Tokenizes chunk text and batches embedding calls via an injectable Embedder.
Chunker components
internal/ingestion/component/chunker/*.go, tests
Implements Token, Group, Hierarchy, and Title chunkers plus shared registration helpers.
Pipeline engine
internal/ingestion/pipeline/*.go, internal/ingestion/wire/wire.go
Compiles and runs canvas DSL pipelines against the runtime registry and wires component registration via blank imports.
Ingestion task execution
internal/ingestion/ingestion_service.go, internal/dao/ingestion.go, tests
Runs canonical DSL pipelines per task and centralizes task status and Ack/Nack disposition.

Estimated code review effort: 5 (Critical) | ~150+ minutes

Sequence Diagram(s)

sequenceDiagram
  participant Ingestor
  participant Pipeline
  participant Canvas
  participant RuntimeRegistry
  participant Components

  Ingestor->>Pipeline: NewPipelineFromDSL(dsl, taskID)
  Pipeline->>Canvas: DecodeFromDSL(dsl)
  Ingestor->>Pipeline: Run(ctx, inputs)
  Pipeline->>RuntimeRegistry: InstallDefaultRegistryFactory()
  Canvas->>RuntimeRegistry: Lookup(componentName)
  RuntimeRegistry-->>Canvas: factory
  Canvas->>Components: Invoke(ctx, inputs)
  Components-->>Canvas: outputs
  Canvas-->>Pipeline: workflow result
  Pipeline-->>Ingestor: merged output + state
Loading

Possibly related PRs

Suggested labels: ci, size:XXL

Suggested reviewers: JinHai-CN, yingfeng

Poem

A rabbit hopped through registries bright,
And split the parsers into typed delight.
Pipelines now can run and sing,
With chunks and components all in spring,
Hooray for carrots, code, and light 🐇

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change set: aligning Go ingestion behavior with Python across boundaries and output semantics.
Description check ✅ Passed The description captures the PR’s purpose and major changes, but it is shorter than the template’s requested summary with background context.
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.

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: 2

Note

Due to the large number of review comments, Critical severity comments were prioritized as inline comments.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
internal/ingestion/ingestion_service.go (2)

483-489: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Commented-out code left inside defer — remove instead of leaving a recovery note.

The defer func() { ... } body is now 100% commented-out lines. Per repo guideline, commented-out Go code should be removed, not preserved as a "recovery note."

🧹 Proposed cleanup
 func (e *Ingestor) executeTask(taskCtx *TaskContext) {
-	defer func() {
-		//e.tasksMu.Lock()
-		//delete(e.currentTasks, taskCtx.Task.TaskId)
-		//e.tasksMu.Unlock()
-	}()
-
 	ctx := taskCtx.Ctx

As per coding guidelines, "Remove commented-out Go code instead of leaving recovery notes in place."

🤖 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/ingestion/ingestion_service.go` around lines 483 - 489, The defer
block in executeTask contains only commented-out Go code, which should be
removed entirely rather than left as a recovery note. Clean up the executeTask
function by deleting the empty defer func() block and any commented-out task
cleanup lines, keeping only active code and preserving the existing task flow.

Source: Coding guidelines


209-211: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Remove the remaining commented-out ingestion admin flow internal/ingestion/ingestion_service.go:209 still contains the old Connect/admin block, and there are additional stale commented sections later in the file. Delete the dead Go code instead of leaving it behind.

🤖 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/ingestion/ingestion_service.go` around lines 209 - 211, The
ingestion service still contains stale commented-out admin/connect flow and
other dead Go code that should be removed. Clean up the leftover commented
sections in ingestion_service.go by deleting the obsolete blocks around the old
admin registration path and any similar commented code later in the file,
especially within the ingestion_service implementation and related helper
methods. Keep only active code so the file no longer carries unused commented
logic.
♻️ Duplicate comments (1)
internal/service/components_service.go (1)

68-100: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

List unconditionally exposes legacy-adapter components with empty metadata.

Every component registered via internal/agent/component.Register carries Metadata{Version: "legacy", Inputs: nil, Outputs: nil} (see internal/agent/component/registry.go, Lines 68-76). Since List iterates all registered names without any metadata-completeness check, the discovery endpoint's primary value proposition — describing a component's inputs/outputs — is empty for every agent component today. This directly contradicts the migration rule documented in internal/agent/component/registry.go (Lines 58-61): "agent/shared components must be backfilled with real metadata before they are exposed to the component catalog." Flagging here since this is the enforcement point that's missing.

🤖 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/components_service.go` around lines 68 - 100,
`ComponentsService.List` is exposing legacy agent components that only have
placeholder metadata, so discovery returns empty inputs/outputs. Update `List`
to enforce the catalog contract by skipping any registry entry whose metadata is
still legacy/incomplete (for example, the `Metadata` returned from
`runtime.DefaultRegistry.Lookup` when it has the legacy marker and no real
inputs/outputs). Apply this check in both the unfiltered and category-filtered
branches, using the existing `descriptor`, `runtime.DefaultRegistry.Lookup`, and
`dedupeCategories` flow as the place to filter before appending to `out`.
🟠 Major comments (25)
build.sh-514-517 (1)

514-517: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Keep the --test argv filtering in sync with the parsed args.

shift still operates on the original positional params, not the filtered args array, so --strip can be discarded instead of --test. It also forwards the CI-style -- delimiter into go test, which breaks the targeted test path. Rebuild the forwarded argv from args and strip the delimiter explicitly.

Suggested fix
         --test|-t)
             check_go_deps
-            shift
-            run_go_tests "$@"
+            if [ "${args[1]:-}" = "--" ]; then
+                run_go_tests "${args[@]:2}"
+            else
+                run_go_tests "${args[@]:1}"
+            fi
             ;;
🤖 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 `@build.sh` around lines 514 - 517, The `--test` handling in the main argument
parser is still shifting the original positional params instead of the filtered
`args`, so the forwarded test arguments can lose `--strip` and accidentally pass
the CI `--` delimiter through to `run_go_tests`. Update the `--test|-t` branch
to rebuild the argv from `args` after parsing, and explicitly remove the
delimiter before calling `run_go_tests`, keeping the behavior aligned with the
parsed options.
internal/ingestion/compilation/extractor/no_cgo.go-19-38 (1)

19-38: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Doc comment references the wrong build tag and overstates default availability.

This comment states the sibling files "carry //go:build cgo" and that "the CGO path (the //go:build cgo files are selected when CGO_ENABLED=1, which is the default)" — but ner.go, ner_extractor.go, and parser_go.go are actually gated by the custom tag //go:build cgo_thincner, not the built-in cgo constraint. cgo_thincner is never implied by CGO_ENABLED=1; it requires an explicit -tags=cgo_thincner. As written, this stale/incorrect documentation could mislead engineers into believing real NER inference runs by default in production builds when in fact this no-cgo stub (returning ErrNoCGO) is what actually compiles unless the custom tag is explicitly passed.

📝 Suggested correction
-// The C++ ThincNER engine (and its ThincParser / ThincTagger
-// siblings) is wired through cgo in ner.go, parser_go.go, and
-// ner_extractor.go — those files carry `//go:build cgo`. Without
-// the CGO build tag, the test binary cannot link the missing
-// ThincNER_* / ThincParser_* / ThincTagger_* symbols.
+// The C++ ThincNER engine (and its ThincParser / ThincTagger
+// siblings) is wired through cgo in ner.go, parser_go.go, and
+// ner_extractor.go — those files carry `//go:build cgo_thincner`.
+// Without that explicit build tag, the test binary cannot link the
+// missing ThincNER_* / ThincParser_* / ThincTagger_* symbols.
@@
-// The cgo-backed functions return an explicit ErrNoCGO error so
-// any caller that reaches the C++ engine on a no-CGO build fails
-// loudly rather than silently degrading. Production builds keep
-// the CGO path (the `//go:build cgo` files are selected when
-// CGO_ENABLED=1, which is the default).
+// The cgo-backed functions return an explicit ErrNoCGO error so
+// any caller that reaches the C++ engine on a no-`cgo_thincner`
+// build fails loudly rather than silently degrading. Production
+// builds that need real NER inference must explicitly pass
+// `-tags=cgo_thincner`; it is not enabled merely by CGO_ENABLED=1.
As per coding guidelines: "Keep Go package comments and doc comments aligned with the current runtime path, not with migration history."
🤖 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/ingestion/compilation/extractor/no_cgo.go` around lines 19 - 38, The
package-level stub comment in no_cgo.go is outdated and misleading about the
build constraints used by the ThincNER-backed files. Update the comment near the
no-cgo declarations to say that ner.go, ner_extractor.go, and parser_go.go are
gated by the custom cgo_thincner build tag, not the built-in cgo tag, and that
CGO_ENABLED=1 does not select that path unless -tags=cgo_thincner is explicitly
provided. Keep the description of ErrNoCGO and the exported surface aligned with
the actual no-CGO fallback in this package.

Source: Coding guidelines

internal/agent/runtime/registry.go-116-133 (1)

116-133: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Runtime error message embeds internal planning-doc references.

The empty-metadata error string literally quotes "see plan §4 Phase 0 task 1" and prescribes migration rules inline in an error that can surface in logs/API 500 responses. Callers/operators outside this repo's migration effort have no access to "plan §4", making the message confusing rather than actionable. Error text should describe the actual violated invariant, not point at a planning document.

As per coding guidelines: "Keep Go package comments and doc comments aligned with the current runtime path, not with migration history" — the same principle applies more strongly to user-facing error strings.

🐛 Suggested fix
-	if metadata.Version == "" && metadata.Inputs == nil && metadata.Outputs == nil {
-		return fmt.Errorf("runtime: %q registered with empty metadata (Version, Inputs, Outputs all unset; "+
-			"see plan §4 Phase 0 task 1 — ingestion components MUST supply a version string, "+
-			"legacy agent-component adapter MUST supply {Version: \"legacy\"})", name)
-	}
+	if metadata.Version == "" && metadata.Inputs == nil && metadata.Outputs == nil {
+		return fmt.Errorf("runtime: %q registered with empty metadata (Version, Inputs, and Outputs are all unset)", name)
+	}
🤖 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/agent/runtime/registry.go` around lines 116 - 133, The
empty-metadata error in memoryRegistry.Register includes internal migration-plan
wording that should not appear in user-facing logs or API errors. Update
Register to return a concise invariant-focused message that only states the
component name was registered without required metadata, and keep the check tied
to metadata.Version, metadata.Inputs, and metadata.Outputs without referencing
the planning doc. Use the existing Register and memoryRegistry symbols to locate
the message, and ensure the error stays actionable for callers outside this
repo.

Source: Coding guidelines

internal/agent/runtime/helpers.go-90-100 (1)

90-100: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Function doc comments continue the same migration-log style.

WithTimeout's and TrackElapsed's docs repeatedly cite Python line numbers (base.py:42, 58) and asyncio.TimeoutError/ProcessBase semantics instead of describing the Go contract on its own terms. Same guideline violation as the package doc above — consider condensing to just the Go-observable behavior (return values, error semantics, map keys).

As per coding guidelines: "Keep Go package comments and doc comments aligned with the current runtime path, not with migration history."

Also applies to: 128-146

🤖 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/agent/runtime/helpers.go` around lines 90 - 100, The doc comments
for WithTimeout and TrackElapsed are still written as migration notes and
reference Python-specific implementation details instead of the Go contract.
Update the comments near those symbols to describe only the Go-observable
behavior: what each function returns, how timeout and cancellation errors are
surfaced, and what TrackElapsed records in its map keys, without citing Python
line numbers, asyncio semantics, or ProcessBase history.

Source: Coding guidelines

internal/router/router.go-564-570 (1)

564-570: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Comment references an internal migration-plan document instead of describing current behavior.

"Phase 4 of port-rag-flow-pipeline-to-go.md" is migration-history bookkeeping embedded in a route-registration comment. Per coding guidelines, doc comments should describe the current runtime path, not migration history.

✏️ Suggested trim
-			// Component catalog — Phase 4 of
-			// port-rag-flow-pipeline-to-go.md. Optional
-			// ?category=ingestion,agent,shared filter; defaults to
-			// all categories. The data source is
-			// runtime.DefaultRegistry.
+			// Component catalog. Optional ?category=ingestion,agent,shared
+			// filter; defaults to all categories. Data source is
+			// runtime.DefaultRegistry.
 			v1.GET("/components", r.componentsHandler.Get)

As per coding guidelines: "Keep Go package comments and doc comments aligned with the current runtime path, not with migration history."

🤖 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/router/router.go` around lines 564 - 570, The route comment above
componentsHandler.Get still mentions migration history (“Phase 4” and the plan
document), which should be removed. Update the doc comment in router
registration to describe only the current behavior of the /components endpoint,
including its optional category filter and data source, and keep it aligned with
the runtime path rather than the migration plan.

Source: Coding guidelines

internal/agent/runtime/helpers.go-17-38 (1)

17-38: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Trim migration-history narrative from the package doc.

This doc comment is written as a porting log against Python rag/flow/base.py:ProcessBase (dual timeout layers, plan §8 R1) rather than describing the current Go contract. Per coding guidelines, package/doc comments should describe the current runtime path, not migration history.

✏️ Suggested trim
-// Cross-cutting helpers that replace Python's `rag/flow/base.py:ProcessBase`
-// wrapper (lines 33-63). Three call-site concerns are extracted into plain
-// higher-order functions:
+// Cross-cutting helpers used by pipeline/canvas call sites. Three
+// concerns are extracted into plain higher-order functions:
 //
 //	(a) timeout enforcement         -> WithTimeout
 //	(b) progress callback fan-out   -> TrackProgress
 //	(c) elapsed-time accounting     -> TrackElapsed
 //
 // These live in `runtime` (rather than as a `Component` interface method or
 // a base type) because they are call-site concerns, not extension points.
 // Both `internal/ingestion/pipeline` and `internal/agent/canvas` compose
 // them at the DAG-node / goroutine boundary.
-//
-// LOSSY MAPPING (plan §8 R1):
-//
-// Python `ProcessBase._invoke` is wrapped by BOTH `asyncio.wait_for` AND
-// the `@timeout` decorator — a dual-layer timeout to catch different
-// failure modes. Go's `context.WithTimeout` collapses this into a single
-// layer; `WithTimeout` covers the outer one (asyncio.wait_for equivalent).
-// The inner `@timeout` decorator has no Go equivalent and is not
-// replicated here. If a future requirement needs the inner layer,
-// `WithTimeout` can be nested at the call site.
+//
+// `WithTimeout` enforces a single context-based timeout; nest calls at
+// the call site if a layered timeout is required.
 package runtime

Based on learnings and coding guidelines: "Keep Go package comments and doc comments aligned with the current runtime path, not with migration history" and "Do not add new compatibility wording in comments or docs."

🤖 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/agent/runtime/helpers.go` around lines 17 - 38, Trim the package
comment in helpers.go so it describes the current runtime helpers only, not the
Python porting history or migration notes. Update the comment near WithTimeout,
TrackProgress, and TrackElapsed to focus on their present behavior and call-site
role, and remove references to rag/flow/base.py, plan §8 R1, dual-layer timeout
mapping, and any compatibility/migration wording.

Sources: Coding guidelines, Learnings

internal/ingestion/component/parser.go-17-72 (1)

17-72: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Package doc comment documents migration history, not current runtime behavior.

This comment block ("SCOPE (honest)", "WHAT IS NOT YET PORTED", references to port-rag-flow-pipeline-to-go.md) describes a prior/roadmap state of the code. It's now stale: dispatchParse (parser_dispatch.go) already performs real structured parsing via parser.GetParser/ParseWithResult, not "SKELETONS that print to stdout and return nil" as claimed here. As per coding guidelines, "Keep Go package comments and doc comments aligned with the current runtime path, not with migration history." Please rewrite this to describe what the component actually does today (fan-out page parsing + dispatch to structured parsers, with a raw-text fallback for unrecognized file types), and drop the plan/phase references.

🤖 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/ingestion/component/parser.go` around lines 17 - 72, Rewrite the
package comment in parser.go so it describes the current runtime behavior of
ParserComponent, not the migration plan: explain that NewParserComponent/Invoke
fan out page parsing, dispatch through parser.GetParser and ParseWithResult via
dispatchParse, merge results deterministically, and fall back to raw-text
parsing for unrecognized inputs. Remove the “SCOPE (honest)”, “WHAT IS NOT YET
PORTED”, and port-rag-flow-pipeline-to-go.md phase/history references, and
ensure the comment matches the actual parser package behavior today.

Source: Coding guidelines

internal/ingestion/component/parser_dispatch.go-100-151 (1)

100-151: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use the family key when resolving lib_type. dispatchParse passes the extension form here, so the family-keyed slides / spreadsheet setups never match; their parse_method is lost and NewPPTXParser / NewXLSXParser reject the empty lib_type, so those pipelines fail instead of falling back.

🤖 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/ingestion/component/parser_dispatch.go` around lines 100 - 151,
`dispatchParse` is looking up parser setup data with the extension-based file
type, so family-scoped entries like slides and spreadsheet are missed and their
`lib_type`/`parse_method` never resolve. Update `resolveLibType` to use the
family key for the parser setup lookup (matching how `parser.GetParser`,
`NewPPTXParser`, and `NewXLSXParser` expect these configs) while keeping the
existing fallback behavior for unset `lib_type`.
internal/ingestion/component/schema/parser.go-74-76 (1)

74-76: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Doc comment references migration phase.

"business-rule validation lives in the component implementation (Phase 2.2)" describes migration planning rather than the current contract.

As per coding guidelines, "Keep Go package comments and doc comments aligned with the current runtime path, not with migration history."

🤖 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/ingestion/component/schema/parser.go` around lines 74 - 76, The doc
comment on Validate in parser.go should describe the current runtime contract
only, not migration history. Update the comment near Validate() to remove the
Phase 2.2 reference and any wording about migration planning, while keeping the
distinction that Validate() enforces wire-shape only and component-specific
business-rule checks remain in the component implementation via check().

Source: Coding guidelines

internal/ingestion/component/file.go-17-39 (1)

17-39: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Multiple doc comments describe migration phases instead of current behavior.

"Phase 2.1", "Phase 2.1 spec", "Phase 2.5+", and "plan §4 Phase 2.1" appear throughout this file's doc comments, describing the migration roadmap rather than what the code does today.

As per coding guidelines, "Keep Go package comments and doc comments aligned with the current runtime path, not with migration history."

Also applies to: 74-84, 87-90, 262-266

🤖 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/ingestion/component/file.go` around lines 17 - 39, Several doc
comments in this file still describe migration phases and roadmap notes instead
of the component’s current runtime behavior. Update the package comment and the
affected comments around the file-level documentation, the `File` component
area, and the `TrackProgress`/parser-related sections so they describe what
`component` does today without references to “Phase 2.1”, “Phase 2.5+”, or plan
sections. Keep the descriptions aligned with the actual behavior of the relevant
symbols such as `component`, `runtime.TrackProgress`, and the file ingestion
flow.

Source: Coding guidelines

internal/ingestion/component/schema/file.go-69-76 (1)

69-76: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Doc comment references migration phase, not current behavior.

The comment justifies keeping FileParam empty by citing "Phase 2.1"/future phases rather than describing current runtime behavior.

✏️ Suggested rewrite
-// Mirrors rag/flow/file.py:FileParam. The Python class has no fields
-// beyond what ProcessParamBase provides (none stored on the instance), so
-// the Go struct is intentionally empty. It is kept as a distinct type so
-// Phase 2.1 can attach config knobs (e.g., a `with_blob` flag) without a
-// rename.
+// Mirrors rag/flow/file.py:FileParam. The Python class has no fields
+// beyond what ProcessParamBase provides (none stored on the instance), so
+// the Go struct is intentionally empty. It is kept as a distinct type to
+// allow future config knobs (e.g., a `with_blob` flag) without a rename.

As per coding guidelines, "Keep Go package comments and doc comments aligned with the current runtime path, not with migration history."

🤖 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/ingestion/component/schema/file.go` around lines 69 - 76, The
FileParam doc comment is describing migration history and future phases instead
of the current behavior. Update the comment on FileParam to explain only the
present runtime purpose of the empty struct and its relationship to
ProcessParamBase, and remove references to Phase 2.1 or future config knobs so
the documentation matches current behavior.

Source: Coding guidelines

internal/parser/parser/ppt_parser.go-44-57 (1)

44-57: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Route legacy .ppt bytes through the ppt reader
office_oxide requires the correct format string for raw bytes and does not auto-detect, so passing genuine .ppt CFB payloads as "pptx" will fail here. Use "ppt" on this path or detect the format before dispatching.

🤖 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/parser/parser/ppt_parser.go` around lines 44 - 57, The PPT parsing
path in ParseWithResult is delegating legacy .ppt bytes through NewPPTXParser
with the wrong format, which breaks OfficeOxide on raw CFB payloads. Update the
PPTParser.ParseWithResult path to use the ppt reader/format instead of
hardcoding pptx, or add format detection before creating the delegate. Keep the
existing format override on the ParseResult, but ensure the underlying parser is
selected correctly for genuine .ppt data.
internal/parser/parser/pdf_parser_common.go-87-115 (1)

87-115: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Duplicate image data-URL prefixing logic.

pdfParseResultToJSON (lines 102-104) already prefixes image with "data:image/png;base64,", then parsePDFWithDeepDoc (lines 175-179) re-checks and calls inlinePNGDataURL on the same field — a no-op today only because of the guard in inlinePNGDataURL, but it's redundant, duplicate logic that can silently diverge if one path is edited without the other.

♻️ Suggested consolidation
 	for i := range items {
 		if layoutType, _ := items[i]["layout_type"].(string); layoutType != "" {
 			items[i]["layout"] = layoutType
 		}
 		if _, ok := items[i]["page_number"]; !ok {
 			items[i]["page_number"] = firstPageNumber(items[i]["_pdf_positions"])
 		}
-		if img, _ := items[i]["image"].(string); img != "" {
-			items[i]["image"] = "data:image/png;base64," + img
-		}
+		if img, _ := items[i]["image"].(string); img != "" {
+			items[i]["image"] = inlinePNGDataURL(img)
+		}
 	}
-	res := pdfParseResultToJSON(filename, parsed)
-	for i := range res.JSON {
-		if img, _ := res.JSON[i]["image"].(string); img != "" {
-			res.JSON[i]["image"] = inlinePNGDataURL(img)
-		}
-	}
-	return res
+	return pdfParseResultToJSON(filename, parsed)
As per coding guidelines for `internal/{ingestion,parser,deepdoc}`: "prefer collapsing duplicate paths over preserving transitional wrappers."

Also applies to: 166-181

🤖 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/parser/parser/pdf_parser_common.go` around lines 87 - 115,
`pdfParseResultToJSON` and `parsePDFWithDeepDoc` both normalize the same `image`
field, creating duplicate data-URL prefixing logic. Remove the redundant
handling in one place and keep a single source of truth for inlining PNG data
URLs, using the existing helpers like `inlinePNGDataURL` and the `image`
normalization inside `pdfParseResultToJSON` to avoid divergent behavior.

Source: Coding guidelines

internal/parser/parser/pdf_parser_common.go-69-85 (1)

69-85: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Stop falling back to MockDocAnalyzer on configured DeepDOC failures. internal/parser/parser/pdf_parser_common.go:69-85 — keep the mock for the empty-env case only; when DEEPDOC_URL/OSSDEEPDOC_URL is set but the client cannot be created or Health() is false, return an error instead of a healthy mock so outages and misconfigurations don’t turn into silent “successful” parses.

🤖 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/parser/parser/pdf_parser_common.go` around lines 69 - 85, The
fallback logic in deepDocAnalyzerFromEnv is too permissive: it returns
deepdocpdf.MockDocAnalyzer even when DEEPDOC_URL or OSSDEEPDOC_URL is configured
but inference.NewClient fails or client.Health() is false. Keep the mock only
for the empty environment case, and change deepDocAnalyzerFromEnv to return an
error for configured-but-unhealthy DeepDOC setups so callers can surface the
failure instead of silently proceeding.

Source: Coding guidelines

internal/parser/parser/text_parser.go-99-144 (1)

99-144: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Hand-rolled UTF-8 validator misses overlong-encoding and surrogate-half rejection; prefer stdlib.

The comment justifies avoiding unicode/utf8 to stay "dependency-light," but unicode/utf8 is part of the Go standard library, not an external dependency. Meanwhile decodeRune doesn't reject overlong multi-byte encodings or UTF-16 surrogate-half values (U+D800–U+DFFF), both of which utf8.Valid correctly flags as invalid — so this validator can accept byte sequences the spec (and the python side) would treat as invalid UTF-8.

♻️ Suggested fix
 import (
 	"bytes"
 	"strings"
+	"unicode/utf8"
 )
...
-func utf8Valid(data []byte) bool {
-	for i := 0; i < len(data); {
-		r, size := decodeRune(data[i:])
-		if r == 0xFFFD && size == 1 {
-			return false
-		}
-		i += size
-	}
-	return true
-}
-
-// decodeRune is a minimal UTF-8 decoder ...
-func decodeRune(p []byte) (rune, int) {
-	...
-}
+func utf8Valid(data []byte) bool {
+	return utf8.Valid(data)
+}
🤖 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/parser/parser/text_parser.go` around lines 99 - 144, The custom
UTF-8 validation in utf8Valid/decodeRune is incomplete and can accept invalid
sequences such as overlong encodings and surrogate halves. Replace the
hand-rolled logic with the standard library utf8.Valid/utf8.DecodeRune behavior
in text_parser.go, since unicode/utf8 is part of Go’s stdlib and already
provides the correct validation semantics; keep utf8Valid as a thin wrapper if
needed, but ensure it delegates to the stdlib implementation.
internal/parser/parser/text_parser.go-146-178 (1)

146-178: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Slicing only runs once per paragraph, and the hard-slice cut isn't rune-boundary safe.

Two issues in the same block:

  1. The slicing at lines 156-171 is guarded by if, not for — for a single paragraph much larger than 2 * maxItemBytes, only the first maxItemBytes-sized piece is capped; the remainder is appended as one oversized item at line 172-175, violating the documented invariant that "maxItemBytes caps each emitted item's text length."
  2. When no newline exists within the first maxItemBytes bytes, cut = maxItemBytes is a raw byte offset that can land mid-rune, corrupting multi-byte UTF-8 characters (e.g., CJK text) at the split point.
🔧 Suggested fix
-		if maxItemBytes > 0 && len(text) > maxItemBytes {
-			// Slice at the nearest newline below maxItemBytes;
-			// falls back to a hard slice when no newline exists.
-			cut := strings.LastIndex(text[:maxItemBytes], "\n")
-			if cut <= 0 {
-				cut = maxItemBytes
-			}
-			items = append(items, map[string]any{
-				"text":         strings.TrimSpace(text[:cut]),
-				"doc_type_kwd": "text",
-			})
-			text = strings.TrimSpace(text[cut:])
-			if text == "" {
-				continue
-			}
-		}
+		for maxItemBytes > 0 && len(text) > maxItemBytes {
+			// Slice at the nearest newline below maxItemBytes;
+			// falls back to a hard slice at a rune boundary when
+			// no newline exists.
+			cut := strings.LastIndex(text[:maxItemBytes], "\n")
+			if cut <= 0 {
+				cut = maxItemBytes
+				for cut > 0 && !utf8.RuneStart(text[cut]) {
+					cut--
+				}
+			}
+			items = append(items, map[string]any{
+				"text":         strings.TrimSpace(text[:cut]),
+				"doc_type_kwd": "text",
+			})
+			text = strings.TrimSpace(text[cut:])
+		}
+		if text == "" {
+			continue
+		}
🤖 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/parser/parser/text_parser.go` around lines 146 - 178,
textParserItems only slices a long paragraph once and can leave the remainder
oversized, so change the single maxItemBytes check into a loop that keeps
emitting capped chunks until the paragraph is fully consumed. While doing so,
make the fallback hard-slice rune-safe by choosing a cut point on a UTF-8
boundary before splitting, and keep the existing paragraph/newline behavior
intact.
internal/ingestion/ingestion_service.go-516-526 (1)

516-526: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Cancellation-path UpdateStatus failure is silently discarded, unlike the failTask sibling path.

_ = e.ingestionTaskDAO.UpdateStatus(task.ID, common.STOPPED) swallows the error entirely (no log), yet the code unconditionally proceeds to Ack the message anyway. If the STOPPED write fails, the task is permanently stuck in RUNNING with the message already removed from the queue — no retry path and no trace in the logs of why.

🔧 Proposed fix: log the failure like `failTask` does
-			_ = e.ingestionTaskDAO.UpdateStatus(task.ID, common.STOPPED)
+			if statusErr := e.ingestionTaskDAO.UpdateStatus(task.ID, common.STOPPED); statusErr != nil {
+				common.Error(fmt.Sprintf("Task %s update status (stopped) error", task.ID), statusErr)
+			}
🤖 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/ingestion/ingestion_service.go` around lines 516 - 526, The
cancellation path in the task handling flow drops the error from
ingestionTaskDAO.UpdateStatus(task.ID, common.STOPPED), so mirror the
failTask-style handling by checking that return value and logging any failure
before acking the message. Use the surrounding runErr context-cancellation
branch in ingestion_service.go to locate the fix, and keep the Ack only after
the STOPPED update attempt has been logged appropriately.
internal/ingestion/ingestion_service.go-545-573 (1)

545-573: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Handle base64-encoded DSL after DB reload entity.JSONMap marshals []byte as base64, so a persisted schema.pipeline/schema.dsl comes back as a string. defaultPipelineDSL then forwards that raw text after SetRunningByIngestor(), which breaks pipeline loading for reloaded tasks. The current tests reuse the in-memory task and miss this path.

🤖 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/ingestion/ingestion_service.go` around lines 545 - 573,
defaultPipelineDSL currently returns raw string values for schema.pipeline and
schema.dsl, which breaks reloaded tasks because entity.JSONMap can persist
[]byte as base64 text and reload them as strings. Update defaultPipelineDSL to
detect and decode base64-encoded string values before returning, while still
preserving the existing []byte path, and make sure the logic covers both
pipeline and dsl lookups consistently. Add/adjust coverage around
IngestionService task reload behavior and defaultPipelineDSL so the DB-reload
case is exercised rather than only the in-memory task path.
internal/ingestion/component/tokenizer.go-338-356 (1)

338-356: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Dead if block: title-weight blending is documented but never implemented.

The block checks titleWeight != 0 && len(v) > 0 and then does nothing but _ = titleWeight — the "documented deviation" is really just a no-op with a long comment explaining why. This means Param.FilenameEmbdWeight (a user-configurable, documented parameter) currently has zero effect on the produced vectors, silently. Since this repo treats internal/ingestion as actively-refactored code where transitional/"future work" notes should not be preserved in place, either implement the blend now or drop the vestigial conditional so the code doesn't imply a feature that doesn't exist.

♻️ Proposed cleanup (remove the no-op branch until title-blend is implemented)
-					v := vects[k]
-					if titleWeight != 0 && len(v) > 0 {
-						// The title vector path in python pulls
-						// `embedding_model.encode([name])` separately;
-						// here we follow the same wire shape but skip
-						// the title-blend call because that would
-						// double the embedding round-trips. The chunk
-						// vector is recorded as-is. (Documented
-						// deviation; can be added once the embedding
-						// resolver exposes a `title_encode` knob.)
-						_ = titleWeight
-					}
+					v := vects[k]

Based on learnings, "Do not add new compatibility wording in comments or docs" and "Prefer deletion over shims, deprecated branches, wrapper APIs, and dual-track migration notes."

🤖 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/ingestion/component/tokenizer.go` around lines 338 - 356, The
title-weight branch in the tokenizer is a dead no-op: `Param.FilenameEmbdWeight`
is checked in `tokenizer.go` via the `titleWeight`/`vects` loop, but nothing is
actually blended. Remove the vestigial `if titleWeight != 0 && len(v) > 0` block
and its transitional comment unless you implement the real title-vector blend in
this path, so `c.param.FilenameEmbdWeight` does not imply behavior that never
happens.

Source: Learnings

internal/ingestion/ingestion_service.go-532-540 (1)

532-540: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Avoid Nacking after the pipeline has already completed

If UpdateStatus(COMPLETED) fails, the task stays RUNNING, so a redelivery will go back through SetRunningByIngestor and executeTask again. That can replay the whole pipeline and duplicate downstream writes. Handle the status-write failure without requeueing the task, or make this completion path idempotent.

🤖 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/ingestion/ingestion_service.go` around lines 532 - 540, The
completion path in ingestionService.executeTask is requeueing a task after the
pipeline has already finished, which can replay work and duplicate writes.
Update the UpdateStatus(COMPLETED) failure handling so it does not
Nack/negative-ack the task; instead treat the failure as a terminal
completion-path error and still Ack, or otherwise make the executeTask/ackOrNack
flow idempotent so a redelivery cannot rerun the whole pipeline.
internal/ingestion/component/chunker/token.go-289-334 (1)

289-334: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Cancelled/timed-out context silently produces a partial "success" result.

When ctx is cancelled mid-fan-out, unfinished items are set to nil and dropped, but invokeJSONPayload still returns a normal chunks output with no error. Callers (and eventually persisted chunk data) can't tell the difference between "fewer chunks because the input was short" and "fewer chunks because the operation was cut off." Given the doc comment's stated intent to "honour ctx cancellation," the aggregated ctx.Err() should be checked after wg.Wait() and surfaced as an error.

🛡️ Propagate cancellation as an error
 	wg.Wait()
+	if err := ctx.Err(); err != nil {
+		return map[string]any{
+			"output_format": "chunks",
+			"chunks":        []map[string]any{},
+			"_ERROR":        fmt.Sprintf("TokenChunker: %v", err),
+		}
+	}
 
 	// Attach surrounding media context (token_chunker.py:358).
 	attached := attachMediaContext(perItem, c.param.TableContextSize, c.param.ImageContextSize)
🤖 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/ingestion/component/chunker/token.go` around lines 289 - 334,
invokeJSONPayload currently drops unfinished items on ctx cancellation and still
returns a normal chunk result, so cancellation is hidden from callers. After the
fan-out in TokenChunkerComponent.invokeJSONPayload and after wg.Wait(), check
ctx.Err() and surface it as an error instead of returning chunkOutputs when the
context was cancelled or timed out. Keep the existing per-item work in
chunkFromItem/partition intact, but make the aggregated result fail fast on
cancellation so callers can distinguish partial work from a successful run.
internal/ingestion/component/chunker/register.go-17-27 (1)

17-27: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Drop migration-phase references from doc comments.

The package doc comment and MustRegisterChunker's comment cite migration-plan artifacts ("Phase 2.3 of plan port-rag-flow-pipeline-to-go.md", "plan §4 Phase 2 'one init() per file' hard rule") rather than describing the current runtime contract. This reads as transient migration history baked into permanent doc comments.

✏️ Proposed comment cleanup
-// Package chunker holds the ingestion chunker components (Phase 2.3
-// of plan port-rag-flow-pipeline-to-go.md): TokenChunker,
-// TitleChunker, GroupTitleChunker, HierarchyTitleChunker. The four
+// Package chunker holds the ingestion chunker components: TokenChunker,
+// TitleChunker, GroupTitleChunker, HierarchyTitleChunker. The four
 // components share the same upstream payload (schema.ChunkerFromUpstream)
 // and the same output shape (schema.ChunkerOutputs).
@@
-// MustRegisterChunker registers a single chunker component under
-// CategoryIngestion. The four chunker files each carry exactly one
-// init() that calls this with the registered component's name; the
-// factory body resolves the typed constructor via newChunkerByName
-// (in common.go).
-//
-// One helper call per file keeps the registration surface flat
-// (plan §4 Phase 2 "one init() per file" hard rule).
+// MustRegisterChunker registers a single chunker component under
+// CategoryIngestion. Each chunker file carries exactly one init()
+// that calls this with the registered component's name; the factory
+// body resolves the typed constructor via newChunkerByName (in
+// common.go). One helper call per file keeps the registration
+// surface flat.
As per coding guidelines, "Keep Go package comments and doc comments aligned with the current runtime path, not with migration history."

Also applies to: 33-40

🤖 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/ingestion/component/chunker/register.go` around lines 17 - 27,
Remove migration-plan references from the package and MustRegisterChunker doc
comments so they describe the current runtime behavior only. Update the chunker
package comment and the MustRegisterChunker comment to explain what the package
and registration function do now, using symbols like package chunker and
MustRegisterChunker, and avoid mentioning plan phases, rollout artifacts, or
migration rules.

Source: Coding guidelines

internal/ingestion/component/chunker/title.go-17-49 (1)

17-49: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Migration-phase references in doc comment.

The SCOPE (honest) block cites "Phase 2.3b", "plan §4 Phase 2 row 2.3b", and "plan §8 R2" — migration-plan bookkeeping rather than runtime documentation. As with group.go/hierarchy.go, it also claims "2 goroutines" fan out over chunk splits, but TitleChunkerComponent.Invoke only dispatches synchronously to invokeGroup/invokeHierarchy. Recommend trimming these comments to describe the actual heading-detection scope/limitations (the ASCII-only regex-based parity gap is legitimate and worth keeping) without the plan-phase citations.

As per coding guidelines, "Keep Go package comments and doc comments aligned with the current runtime path, not with migration history."

🤖 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/ingestion/component/chunker/title.go` around lines 17 - 49, Remove
the migration-plan references from the SCOPE comment in TitleChunker and keep
only runtime-relevant documentation. Update the package comment near
TitleChunker to drop “Phase 2.3b”, “plan §4 Phase 2 row 2.3b”, and “plan §8 R2”,
and revise the concurrency note so it matches TitleChunkerComponent.Invoke and
its synchronous dispatch to invokeGroup and invokeHierarchy rather than claiming
fan-out behavior. Preserve the useful parity-gap notes about ASCII-only regex
heading detection and the supported resolve_levels path.

Source: Coding guidelines

internal/ingestion/component/chunker/group.go-149-158 (1)

149-158: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Guard the non-text flush to avoid blank chunks. groupRecords appends currentGroup even when it’s empty, so a leading or consecutive non-text record (table/image) can produce an empty group that invokeGroup turns into {"text": ""}. Add the same len(currentGroup) > 0 guard used in the other flush path.

🤖 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/ingestion/component/chunker/group.go` around lines 149 - 158, In
groupRecords, the non-text flush path is appending an empty currentGroup, which
can create blank text chunks when invokeGroup processes them. Update the flush
logic around the rec.isText() branch to match the other flush path by only
appending currentGroup when len(currentGroup) > 0, then keep appending the
non-text record itself as its own group.
internal/ingestion/component/chunker/group.go-17-34 (1)

17-34: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Trim the migration-plan text from the group.go doc comment. The SCOPE block should describe runtime behavior only; remove the Phase 2/plan references and rewrite the Parallelism() note as a declarative hint only if an outer executor uses it.

🤖 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/ingestion/component/chunker/group.go` around lines 17 - 34, The
package comment on GroupTitleChunker in group.go still includes migration-plan
and phase references that belong in design notes, not runtime docs. Trim the
SCOPE block so it only describes the chunker’s behavior, and rephrase the
parallelism note in a neutral declarative way tied to the Parallelism() method
rather than the Phase 2 plan language.

Source: Coding guidelines

🟡 Minor comments (5)
internal/router/router.go-56-56 (1)

56-56: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Guard componentsHandler in Setup or keep Router construction centralized. v1.GET("/components", r.componentsHandler.Get) is unconditional, but this repo also builds &Router{...} directly without componentsHandler; calling Setup on one of those routers will panic. Make it nil-safe like botHandler/mcpServerHandler, or avoid partial Router wiring.

🤖 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/router/router.go` at line 56, The Router.Setup path unconditionally
registers r.componentsHandler.Get, but Router instances can be constructed
without a componentsHandler and will panic when Setup is called. Update Setup to
guard the /components route the same way botHandler and mcpServerHandler are
handled, or centralize Router construction so componentsHandler is always
populated before use.
internal/ingestion/component/file.go-70-98 (1)

70-98: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

bucket field is declared but never wired up.

FileComponent.bucket (line 71) is never set from NewFileComponent's params and never read in Invoke; it's dead scaffolding kept "for forward compatibility." Either wire it to params["bucket"] or drop it until it's actually needed.

🧹 Suggested fix
-type FileComponent struct {
-	bucket string // static config: storage bucket override (rare; default empty)
-}
+type FileComponent struct{}
Based on learnings, "Prefer deletion over shims, deprecated branches, wrapper APIs, and dual-track migration notes" and "Keep exported APIs only when the current code actually needs 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/ingestion/component/file.go` around lines 70 - 98, The FileComponent
bucket field is unused scaffolding and should not be kept as a dead exported
seam. Either wire FileComponent.bucket through NewFileComponent by reading the
bucket value from params and using it in Invoke, or remove the bucket field and
any related forward-compatibility comments if the feature is not implemented
yet. Make the change in NewFileComponent and FileComponent so the struct only
contains state that is actually consumed.

Source: Learnings

internal/parser/chunk/pipeline.go-87-106 (1)

87-106: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

validate()'s default-strategy assignment is dead code.

validate() has a value receiver, so o.SplitStrategy = "sentence" (Line 92) mutates only the local copy and is discarded — Run() never sees the normalized value; opts.SplitStrategy used later (Line 148) can still be "". Today this is masked because the split operator independently defaults empty strategy to "sentence" (per the comment on Lines 60-61), but the "default" logic here is misleading dead code and would silently stop working as documented if the operator's own default ever changes.

🐛 Proposed fix: make validate() mutate through a pointer, or return normalized options
-func (o PipelineOptions) validate() error {
+func (o *PipelineOptions) validate() error {
 	if o.SplitStrategy == "" {
 		// Default to sentence to match the operator's own default;
 		// callers that want a no-op split should override with
 		// "paragraph" + a FilterMinLength >= 1.
 		o.SplitStrategy = "sentence"
 	}
 	...
 }

And update the call site:

-func Run(text string, opts PipelineOptions) (*ChunkContext, error) {
-	if err := opts.validate(); err != nil {
+func Run(text string, opts PipelineOptions) (*ChunkContext, error) {
+	if err := (&opts).validate(); err != nil {
 		return nil, err
 	}
🤖 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/parser/chunk/pipeline.go` around lines 87 - 106, The SplitStrategy
defaulting in PipelineOptions.validate is ineffective because validate uses a
value receiver, so the normalization is lost and Run still sees an empty
SplitStrategy. Fix this by making validate mutate the actual options (for
example, change PipelineOptions.validate to a pointer receiver) or by returning
the normalized PipelineOptions and using that result in Run; make sure the call
site that later reads opts.SplitStrategy uses the updated value.
internal/parser/parser/pdf_parser_common.go-132-151 (1)

132-151: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

firstPageNumber should not silently fall back to 0 on shape mismatches

firstPageNumber is coupled to the current _pdf_positions layout and returns 0 for any deviation, which can emit an incorrect page_number without surfacing the mismatch. Consider a typed helper or an explicit error path instead of defaulting.

🤖 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/parser/parser/pdf_parser_common.go` around lines 132 - 151,
firstPageNumber is masking _pdf_positions shape mismatches by returning 0, which
can produce a false page_number. Update firstPageNumber in pdf_parser_common.go
to use a typed/validated parsing path and surface an explicit error (or
propagate one to the caller) instead of silently defaulting to 0. Make sure the
callers that consume firstPageNumber handle the error case so malformed
positions are not treated as page 0.
internal/ingestion/component/tokenizer_test.go-40-59 (1)

40-59: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Comment claims tests are skipped via t.Skip, but no test does that.

The doc comment says failing tokenizer-pool init means "affected tests are skipped via t.Skip at runtime," but no test function in this file calls t.Skip. If tokenizer.Init fails in a sandbox lacking the dictionary path, every test exercising tokenizeChunks will simply fail with a real error, not skip — the comment misrepresents actual behavior and will mislead whoever investigates a CI failure here.

📝 Fix the comment (or add real skip logic)
-// If Init fails (e.g., dict path missing in some CI sandboxes),
-// we log the failure but still run the tests — the affected tests
-// are skipped via `t.Skip` at runtime.
+// If Init fails (e.g., dict path missing in some CI sandboxes),
+// we log the failure but still run the tests. Tests that exercise
+// tokenizeChunks will fail (not skip) when the pool isn't
+// initialized; the CI environment is expected to provide
+// RAGFLOW_DICT_PATH or the default dictionary location.
🤖 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/ingestion/component/tokenizer_test.go` around lines 40 - 59, The
TestMain comment in tokenizer_test.go claims failing tokenizer initialization
will cause affected tests to be skipped via t.Skip, but no test actually does
that. Either update the comment to describe the real behavior after
tokenizer.Init fails, or add explicit skip logic in the tokenize-dependent tests
so they call t.Skip when initialization did not succeed. Use TestMain,
tokenizer.Init, and the tests covering tokenizeChunks to keep the intent and
behavior aligned.

Comment thread internal/dao/ingestion.go Resolved
Comment thread internal/parser/parser/html_parser.go Resolved
@yuzhichang yuzhichang added the ci Continue Integration label Jul 5, 2026

@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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
internal/cli/user_command.go (1)

3765-3823: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

explain output is discarded — result.Message gets overwritten unconditionally.

When explain is true, result.Message = explanation (line 3800) is set, but the unconditional result.Message = fmt.Sprintf("Success to chunk %s", filename) at line 3821 always runs afterward and clobbers it. The explain feature never actually surfaces its output to the caller.

🐛 Proposed fix
 	result.Duration = time.Since(start).Seconds()
 	result.Code = 0
-	result.Message = fmt.Sprintf("Success to chunk %s", filename)
+	if !explain {
+		result.Message = fmt.Sprintf("Success to chunk %s", filename)
+	}
 	return &result, nil
🤖 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/cli/user_command.go` around lines 3765 - 3823, In DevChunkCommand,
the explain path sets result.Message from explainChunkOptions but that value is
always overwritten by the final success message before returning. Update the
control flow so the success message is only assigned for the normal chunking
path, and preserve the explanation text when cmd.Params["explain"] is true; use
the DevChunkCommand, explainChunkOptions, and result.Message assignment points
to locate the fix.
internal/parser/chunk/postprocess.go (2)

41-63: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Type assertion always fails for int inputs — MergeTargetSize/FilterMinLength from ChunkOptions are silently ignored.

execute.go builds postCfg["merge"]["target_size"] and postCfg["filter"]["min_length"] from opts.MergeTargetSize/opts.FilterMinLength, which are Go int values. Here, both are only asserted as .(float64) (a pattern that only holds for JSON-decoded numbers). Since the concrete type is int, both assertions fail every time:

  • op.merge.TargetSize always falls back to the hardcoded 500, ignoring the caller's MergeTargetSize.
  • op.filter.MinLength always stays 0 (zero value), which — per filterChunks's "when MinLength > 0" semantics — effectively disables the length filter regardless of FilterMinLength.

This silently breaks both postprocessing knobs for every production caller going through chunk.Run.

🐛 Proposed fix
 	if m, ok := config["merge"].(map[string]interface{}); ok {
 		op.merge = &mergeConfig{}
-		if ts, ok := m["target_size"].(float64); ok {
-			op.merge.TargetSize = int(ts)
-		} else {
-			op.merge.TargetSize = 500
-		}
+		switch ts := m["target_size"].(type) {
+		case float64:
+			op.merge.TargetSize = int(ts)
+		case int:
+			op.merge.TargetSize = ts
+		default:
+			op.merge.TargetSize = 500
+		}
 	}
 
 	// Filter
 	if f, ok := config["filter"].(map[string]interface{}); ok {
 		op.filter = &filterConfig{}
-		if v, ok := f["min_length"].(float64); ok {
-			op.filter.MinLength = int(v)
-		}
+		switch v := f["min_length"].(type) {
+		case float64:
+			op.filter.MinLength = int(v)
+		case int:
+			op.filter.MinLength = v
+		}
 	}
🤖 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/parser/chunk/postprocess.go` around lines 41 - 63, The
NewPostprocessOperator config parsing only accepts float64 values, so the int
values produced by execute.go for merge.target_size and filter.min_length are
ignored. Update NewPostprocessOperator to handle both int and float64 (or
another numeric type conversion path) when reading mergeConfig.TargetSize and
filterConfig.MinLength, and keep the existing defaults only when the keys are
truly absent. Make sure the fix preserves the current PostprocessOperator,
mergeConfig, and filterConfig flow so ChunkOptions values are applied correctly
through chunk.Run.

86-90: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Size uses byte length instead of rune count.

chunks[i].Size = len(chunks[i].GetContent()) computes byte length, but the codebase's documented semantics are rune-based (options.go: "FilterMinLength > 0 drops chunks shorter than that (rune count)"), and helpers.go even defines a RuneCount helper apparently for this purpose that isn't used here. For CJK content this over-reports Size relative to character count, which can skew any downstream length-based decisions using this field.

🔧 Proposed fix
 	// Re-index
 	for i := range chunks {
 		chunks[i].Index = i
-		chunks[i].Size = len(chunks[i].GetContent())
+		chunks[i].Size = RuneCount(chunks[i].GetContent())
 	}
🤖 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/parser/chunk/postprocess.go` around lines 86 - 90, The Chunk
postprocessing re-index step is setting Chunk.Size from byte length instead of
rune count. Update the size assignment in the re-index loop to use the existing
rune-count semantics, preferably by calling the RuneCount helper from helpers.go
on chunks[i].GetContent(). Keep Index assignment unchanged and ensure Size now
reflects characters consistently with the documented FilterMinLength behavior.
🤖 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/parser/chunk/execute.go`:
- Around line 56-67: The postprocess config built in execute should not store
numeric values as native int because NewPostprocessOperator expects float64 when
reading the merge.target_size and filter.min_length settings. Update the postCfg
construction in execute to cast opts.MergeTargetSize and opts.FilterMinLength to
float64 before inserting them, so the downstream type assertions in
postprocess.go succeed.

In `@internal/parser/chunk/options.go`:
- Around line 51-57: The defaulting logic in ChunkOptions.validate is
ineffective because it uses a value receiver, so setting SplitStrategy there
only changes a local copy. Remove the dead assignment from validate if
SplitOperator.Execute already applies the default, or change validate to a
pointer receiver if the default should be applied through ChunkOptions itself.
Use ChunkOptions.validate and SplitOperator.Execute to keep the behavior in one
place and avoid misleading duplicate logic.

In `@internal/parser/chunk/split.go`:
- Around line 77-93: The sentence splitting logic in
SplitOperator.splitSentences is missing the ASCII sentence terminators, so
English text is not being split as expected. Update the sentenceBoundaries set
to include the ASCII boundaries used by the parser, alongside the existing CJK
punctuation and newline, and keep the existing punctuation-dropping behavior in
the splitSentences flow so chunk.Run with SplitStrategy "sentence" handles
non-CJK input correctly.

---

Outside diff comments:
In `@internal/cli/user_command.go`:
- Around line 3765-3823: In DevChunkCommand, the explain path sets
result.Message from explainChunkOptions but that value is always overwritten by
the final success message before returning. Update the control flow so the
success message is only assigned for the normal chunking path, and preserve the
explanation text when cmd.Params["explain"] is true; use the DevChunkCommand,
explainChunkOptions, and result.Message assignment points to locate the fix.

In `@internal/parser/chunk/postprocess.go`:
- Around line 41-63: The NewPostprocessOperator config parsing only accepts
float64 values, so the int values produced by execute.go for merge.target_size
and filter.min_length are ignored. Update NewPostprocessOperator to handle both
int and float64 (or another numeric type conversion path) when reading
mergeConfig.TargetSize and filterConfig.MinLength, and keep the existing
defaults only when the keys are truly absent. Make sure the fix preserves the
current PostprocessOperator, mergeConfig, and filterConfig flow so ChunkOptions
values are applied correctly through chunk.Run.
- Around line 86-90: The Chunk postprocessing re-index step is setting
Chunk.Size from byte length instead of rune count. Update the size assignment in
the re-index loop to use the existing rune-count semantics, preferably by
calling the RuneCount helper from helpers.go on chunks[i].GetContent(). Keep
Index assignment unchanged and ensure Size now reflects characters consistently
with the documented FilterMinLength behavior.
🪄 Autofix (Beta)

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

Run ID: 6bb254f3-e2b0-46d7-a703-6b96132eb136

📥 Commits

Reviewing files that changed from the base of the PR and between c6d00af and 0fd7df5.

📒 Files selected for processing (16)
  • agent/component/pipeline_chunker.py
  • internal/agent/component/pipeline_chunker.go
  • internal/agent/component/pipeline_chunker_test.go
  • internal/agent/runtime/registry.go
  • internal/agent/runtime/registry_test.go
  • internal/cli/dev_parser.go
  • internal/cli/user_command.go
  • internal/handler/components_testpkg/components_handler_test.go
  • internal/ingestion/component/chunker/token.go
  • internal/parser/chunk/execute.go
  • internal/parser/chunk/helpers.go
  • internal/parser/chunk/options.go
  • internal/parser/chunk/postprocess.go
  • internal/parser/chunk/split.go
  • internal/service/components_service_test.go
  • test/unit_test/agent/test_pipeline_chunker.py
💤 Files with no reviewable changes (3)
  • agent/component/pipeline_chunker.py
  • internal/agent/component/pipeline_chunker.go
  • internal/agent/component/pipeline_chunker_test.go
✅ Files skipped from review due to trivial changes (1)
  • internal/cli/dev_parser.go
🚧 Files skipped from review as they are similar to previous changes (4)
  • internal/agent/runtime/registry.go
  • internal/agent/runtime/registry_test.go
  • internal/handler/components_testpkg/components_handler_test.go
  • internal/ingestion/component/chunker/token.go

Comment thread internal/parser/chunk/execute.go Resolved
Comment thread internal/parser/chunk/options.go Resolved
Comment thread internal/parser/chunk/split.go Resolved
@yuzhichang

Copy link
Copy Markdown
Member Author

CodeRabbit follow-up, item by item:

  1. LatestLogByTaskID nil contract: fixed in 486311a2c, then pushed in 7959b2098. DAO now propagates not-found, and admin listing has a nil/checkpoint guard. Thread replied inline and resolved.
  2. HTML sibling leakage in walkHTMLLeaf: fixed in 486311a2c, then pushed in 7959b2098. Added text-level assertions to the HTML parser test. Thread replied inline and resolved.
  3. build.sh --test argv forwarding: fixed in 402713346. This was the root cause of the current CI failures (go test . at repo root -> no Go files).
  4. internal/ingestion/ingestion_service.go commented-out dead code: removed in 402713346.
  5. executeTask completion path Nack-after-success risk: fixed in 402713346. UpdateStatus(COMPLETED) failure now still Acks to avoid replaying an already-finished pipeline.
  6. GroupTitleChunker empty flush on non-text records: fixed in 402713346.
  7. TokenChunker cancellation hidden as partial success: fixed in 402713346. Aggregated ctx.Err() is now surfaced via _ERROR instead of silently returning partial chunks.
  8. Migration-history doc comments in chunker/register.go, group.go, title.go: cleaned in 402713346.
  9. FileComponent.bucket dead scaffolding: removed in 402713346.
  10. tokenizer_test.go comment claiming t.Skip: corrected in 402713346.
  11. router.Setup unconditional componentsHandler: guarded in 402713346.
  12. extractor/no_cgo.go wrong build-tag doc comment (cgo vs cgo_thincner): fixed in 7959b2098.
  13. Tokenizer title-weight dead no-op branch: removed in 7959b2098.
  14. internal/parser/chunk/pipeline.go value-receiver validate() comment: obsolete after the aggressive refactor in 0fd7df531 because internal/parser/chunk/pipeline.go was deleted and replaced by execute.go / options.go.
  15. PipelineChunker-related comments/tests: obsolete after the aggressive refactor in 0fd7df531 because the Go/Python PipelineChunker surfaces were deleted.
  16. ComponentsService.List filtering out legacy metadata-only agent components: not changed in this slice. Doing so would currently hide the agent catalog entirely until metadata backfill lands, which is a larger API-behavior change than the CI/review-fix scope here.
  17. pdf_parser_common.go:firstPageNumber shape-mismatch handling: not changed in this slice. That needs a wider typed/error-propagation change across callers, and it is unrelated to the current CI breakage.

Validation run after the fixes:

  • bash build.sh --test -- ./internal/admin/...
  • bash build.sh --test -- ./internal/router/...
  • bash build.sh --test -- ./internal/ingestion/...
  • bash build.sh --test -- ./internal/ingestion/component/...
  • bash build.sh --test -- ./internal/ingestion/compilation/extractor/...

The failing CI jobs should rerun cleanly once GitHub picks up 7959b2098.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
internal/admin/service.go (2)

117-121: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Remove commented-out code.

Dead code for document fetching remains commented out inside the loop. As per coding guidelines, **/*.go files should "Remove commented-out Go code instead of leaving recovery notes in place."

🧹 Proposed fix
-		//var document *entity.Document
-		//document, err = s.documentDAO.GetByID(task.DocumentID)
-		//if err != nil {
-		//	return nil, err
-		//}
-
🤖 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/admin/service.go` around lines 117 - 121, Remove the commented-out
document lookup block from the task loop in service.go, since it is dead Go code
and should not remain as a recovery note. Clean up the unused `document` and
`s.documentDAO.GetByID` lines entirely, keeping the loop logic in `service.go`
focused on the active code path only.

Source: Coding guidelines


125-146: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Silently swallowed error from LatestLogByTaskID.

If the DAO call at Line 125 returns a non-nil err, the outer check err == nil at Line 133 simply skips the step logic and appends the task without step — the error itself is never logged or surfaced. This can mask real DB/query failures as "no step data".

🩹 Suggested fix (log the error at minimum)
 		latestLog, err = s.ingestionTaskLogDao.LatestLogByTaskID(task.ID)
+		if err != nil {
+			log.Warnf("failed to fetch latest ingestion task log for task %s: %v", task.ID, err)
+		}
 		showTask = map[string]interface{}{
🤖 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/admin/service.go` around lines 125 - 146, The LatestLogByTaskID
error is being swallowed in the task listing flow, so failures look like missing
step data instead of DAO/query issues. Update the logic in the service method
that builds showTask to explicitly handle err from
s.ingestionTaskLogDao.LatestLogByTaskID by logging it (at minimum) before
continuing, and keep the existing step extraction only for the nil-error path;
use the LatestLogByTaskID call and the showTask assembly block to locate the
fix.
🧹 Nitpick comments (1)
internal/admin/service.go (1)

126-146: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicated map literal for showTask.

The five base fields are repeated verbatim in both the initial map and the step-augmented map. Building the map once and conditionally adding "step" avoids the duplication.

♻️ Proposed refactor
 		showTask = map[string]interface{}{
 			"id":          task.ID,
 			"user_id":     task.UserID,
 			"user":        user.Email,
 			"document_id": task.DocumentID,
 			"status":      task.Status,
 		}
 		if err == nil && latestLog != nil && latestLog.Checkpoint != nil {
 			step, ok := latestLog.Checkpoint["current_step"].(float64)
-			if !ok {
-				showTasks = append(showTasks, showTask)
-				continue
-			}
-			showTask = map[string]interface{}{
-				"id":          task.ID,
-				"user_id":     task.UserID,
-				"user":        user.Email,
-				"document_id": task.DocumentID,
-				"status":      task.Status,
-				"step":        int(step),
-			}
+			if ok {
+				showTask["step"] = int(step)
+			}
 		}
🤖 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/admin/service.go` around lines 126 - 146, The showTask map literal
in the task listing flow is duplicated when adding the optional step field, so
refactor the logic to build the base map once and then conditionally add the
"step" entry if latestLog.Checkpoint["current_step"] is present and valid.
Update the code around showTask, latestLog.Checkpoint, and the current_step
parsing so the common id/user_id/user/document_id/status fields are only defined
once, then append the task to showTasks after the conditional update.
🤖 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.

Outside diff comments:
In `@internal/admin/service.go`:
- Around line 117-121: Remove the commented-out document lookup block from the
task loop in service.go, since it is dead Go code and should not remain as a
recovery note. Clean up the unused `document` and `s.documentDAO.GetByID` lines
entirely, keeping the loop logic in `service.go` focused on the active code path
only.
- Around line 125-146: The LatestLogByTaskID error is being swallowed in the
task listing flow, so failures look like missing step data instead of DAO/query
issues. Update the logic in the service method that builds showTask to
explicitly handle err from s.ingestionTaskLogDao.LatestLogByTaskID by logging it
(at minimum) before continuing, and keep the existing step extraction only for
the nil-error path; use the LatestLogByTaskID call and the showTask assembly
block to locate the fix.

---

Nitpick comments:
In `@internal/admin/service.go`:
- Around line 126-146: The showTask map literal in the task listing flow is
duplicated when adding the optional step field, so refactor the logic to build
the base map once and then conditionally add the "step" entry if
latestLog.Checkpoint["current_step"] is present and valid. Update the code
around showTask, latestLog.Checkpoint, and the current_step parsing so the
common id/user_id/user/document_id/status fields are only defined once, then
append the task to showTasks after the conditional update.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4305fd61-0343-4ce6-b09c-a01d66e90d8f

📥 Commits

Reviewing files that changed from the base of the PR and between 0fd7df5 and 7959b20.

📒 Files selected for processing (15)
  • build.sh
  • internal/admin/service.go
  • internal/dao/ingestion.go
  • internal/ingestion/compilation/extractor/no_cgo.go
  • internal/ingestion/component/chunker/group.go
  • internal/ingestion/component/chunker/register.go
  • internal/ingestion/component/chunker/title.go
  • internal/ingestion/component/chunker/token.go
  • internal/ingestion/component/file.go
  • internal/ingestion/component/tokenizer.go
  • internal/ingestion/component/tokenizer_test.go
  • internal/ingestion/ingestion_service.go
  • internal/parser/parser/html_parser.go
  • internal/parser/parser/parse_with_result_test.go
  • internal/router/router.go
💤 Files with no reviewable changes (2)
  • internal/dao/ingestion.go
  • internal/ingestion/component/tokenizer.go
🚧 Files skipped from review as they are similar to previous changes (9)
  • internal/ingestion/component/chunker/register.go
  • build.sh
  • internal/ingestion/component/file.go
  • internal/ingestion/compilation/extractor/no_cgo.go
  • internal/ingestion/component/chunker/group.go
  • internal/ingestion/ingestion_service.go
  • internal/ingestion/component/chunker/title.go
  • internal/ingestion/component/chunker/token.go
  • internal/ingestion/component/tokenizer_test.go

@codecov

codecov Bot commented Jul 5, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (0fcfb38) to head (20763a5).

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #16647      +/-   ##
==========================================
- Coverage   94.56%   93.16%   -1.40%     
==========================================
  Files          10       10              
  Lines         717      717              
  Branches      118      118              
==========================================
- Hits          678      668      -10     
- Misses         25       29       +4     
- Partials       14       20       +6     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@yuzhichang
yuzhichang merged commit 014c3f6 into infiniflow:main Jul 5, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant