Skip to content

Refactor: task executor - #2

Closed
xugangqiang wants to merge 2 commits into
mainfrom
te-refactor
Closed

xugangqiang wants to merge 2 commits into
mainfrom
te-refactor

Conversation

@xugangqiang

@xugangqiang xugangqiang commented May 18, 2026 •

Copy link
Copy Markdown
Owner

What problem does this PR solve?

  1. Break huge function into smaller pieces
  2. Add unit test for the smaller pieces function
  3. Layer-ed design
    a. infra layer - task_context.py, recording_context.py, write_operation_interceptor.py, ...
    b. service layer - *_service.py
    c. business layer - task_handler.py

Type of change

  • Bug Fix (non-breaking change which fixes an issue)
  • Refactoring
  • Performance Improvement

@xugangqiang xugangqiang changed the title Te refactor Refactor: task executor May 20, 2026
@xugangqiang
xugangqiang force-pushed the te-refactor branch 7 times, most recently from 7fd44f3 to d7e3085 Compare May 25, 2026 12:28
xugangqiang pushed a commit that referenced this pull request May 25, 2026
…infiniflow#14849)

## What problem does this PR solve?

Closes infiniflow#12582.

When a Retrieval component sits inside an Iteration with a **manual**
metadata filter that references the iteration variable (e.g.
`{IterationItem:abc@item}`), every iteration reuses the value resolved
on the **first** pass.

Root cause: [`_resolve_manual_filter` in
`agent/tools/retrieval.py`](https://github.com/infiniflow/ragflow/blob/main/agent/tools/retrieval.py#L144-L171)
mutated `flt["value"]` in place. The `filters` list passed in is the
live `self._param.meta_data_filter["manual"]` (see
[`apply_meta_data_filter` in
`common/metadata_utils.py:257-261`](https://github.com/infiniflow/ragflow/blob/main/common/metadata_utils.py#L257-L261)),
so after the first iteration the param dict permanently held the
resolved string instead of the original variable reference.

```text
iter #1: flt["value"] = "{IterationItem:abc@item}"  →  resolved to "AI"
         after mutation: flt["value"] = "AI"        ← written back into _param

iter #2: flt["value"] = "AI"                         ← no {…} matches
         retrieval keeps filtering by "AI" forever
```

This PR returns a shallow copy with the resolved value instead, leaving
the original filter (and its variable reference) intact for the next
iteration.

## Type of change

- [x] Bug fix (non-breaking change which fixes an issue)

## Test plan

- [ ] Build an agent: `Agent (structured output → list of areas) →
Iteration → Retrieval (manual filter: Area = {IterationItem/Item}) →
Message`. Run with a multi-area query and confirm each iteration's
Retrieval result matches its own item, not the first item.
- [ ] Regression: Retrieval with a manual metadata filter outside an
Iteration still resolves the variable correctly on each request.
- [ ] Regression: Retrieval with no metadata filter and with `auto` /
`semi_auto` filters behave unchanged.
2. add execution mode support - dry run & compare, original or refactor-ed version
3. unit test
@xugangqiang
xugangqiang marked this pull request as draft May 26, 2026 09:32
xugangqiang added a commit that referenced this pull request Aug 17, 2026
In the Go PDF pipeline, processTablesWithReplacements marked every box
overlapping a DLA table region for removal, then re-inserted an HTML box
only when buildTableHTMLs produced one. When DLA over-labeled a text box
as a table but TSR produced no cells (or a degenerate table whose
ConstructTable returned ""), the box was removed with nothing re-inserted
-- silently dropping the original text (~20% of characters on documents
where DLA over-labels prose as tables).

Flip the logic: a box is removed only when it is actually replaced by a
table HTML box. A DLA-tagged region that yields no HTML keeps its text,
matching Python, which keeps non-table regions as text.

This also fixes a duplication bug (CodeRabbit #2): when one box is covered
by both an empty-table and a real-table replacement, the old
mark-all-then-unmark-empty approach left the box in place while still
inserting the real table's HTML, duplicating the content. Marking per
replacement only when HTML is present removes the box exactly once.

Add three unit tests:
- KeepsTextWhenNoCells: DLA over-label with no cells keeps the text.
- NoDupWhenCoveredByEmptyAndRealTable: mixed coverage removes the box and
  inserts exactly one HTML (red under the old logic, green now).
- KeepsTextWhenCellsButEmptyHTML: a degenerate table keeps the text.

table + layout package tests stay green; real tables are unchanged.
xugangqiang added a commit that referenced this pull request Aug 17, 2026
In the Go PDF pipeline, processTablesWithReplacements marked every box
overlapping a DLA table region for removal, then re-inserted an HTML box
only when buildTableHTMLs produced one. When DLA over-labeled a text box
as a table but TSR produced no cells (or a degenerate table whose
ConstructTable returned ""), the box was removed with nothing re-inserted
-- silently dropping the original text (~20% of characters on documents
where DLA over-labels prose as tables).

Flip the logic: a box is removed only when it is actually replaced by a
table HTML box. A DLA-tagged region that yields no HTML keeps its text,
matching Python, which keeps non-table regions as text.

This also fixes a duplication bug (CodeRabbit #2): when one box is covered
by both an empty-table and a real-table replacement, the old
mark-all-then-unmark-empty approach left the box in place while still
inserting the real table's HTML, duplicating the content. Marking per
replacement only when HTML is present removes the box exactly once.

Add three unit tests:
- KeepsTextWhenNoCells: DLA over-label with no cells keeps the text.
- NoDupWhenCoveredByEmptyAndRealTable: mixed coverage removes the box and
  inserts exactly one HTML (red under the old logic, green now).
- KeepsTextWhenCellsButEmptyHTML: a degenerate table keeps the text.

table + layout package tests stay green; real tables are unchanged.
xugangqiang added a commit that referenced this pull request Aug 17, 2026
In the Go PDF pipeline, processTablesWithReplacements marked every box
overlapping a DLA table region for removal, then re-inserted an HTML box
only when buildTableHTMLs produced one. When DLA over-labeled a text box
as a table but TSR produced no cells (or a degenerate table whose
ConstructTable returned ""), the box was removed with nothing re-inserted
-- silently dropping the original text (~20% of characters on documents
where DLA over-labels prose as tables).

Flip the logic: a box is removed only when it is actually replaced by a
table HTML box. A DLA-tagged region that yields no HTML keeps its text,
matching Python, which keeps non-table regions as text.

This also fixes a duplication bug (CodeRabbit #2): when one box is covered
by both an empty-table and a real-table replacement, the old
mark-all-then-unmark-empty approach left the box in place while still
inserting the real table's HTML, duplicating the content. Marking per
replacement only when HTML is present removes the box exactly once.

Add three unit tests:
- KeepsTextWhenNoCells: DLA over-label with no cells keeps the text.
- NoDupWhenCoveredByEmptyAndRealTable: mixed coverage removes the box and
  inserts exactly one HTML (red under the old logic, green now).
- KeepsTextWhenCellsButEmptyHTML: a degenerate table keeps the text.

Also add a manual (cgo && manual) real-PDF over-label test
(TestRealPDFOverlabelKeepsText): it parses the real PDF Doc1.pdf, simulates
a DLA over-label on REAL extracted text (a box classified LayoutTypeTable
paired with a degenerate table that has no cells), and asserts the fix keeps
that text. It fails under the pre-fix logic (text silently dropped), proving
the retention win on real PDF content. Runs only locally (Doc1.pdf is
gitignored, not in CI).

table + layout package tests stay green; real tables are unchanged.
xugangqiang added a commit that referenced this pull request Sep 1, 2026
The token chunker stored each new (overlap) chunk as a single fused
merged_item whose text is the full overlap prefix + current unit, and
whose PDF positions bundle the entire previous chunk's tail boxes plus
the current unit's. On the next overlap boundary the whole fused item
was selected, dragging the previous chunk's HEAD coordinates forward
again, so coordinates accumulated across chained overlaps (infiniflow#18148
follow-up; CodeRabbit review #2 on PR infiniflow#18227).

Keep the previous chunk's tail as SEPARATE merged_items entries, each
truncated to the overlap portion, so the next overlap selects only the
true tail and the window converges to a sliding window instead of
accumulating head coordinates. The flattened tail boxes are still
carried into the output chunk so the overlap region stays highlighted,
and the hard-cap trim (trimRunes) is preserved.

Adds Go unit/integration tests covering the truncation and the no-head
accumulation invariant (TestOverlapTailItemsTruncatesToOverlapPortion
and TestMergeByTokenSizeFromJSON_ChainedOverlapNoHeadAccumulation).
xugangqiang added a commit that referenced this pull request Sep 2, 2026
The token chunker stored each new (overlap) chunk as a single fused
merged_item whose text is the full overlap prefix + current unit, and
whose PDF positions bundle the entire previous chunk's tail boxes plus
the current unit's. On the next overlap boundary the whole fused item
was selected, dragging the previous chunk's HEAD coordinates forward
again, so coordinates accumulated across chained overlaps (infiniflow#18148
follow-up; CodeRabbit review #2 on PR infiniflow#18227).

Keep the previous chunk's tail as SEPARATE merged_items entries, each
truncated to the overlap portion, so the next overlap selects only the
true tail and the window converges to a sliding window instead of
accumulating head coordinates. The flattened tail boxes are still
carried into the output chunk so the overlap region stays highlighted,
and the hard-cap trim (trimRunes) is preserved.

Adds Go unit/integration tests covering the truncation and the no-head
accumulation invariant (TestOverlapTailItemsTruncatesToOverlapPortion
and TestMergeByTokenSizeFromJSON_ChainedOverlapNoHeadAccumulation).
xugangqiang added a commit that referenced this pull request Sep 8, 2026
Addresses the architecture review (F1-F3) and CodeRabbit findings on the
per-chunk cache introduced in feat/ingestion-checkpoint-chunk-cache.

Cache key contract (F1/F2):
- chunkcache.Key now guards an empty modelID symmetrically with an empty
  chunkID, so a caller that forgot to resolve the model cannot collapse
  every model onto one bucket. The doc spells out the modelID semantics:
  embd_id for the "emb" kind, and the chat model id (or resolved tenant
  default) for extractor:*/meta/tagger kinds.
- extractor.go adds extractorCacheModelID, which resolves an empty llmID to
  the real tenant-default chat model identity ("driver/modelName") instead
  of keying on the empty override. This keeps the default-model path cached
  while still scoping entries per actual model.

Key coverage of model inputs (F3 / CodeRabbit #2):
- tagger key now folds in the chunk text from getChunkText (includes
  important_kwd), so a keyword change busts stale tags.
- embedding key now includes the truncated embedded text (post field
  selection + truncation), so a Fields/model change forces a fresh embed.
- Added regression tests pinning the model dimension into the key for the
  extractor / meta / tagger kinds (TestKey_EmptyModelIDYieldsNoKey,
  TestEmbedChunks_CacheKeyScopedByFields,
  TestTaggerCacheKey_ScopedByChunkID_ModelAndText).

Manifest TTL rollback (CodeRabbit #1):
- chunkcache.Set now deletes the manifest key if Expire fails, instead of
  leaving a TTL-less set that leaks one key per abandoned task.

Purge ordering (CodeRabbit #3):
- Moved chunkcache.PurgeTask to after all failure-capable persist steps
  (index write, compiled-product reconcile, Wiki active-state) succeed, so a
  retry still finds the cache intact and does not re-pay every
  embedding/LLM call — which is the cost the cache exists to absorb.

All three packages (chunkcache, component, task) pass `build.sh --test`.
xugangqiang added a commit that referenced this pull request Oct 30, 2026
- prefer worker-claim time (doc.ProcessBeginAt) for wait duration (#2)
- omit zero-value times from the JSON log line instead of emitting
  0001-01-01, and guard the logger with atomic.Pointer for a safe swap (#8, #7)
- populate DurationMS from ParseDurationS so consumers need not recompute (#11)
- drop the unused IngestLog.Code field (#Nit)
- thread the failure reason through MarkFailed into the emitted event's
  ErrorInfo, so failed runs are no longer logged with an empty reason (#4)
- persist process_end_at idempotently (WHERE process_end_at IS NULL) so
  overlapping terminal events cannot rewrite the recorded completion
  instant (#12)

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

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant