Skip to content

Add Go service/handler tests for API contract parity - #16905

Merged
wangq8 merged 24 commits into
infiniflow:mainfrom
euvre:go-contract-test-parity
Jul 20, 2026
Merged

wangq8 merged 24 commits into
infiniflow:mainfrom
euvre:go-contract-test-parity

Conversation

@euvre

@euvre euvre commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Summary

This PR supplements Go tests and aligns several Go validation/response contracts with the established Python API contract (the category-2 GO_ONLY_SKIPS entries in test/testcases/restful_api/conftest.py).

  • Align chat/dataset/search error messages and authorization codes (102 CodeDataError / 109 CodeAuthenticationError) with the Python contract (e.g. `name` can not be empty., No authorization.).
  • Make KnowledgebaseDAO.GetByName case-insensitive to match MySQL's default collation, so duplicate-name detection is consistent across case.
  • Add Go service- and handler-level tests for:
    • chat: name validation, case-insensitive duplicate detection, tenant_id rejection, prompt-config defaults;
    • search: empty-name rejection (102) and unauthorized update (109), create/update round-trip;
    • dataset: embedding-model format validation, field preservation on partial update, parser_config merge;
    • chat-session: create (name validation, truncation, ownership) and delete (by IDs, delete_all, invalid ID) contracts.
  • Remove the now-satisfied entries from the category-2 GO_ONLY_SKIPS list.

- Align chat/dataset/search validation messages and auth codes (102/109)
  with the established Python API contract.
- Fix GetByName to be case-insensitive (MySQL collation parity) so
  duplicate-name detection matches across case.
- Add service- and handler-level Go tests covering: chat name validation,
  case-insensitive duplicate detection, tenant_id rejection, prompt-config
  defaults, search empty-name (102) and update-unauthorized (109), and
  chat-session create/delete contracts.
- Add dataset tests for embedding-model format, field preservation, and
  parser_config merge.
- Remove now-satisfied entries from the category-2 GO_ONLY_SKIPS list in
  test/testcases/restful_api/conftest.py.
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 14, 2026
@euvre euvre added the ci Continue Integration label Jul 14, 2026
@coderabbitai

coderabbitai Bot commented Jul 14, 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
📝 Walkthrough

Walkthrough

The PR aligns chat, search, dataset, and document validation and authorization contracts, adds dataset uniqueness and filtering behavior, updates ingestion and metadata payload handling, expands Go contract tests, and includes formatting-only changes across Python, tooling, SQL, and frontend files.

Changes

Chat contracts

Layer / File(s) Summary
Chat authorization, validation, and defaults
internal/handler/chat.go, internal/service/chat.go, internal/entity/chat.go, internal/dao/chat.go
Authorization responses, validation messages, defaults, duplicate-name handling, and explicit zero-value persistence are updated.
Chat behavior coverage
internal/handler/chat_test.go, internal/service/chat_list_test.go, internal/service/chat_rest_update_test.go, internal/service/chat_session_contract_test.go
Tests cover ownership denial, listing, pagination, validation, duplication, prompt defaults, and sessions.

Dataset lookup and update flow

Layer / File(s) Summary
Dataset filtering and uniqueness
internal/dao/kb.go, internal/dao/migration.go, internal/service/dataset.go
Dataset ID/name filters and active case-insensitive name uniqueness are added, with duplicate database errors mapped to name conflicts.
Dataset request and validation behavior
internal/handler/dataset.go, internal/service/dataset.go, internal/entity/dataset.go
Parser configuration presence, knowledge-graph parsing, embedding identifier validation, and partial-update behavior are updated.
Dataset contract coverage
internal/service/dataset_create_test.go, internal/service/dataset_update_test.go
Tests cover names, duplicates, embeddings, partial updates, parser configuration, and deletion authorization.

Search access and response contracts

Layer / File(s) Summary
Search validation and access checks
internal/dao/search.go, internal/service/search.go, internal/handler/search.go
Search name validation, count-based access checks, and authentication error mappings are aligned.
Search coverage
internal/handler/search_handler_test.go, internal/service/search_test.go
Tests cover empty names, unauthorized IDs, persisted updates, and configuration merging.

Document listing, ingestion, and metadata

Layer / File(s) Summary
Document list and ingestion contracts
internal/dao/document.go, internal/handler/document.go, internal/router/router.go, internal/service/document.go
Document filtering, ingestion request shape, stop routing, ownership responses, and progress validation are updated.
Metadata payload validation
internal/handler/document.go
Batch metadata payloads now use explicit object/list parsing and JSON shape validation.

Formatting cleanup

Layer / File(s) Summary
Formatting-only updates
api/apps/restful_apis/chat_api.py, deepdoc/parser/*, rag/advanced_rag/*, rag/llm/tool_decorator.py, web/src/hooks/*, docker/init-clickhouse.sql, test/testcases/restful_api/conftest.py, agent/component/begin.py
Formatting, imports, logging, assertions, SQL initialization, and type layout are adjusted without described functional changes.

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

Possibly related PRs

Suggested labels: 🧪 test

Suggested reviewers: jinhai-cn, xugangqiang

Poem

I hop through names, unique and bright,
Guarding chats from wrongs at night.
Datasets parse, searches align,
Documents follow stricter design.
Tests bloom like carrots sweet—
A rabbit’s review is now complete! 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.86% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and matches the main change: adding Go service and handler tests for API contract parity.
Description check ✅ Passed The description includes the required Summary section and clearly explains the PR goals and context with relevant bullets.
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

Caution

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

⚠️ Outside diff range comments (1)
internal/service/dataset.go (1)

2774-2788: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Validate ext.embd_id the same way as EmbeddingModel.
The ext branch still skips validateDatasetEmbeddingModel for "", so ext: {"embd_id": ""} falls through to the existing value instead of raising the same error the top-level field path does. Make this check unconditional and add an ext.embd_id == "" test.

🤖 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/dataset.go` around lines 2774 - 2788, In the ext.embd_id
handling within the dataset update flow, call validateDatasetEmbeddingModel
unconditionally after trimming the value, including when it is empty, so it
matches the top-level EmbeddingModel behavior and rejects ext: {"embd_id": ""}
instead of retaining the existing value. Add a test covering the empty
ext.embd_id case.
🧹 Nitpick comments (3)
internal/service/dataset.go (1)

3583-3608: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Redundant condition in validateDatasetEmbeddingModel.

Given the preceding strings.Contains(embeddingModel, "@") guard, strings.SplitN(embeddingModel, "@", 2) is guaranteed to return exactly 2 elements, and parts[0] == ""/parts[1] == "" is already subsumed by the very next strings.TrimSpace(parts[0]) == "" || strings.TrimSpace(parts[1]) == "" check. The first if len(parts) != 2 || parts[0] == "" || parts[1] == "" branch is unreachable/duplicate logic.

♻️ Proposed cleanup
 	parts := strings.SplitN(embeddingModel, "@", 2)
-	if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
-		return errors.New("Both model_name and provider must be non-empty strings")
-	}
 	if strings.TrimSpace(parts[0]) == "" || strings.TrimSpace(parts[1]) == "" {
 		return errors.New("Both model_name and provider must be non-empty strings")
 	}
As per coding guidelines, "During review, remove deprecated, legacy, compatibility-only, duplicate, stale, or unnecessarily exported code when it is not required by the current implementation."
🤖 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/dataset.go` around lines 3583 - 3608, Remove the redundant
`len(parts) != 2 || parts[0] == "" || parts[1] == ""` condition in
`validateDatasetEmbeddingModel` after `strings.SplitN`; retain the subsequent
TrimSpace validation and its existing error behavior for empty or
whitespace-only model and provider values.

Source: Coding guidelines

internal/service/dataset_create_test.go (1)

74-99: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a case-insensitive duplicate-name test for CreateDataset.

TestDatasetServiceCreateDatasetRejectsDuplicateName only exercises an exact-case match. Since GetByName's case-insensitivity change (kb.go) applies to CreateDataset too, and dataset_update_test.go already has TestDatasetServiceUpdateDatasetRejectsDuplicateNameCaseInsensitive for the update path, add the equivalent case for creation to close the coverage gap for this cohort's stated goal.

🤖 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/dataset_create_test.go` around lines 74 - 99, Extend
TestDatasetServiceCreateDatasetRejectsDuplicateName to use a differently cased
requested name, or add a focused companion test, while retaining the existing
duplicate-name assertions. Verify CreateDataset rejects the case-insensitive
match with common.CodeDataError and an “already exists” error.
internal/dao/kb.go (1)

104-111: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Avoid LOWER(name) here. It prevents the existing name index from being used on this duplicate-name check; keep the comparison on the raw column, or add a matching functional/case-insensitive index if case-insensitive matching is required.

🤖 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/dao/kb.go` around lines 104 - 111, Update KnowledgebaseDAO.GetByName
to avoid applying LOWER() to the name column so the existing name index can be
used, while preserving the tenant_id and valid-status filters. Keep
case-insensitive behavior only if a matching functional or case-insensitive
index is already available; otherwise compare the raw name column.
🤖 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/service/dataset.go`:
- Around line 2484-2495: The check-then-write logic around CreateDataset and the
rename path in UpdateDataset is not concurrency-safe. Add a database unique
constraint or index on tenant_id plus case-insensitive name, then detect its
violation during dataset insertion or rename and return the existing
CodeDataError “Dataset name already exists” response; retain the lookup for
normal validation but rely on the constraint for enforcement.

In `@internal/service/search.go`:
- Around line 568-574: Update the permission check in UpdateSearch to capture
the error returned by Accessible4Deletion instead of discarding it. Return a
wrapped “failed to check deletion permission” error when the DAO check fails,
while preserving the existing “no authorization” response only when accessible
is false without an error.

---

Outside diff comments:
In `@internal/service/dataset.go`:
- Around line 2774-2788: In the ext.embd_id handling within the dataset update
flow, call validateDatasetEmbeddingModel unconditionally after trimming the
value, including when it is empty, so it matches the top-level EmbeddingModel
behavior and rejects ext: {"embd_id": ""} instead of retaining the existing
value. Add a test covering the empty ext.embd_id case.

---

Nitpick comments:
In `@internal/dao/kb.go`:
- Around line 104-111: Update KnowledgebaseDAO.GetByName to avoid applying
LOWER() to the name column so the existing name index can be used, while
preserving the tenant_id and valid-status filters. Keep case-insensitive
behavior only if a matching functional or case-insensitive index is already
available; otherwise compare the raw name column.

In `@internal/service/dataset_create_test.go`:
- Around line 74-99: Extend TestDatasetServiceCreateDatasetRejectsDuplicateName
to use a differently cased requested name, or add a focused companion test,
while retaining the existing duplicate-name assertions. Verify CreateDataset
rejects the case-insensitive match with common.CodeDataError and an “already
exists” error.

In `@internal/service/dataset.go`:
- Around line 3583-3608: Remove the redundant `len(parts) != 2 || parts[0] == ""
|| parts[1] == ""` condition in `validateDatasetEmbeddingModel` after
`strings.SplitN`; retain the subsequent TrimSpace validation and its existing
error behavior for empty or whitespace-only model and provider values.
🪄 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: 340512d8-fc8a-4b34-aa1e-d285982216a5

📥 Commits

Reviewing files that changed from the base of the PR and between eb50622 and d97915e.

📒 Files selected for processing (15)
  • internal/dao/kb.go
  • internal/handler/chat.go
  • internal/handler/chat_test.go
  • internal/handler/search.go
  • internal/handler/search_handler_test.go
  • internal/service/chat.go
  • internal/service/chat_list_test.go
  • internal/service/chat_rest_update_test.go
  • internal/service/chat_session_contract_test.go
  • internal/service/dataset.go
  • internal/service/dataset_create_test.go
  • internal/service/dataset_update_test.go
  • internal/service/search.go
  • internal/service/search_test.go
  • test/testcases/restful_api/conftest.py

Comment thread internal/service/dataset.go Resolved
Comment thread internal/service/search.go Resolved
@codecov

codecov Bot commented Jul 14, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (3da2425) to head (7c510cd).
⚠️ Report is 16 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16905   +/-   ##
=======================================
  Coverage   90.65%   90.65%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          650      650           
  Misses         39       39           
  Partials       28       28           

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

- kb DAO: filter dataset list by id/name so GET /datasets?id= returns the
  requested dataset instead of all tenant datasets
- chat DAO: Create with Select("*") so explicit zero values
  (similarity_threshold, vector_similarity_weight, top_n) persist instead of
  falling back to column defaults; default do_refer to "1"
- dataset update: treat an explicitly provided parser_config ({} or null) as a
  valid no-op instead of "No properties were modified"
- dataset create: return "Dataset name can't be empty." for whitespace-only names
- search create: drop binding:required so an empty name yields code 102
  "name can't be empty" instead of HTTP 500
- conftest: re-skip Python-quirk contracts (Pydantic message wording,
  auto (1) suffix dedup) that Go intentionally does not mirror

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

♻️ Duplicate comments (1)
internal/service/dataset.go (1)

2484-2495: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Enforce dataset-name uniqueness in the database.

The check-then-write logic around CreateDataset (and similarly the rename path in UpdateDataset) remains vulnerable to a time-of-check to time-of-use (TOCTOU) race condition. Concurrent requests can still slip past this existence check and persist duplicate names for the same tenant.

Add a unique index/constraint on (tenant_id, LOWER(name)) (handling active status if soft-deletes apply) in the database, catch its violation during dataset insertion or rename, and map it to the existing CodeDataError "Dataset name already exists" response. Rely on the constraint for enforcement while retaining this lookup for user-friendly validation.

🤖 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/dataset.go` around lines 2484 - 2495, Enforce dataset-name
uniqueness at the database level by adding a unique constraint or index on
tenant_id and LOWER(name), including the active-status predicate if soft deletes
apply. Update CreateDataset and the rename logic in UpdateDataset to detect
violations of this constraint during insert or rename and return CodeDataError
with the existing “Dataset name already exists” response, while retaining the
current GetByName validation for friendly errors.
🤖 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.

Duplicate comments:
In `@internal/service/dataset.go`:
- Around line 2484-2495: Enforce dataset-name uniqueness at the database level
by adding a unique constraint or index on tenant_id and LOWER(name), including
the active-status predicate if soft deletes apply. Update CreateDataset and the
rename logic in UpdateDataset to detect violations of this constraint during
insert or rename and return CodeDataError with the existing “Dataset name
already exists” response, while retaining the current GetByName validation for
friendly errors.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 056e3bd7-428c-4008-b5fb-cffe6bc77140

📥 Commits

Reviewing files that changed from the base of the PR and between d97915e and db27f55.

📒 Files selected for processing (8)
  • internal/dao/chat.go
  • internal/dao/kb.go
  • internal/handler/dataset.go
  • internal/handler/search.go
  • internal/service/chat.go
  • internal/service/dataset.go
  • internal/service/dataset_create_test.go
  • test/testcases/restful_api/conftest.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/service/chat.go
  • test/testcases/restful_api/conftest.py

euvre and others added 5 commits July 14, 2026 19:16
…pecific parser_config default test

- Remove GORM default tags from Chat.SimilarityThreshold/VectorSimilarityWeight/TopN/TopK/DoRefer so an explicitly provided zero value (e.g. similarity_threshold=0) is persisted instead of being overwritten by the column default during Create. The service layer already supplies defaults when a field is omitted.
- Re-skip test_dataset_update_parser_config_defaults_contract under IS_GO_PROXY: its final assertion requires equality with Python's CI-specific DEFAULT_PARSER_CONFIG (embeds a CI tenant llm_id and a richer graphrag/parent_child structure than Go's common.GetParserConfig produces), which is not a meaningful Go contract.
…ission errors

Add a case-insensitive unique constraint on knowledgebase (tenant_id, name) via
a VIRTUAL generated column (name_ci) that is NULL for soft-deleted rows, so
concurrent CreateDataset/UpdateDataset renames cannot slip past the check-then-write
lookup. Map the resulting duplicate-key violation back to the existing "already
exists" domain error.

Fix SearchDAO.Accessible4Deletion to use Count() instead of First(), so "not
authorized" returns (false, nil) instead of (false, ErrRecordNotFound). This
lets UpdateSearch propagate real DB errors (matching DeleteSearch) instead of
silently dropping them as "no authorization".

@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

🤖 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/dao/migration.go`:
- Around line 285-309: Scope the INFORMATION_SCHEMA checks in the migration
around the knowledgebase column and index existence queries to the current
database, using the active database/schema identifier in the WHERE clauses.
Update both the name_ci column check and idx_kb_tenant_name_ci index check so
objects in other databases cannot affect local migration decisions.
- Around line 327-330: The duplicate-detection branch in the migration must fail
instead of reporting success when duplicateCount is greater than zero. Update
the duplicateCount handling to return an error after logging the warning, so the
required unique constraint migration is marked unsuccessful; preserve the
existing successful path when no duplicates are found.
🪄 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: d17c556e-58ee-4e03-9bfc-ad9d1d78fb2d

📥 Commits

Reviewing files that changed from the base of the PR and between cf4b7a5 and 3b94af4.

📒 Files selected for processing (5)
  • internal/dao/kb.go
  • internal/dao/migration.go
  • internal/dao/search.go
  • internal/service/dataset.go
  • internal/service/search.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/dao/kb.go
  • internal/service/dataset.go

Comment thread internal/dao/migration.go Resolved
Comment thread internal/dao/migration.go Resolved
euvre and others added 3 commits July 16, 2026 11:26
…gration

Add TABLE_SCHEMA = DATABASE() to the column and index existence queries in
migrateKnowledgebaseNameUnique so they only inspect the current database, not
every schema on the MySQL server. Without this filter, a column or index with
a matching name in another database could cause the migration to skip creating
the local constraint.
@euvre
euvre marked this pull request as draft July 16, 2026 03:37
@euvre
euvre marked this pull request as ready for review July 16, 2026 03:37
…nstraint

Returning nil after detecting duplicate (tenant_id, name) pairs reported
migration success while leaving the uniqueness invariant absent. Return an
error instead so the server startup surfaces the problem and operators must
resolve the duplicates before the constraint can be enforced.

@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 (1)
api/apps/restful_apis/chat_api.py (1)

1253-1299: 📐 Maintainability & Code Quality | 🟠 Major | ⚖️ Poor tradeoff

Remove compatibility-only legacy branch.

As per coding guidelines, please prefer deletion over compatibility shims and remove compatibility-only surfaces. The legacy streaming fallback should be removed unless explicitly requested to remain.

♻️ Proposed refactor to remove legacy streaming branch
-                if legacy:
-                    # v0.23.0-style streaming: emit accumulated answer text and
-                    # reconstruct raw <think>...</think> markers from the newer
-                    # start_to_think/end_to_think events.
-                    legacy_answer = ""
-                    final_answer = None
-                    async for ans in rag_agent(dia, msg, True, session_id=session_id, **req):
-                        ans = _format_answer(ans)
-                        if ans.get("final"):
-                            final_answer = ans
-                            continue
-                        if ans.get("start_to_think"):
-                            legacy_answer += "<think>"
-                            legacy_chunk = {**ans, "answer": legacy_answer}
-                            legacy_chunk.pop("start_to_think", None)
-                            legacy_chunk.pop("end_to_think", None)
-                            payload = _sanitize_json_floats({"code": 0, "message": "", "data": legacy_chunk})
-                            yield "data:" + json.dumps(payload, ensure_ascii=False) + "\n\n"
-                            continue
-                        if ans.get("end_to_think"):
-                            legacy_answer += "</think>"
-                            legacy_chunk = {**ans, "answer": legacy_answer}
-                            legacy_chunk.pop("start_to_think", None)
-                            legacy_chunk.pop("end_to_think", None)
-                            payload = _sanitize_json_floats({"code": 0, "message": "", "data": legacy_chunk})
-                            yield "data:" + json.dumps(payload, ensure_ascii=False) + "\n\n"
-                            continue
-                        delta = ans.get("answer") or ""
-                        if not delta:
-                            continue
-                        legacy_answer += delta
-                        legacy_chunk = {**ans, "answer": legacy_answer}
-                        legacy_chunk.pop("start_to_think", None)
-                        legacy_chunk.pop("end_to_think", None)
-                        payload = _sanitize_json_floats({"code": 0, "message": "", "data": legacy_chunk})
-                        yield "data:" + json.dumps(payload, ensure_ascii=False) + "\n\n"
-                    if final_answer is not None:
-                        final_chunk = {**final_answer, "answer": final_answer.get("answer") or legacy_answer}
-                        final_chunk.pop("start_to_think", None)
-                        final_chunk.pop("end_to_think", None)
-                        payload = _sanitize_json_floats({"code": 0, "message": "", "data": final_chunk})
-                        yield "data:" + json.dumps(payload, ensure_ascii=False) + "\n\n"
-                else:
-                    async for ans in rag_agent(dia, msg, True, session_id=session_id, **req):
-                        ans = _format_answer(ans)
-                        payload = _sanitize_json_floats({"code": 0, "message": "", "data": ans})
-                        yield "data:" + json.dumps(payload, ensure_ascii=False) + "\n\n"
+                async for ans in rag_agent(dia, msg, True, session_id=session_id, **req):
+                    ans = _format_answer(ans)
+                    payload = _sanitize_json_floats({"code": 0, "message": "", "data": ans})
+                    yield "data:" + json.dumps(payload, ensure_ascii=False) + "\n\n"
🤖 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 `@api/apps/restful_apis/chat_api.py` around lines 1253 - 1299, Remove the
compatibility-only `if legacy` branch, including its accumulated-answer
reconstruction and final-chunk handling. Keep the direct `rag_agent` streaming
path that formats each answer, sanitizes the payload, and yields it unchanged;
eliminate any now-unused legacy-specific references in this flow.

Source: Coding guidelines

🤖 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/dao/migration.go`:
- Around line 273-304: Update the migration logic around the name_ci column and
idx_kb_tenant_name_ci checks to validate definitions rather than existence
alone. Inspect INFORMATION_SCHEMA metadata for the column’s generated status and
GENERATION_EXPRESSION, and for the index’s NON_UNIQUE value and ordered indexed
columns; continue only when they match the expected generated expression and
unique tenant/name_ci columns, otherwise return a schema-mismatch error instead
of skipping creation.

In `@rag/advanced_rag/agentic_rag.py`:
- Around line 549-550: Update the replacement string in the regex loop around
final and re.sub to preserve the capture-group backreference, using a raw
replacement string or an explicit named backreference so re.sub receives \1
rather than an octal control character.
- Around line 258-260: Remove the unconditional return immediately before the
self.kb_ids check in pick_documents so document selection can proceed to
metadata or title filtering. Preserve the existing early return when self.kb_ids
is empty.

---

Outside diff comments:
In `@api/apps/restful_apis/chat_api.py`:
- Around line 1253-1299: Remove the compatibility-only `if legacy` branch,
including its accumulated-answer reconstruction and final-chunk handling. Keep
the direct `rag_agent` streaming path that formats each answer, sanitizes the
payload, and yields it unchanged; eliminate any now-unused legacy-specific
references in this flow.
🪄 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: 3c245805-5d31-48a5-b56d-cf63953488b5

📥 Commits

Reviewing files that changed from the base of the PR and between cf4b7a5 and d4452ca.

📒 Files selected for processing (14)
  • api/apps/restful_apis/chat_api.py
  • deepdoc/parser/docling_parser.py
  • internal/dao/kb.go
  • internal/dao/migration.go
  • internal/dao/search.go
  • internal/service/dataset.go
  • internal/service/search.go
  • rag/advanced_rag/agentic_rag.py
  • rag/advanced_rag/harness/tools/__init__.py
  • rag/advanced_rag/harness/tools/registry.py
  • rag/advanced_rag/harness/tools/search.py
  • rag/advanced_rag/think_log.py
  • rag/llm/tool_decorator.py
  • test/unit_test/deepdoc/parser/test_docling_parser_remote.py
🚧 Files skipped from review as they are similar to previous changes (4)
  • internal/dao/search.go
  • internal/dao/kb.go
  • internal/service/search.go
  • internal/service/dataset.go

@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

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

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 (1)
api/apps/restful_apis/chat_api.py (1)

1253-1299: 📐 Maintainability & Code Quality | 🟠 Major | ⚖️ Poor tradeoff

Remove compatibility-only legacy branch.

As per coding guidelines, please prefer deletion over compatibility shims and remove compatibility-only surfaces. The legacy streaming fallback should be removed unless explicitly requested to remain.

♻️ Proposed refactor to remove legacy streaming branch
-                if legacy:
-                    # v0.23.0-style streaming: emit accumulated answer text and
-                    # reconstruct raw <think>...</think> markers from the newer
-                    # start_to_think/end_to_think events.
-                    legacy_answer = ""
-                    final_answer = None
-                    async for ans in rag_agent(dia, msg, True, session_id=session_id, **req):
-                        ans = _format_answer(ans)
-                        if ans.get("final"):
-                            final_answer = ans
-                            continue
-                        if ans.get("start_to_think"):
-                            legacy_answer += "<think>"
-                            legacy_chunk = {**ans, "answer": legacy_answer}
-                            legacy_chunk.pop("start_to_think", None)
-                            legacy_chunk.pop("end_to_think", None)
-                            payload = _sanitize_json_floats({"code": 0, "message": "", "data": legacy_chunk})
-                            yield "data:" + json.dumps(payload, ensure_ascii=False) + "\n\n"
-                            continue
-                        if ans.get("end_to_think"):
-                            legacy_answer += "</think>"
-                            legacy_chunk = {**ans, "answer": legacy_answer}
-                            legacy_chunk.pop("start_to_think", None)
-                            legacy_chunk.pop("end_to_think", None)
-                            payload = _sanitize_json_floats({"code": 0, "message": "", "data": legacy_chunk})
-                            yield "data:" + json.dumps(payload, ensure_ascii=False) + "\n\n"
-                            continue
-                        delta = ans.get("answer") or ""
-                        if not delta:
-                            continue
-                        legacy_answer += delta
-                        legacy_chunk = {**ans, "answer": legacy_answer}
-                        legacy_chunk.pop("start_to_think", None)
-                        legacy_chunk.pop("end_to_think", None)
-                        payload = _sanitize_json_floats({"code": 0, "message": "", "data": legacy_chunk})
-                        yield "data:" + json.dumps(payload, ensure_ascii=False) + "\n\n"
-                    if final_answer is not None:
-                        final_chunk = {**final_answer, "answer": final_answer.get("answer") or legacy_answer}
-                        final_chunk.pop("start_to_think", None)
-                        final_chunk.pop("end_to_think", None)
-                        payload = _sanitize_json_floats({"code": 0, "message": "", "data": final_chunk})
-                        yield "data:" + json.dumps(payload, ensure_ascii=False) + "\n\n"
-                else:
-                    async for ans in rag_agent(dia, msg, True, session_id=session_id, **req):
-                        ans = _format_answer(ans)
-                        payload = _sanitize_json_floats({"code": 0, "message": "", "data": ans})
-                        yield "data:" + json.dumps(payload, ensure_ascii=False) + "\n\n"
+                async for ans in rag_agent(dia, msg, True, session_id=session_id, **req):
+                    ans = _format_answer(ans)
+                    payload = _sanitize_json_floats({"code": 0, "message": "", "data": ans})
+                    yield "data:" + json.dumps(payload, ensure_ascii=False) + "\n\n"
🤖 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 `@api/apps/restful_apis/chat_api.py` around lines 1253 - 1299, Remove the
compatibility-only `if legacy` branch, including its accumulated-answer
reconstruction and final-chunk handling. Keep the direct `rag_agent` streaming
path that formats each answer, sanitizes the payload, and yields it unchanged;
eliminate any now-unused legacy-specific references in this flow.

Source: Coding guidelines

🤖 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/dao/migration.go`:
- Around line 273-304: Update the migration logic around the name_ci column and
idx_kb_tenant_name_ci checks to validate definitions rather than existence
alone. Inspect INFORMATION_SCHEMA metadata for the column’s generated status and
GENERATION_EXPRESSION, and for the index’s NON_UNIQUE value and ordered indexed
columns; continue only when they match the expected generated expression and
unique tenant/name_ci columns, otherwise return a schema-mismatch error instead
of skipping creation.

In `@rag/advanced_rag/agentic_rag.py`:
- Around line 549-550: Update the replacement string in the regex loop around
final and re.sub to preserve the capture-group backreference, using a raw
replacement string or an explicit named backreference so re.sub receives \1
rather than an octal control character.
- Around line 258-260: Remove the unconditional return immediately before the
self.kb_ids check in pick_documents so document selection can proceed to
metadata or title filtering. Preserve the existing early return when self.kb_ids
is empty.

---

Outside diff comments:
In `@api/apps/restful_apis/chat_api.py`:
- Around line 1253-1299: Remove the compatibility-only `if legacy` branch,
including its accumulated-answer reconstruction and final-chunk handling. Keep
the direct `rag_agent` streaming path that formats each answer, sanitizes the
payload, and yields it unchanged; eliminate any now-unused legacy-specific
references in this flow.
🪄 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: 3c245805-5d31-48a5-b56d-cf63953488b5

📥 Commits

Reviewing files that changed from the base of the PR and between cf4b7a5 and d4452ca.

📒 Files selected for processing (14)
  • api/apps/restful_apis/chat_api.py
  • deepdoc/parser/docling_parser.py
  • internal/dao/kb.go
  • internal/dao/migration.go
  • internal/dao/search.go
  • internal/service/dataset.go
  • internal/service/search.go
  • rag/advanced_rag/agentic_rag.py
  • rag/advanced_rag/harness/tools/__init__.py
  • rag/advanced_rag/harness/tools/registry.py
  • rag/advanced_rag/harness/tools/search.py
  • rag/advanced_rag/think_log.py
  • rag/llm/tool_decorator.py
  • test/unit_test/deepdoc/parser/test_docling_parser_remote.py
🚧 Files skipped from review as they are similar to previous changes (4)
  • internal/dao/search.go
  • internal/dao/kb.go
  • internal/service/search.go
  • internal/service/dataset.go
🛑 Comments failed to post (3)
internal/dao/migration.go (1)

273-304: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Validate the existing column and index definitions, not only their names.

Any name_ci column or idx_kb_tenant_name_ci index makes this migration skip creation. A regular/wrongly generated column, non-unique index, or index over different columns would therefore report success without enforcing the required invariant.

Inspect GENERATION_EXPRESSION, generated-column metadata, NON_UNIQUE, and the ordered index columns; fail with a schema-mismatch error unless they match the expected definitions.

🤖 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/dao/migration.go` around lines 273 - 304, Update the migration logic
around the name_ci column and idx_kb_tenant_name_ci checks to validate
definitions rather than existence alone. Inspect INFORMATION_SCHEMA metadata for
the column’s generated status and GENERATION_EXPRESSION, and for the index’s
NON_UNIQUE value and ordered indexed columns; continue only when they match the
expected generated expression and unique tenant/name_ci columns, otherwise
return a schema-mismatch error instead of skipping creation.
rag/advanced_rag/agentic_rag.py (2)

258-260: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Remove unreachable code blocking document selection.

The unconditional return None stops pick_documents from filtering by metadata or titles.

🐛 Proposed fix
-        return None
         if not self.kb_ids:
             return None
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        if not self.kb_ids:
            return None
🤖 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 `@rag/advanced_rag/agentic_rag.py` around lines 258 - 260, Remove the
unconditional return immediately before the self.kb_ids check in pick_documents
so document selection can proceed to metadata or title filtering. Preserve the
existing early return when self.kb_ids is empty.

549-550: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Fix regex backreference escaping.

The replacement string "[\1]" evaluates to [<SOH>] (Start of Heading character, \x01) because Python resolves \1 in a standard string as an octal escape. Use a raw string r"[\1]" or "[\g<1>]" so re.sub sees the backreference.

🐛 Proposed fix
-        for p, r in [(r"\(\**(ID:\d)\**\)", "[\1]")]:
-            final = re.sub(p, r, final)
+        final = re.sub(r"\(\**(ID:\d)\**\)", r"[\1]", final)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        final = re.sub(r"\(\**(ID:\d)\**\)", r"[\1]", final)
🧰 Tools
🪛 ast-grep (0.44.1)

[warning] 549-549: Regex pattern passed to re is built from a non-literal (variable, call, concatenation, or f-string) value. If that value is attacker-controlled it can introduce a malicious pattern with catastrophic backtracking (ReDoS). Use a hardcoded literal pattern, or validate/escape untrusted input with re.escape() and bound the regex complexity before compiling.
Context: re.sub(p, r, final)
Note: [CWE-1333] Inefficient Regular Expression Complexity.

(redos-non-literal-regex-python)

🤖 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 `@rag/advanced_rag/agentic_rag.py` around lines 549 - 550, Update the
replacement string in the regex loop around final and re.sub to preserve the
capture-group backreference, using a raw replacement string or an explicit named
backreference so re.sub receives \1 rather than an octal control character.

Source: Linters/SAST tools

euvre added 2 commits July 16, 2026 14:21
…data endpoints

Parse endpoint: read dataset_id from path param and document_ids from JSON
body instead of the mismatched StartParseDocumentsRequest schema. Return
{"success_count": N} matching the Python contract.

Stop parse: uncomment the POST /:dataset_id/documents/stop route.

Delete documents: use CodeDataError (102) instead of CodeArgumentError (101)
for empty-ids/empty-body validation, matching the Python contract.

List documents: move create_time_from/create_time_to filtering post-query so
total reflects the unfiltered count, matching Python behavior. Fix access
check to return CodeDataError with "You don't own the dataset" message.

Download: return "Document not found!" for invalid doc IDs.

Metadata batch update: replace strict struct binding with manual JSON parsing
to provide friendly validation messages matching Python (selector/updates/
deletes type checks).

Progress validation: return Pydantic-style range error when progress > 1.

validateDocsInDataset: capitalize "These" in error message.
Add ParserTypeKG constant and special-case it in validateParserID so
document chunk_method updates accept "knowledge_graph", matching the
Python ParserType.KG constant.
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 16, 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: 2

🧹 Nitpick comments (1)
internal/dao/document.go (1)

248-250: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Document current time-filter semantics without compatibility history.

Both comments should explain the runtime contract directly rather than why it matches Python.

  • internal/dao/document.go#L248-L250: state that time bounds are intentionally excluded from DAO predicates because filtering occurs after pagination.
  • internal/handler/document.go#L562-L564: state that page results are filtered in memory while total remains the pre-time-filter count.

As per coding guidelines, “keep package and documentation comments aligned with the current runtime path rather than migration history” and “do not add compatibility wording to comments or documentation.”

🤖 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/dao/document.go` around lines 248 - 250, Update the comments at
internal/dao/document.go:248-250 and internal/handler/document.go:562-564 to
describe only the current runtime behavior: DAO time bounds are excluded because
filtering occurs after pagination, and handler page results are filtered in
memory while total remains the pre-time-filter count. Remove references to
Python API compatibility or migration history.

Source: Coding guidelines

🤖 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/handler/document.go`:
- Around line 1794-1801: Validate each element in the document_ids loop before
converting it to a string. Update the selector parsing logic around
selector.DocumentIDs to safely type-check every id, return the existing
validation error for non-string values, and only append valid strings.
- Around line 1827-1832: Update the update-entry validation in the document
handler around the map lookup for key and value so the value field’s presence is
checked separately from its contents. Reject updates when “value” is absent,
while preserving acceptance of an explicitly provided JSON null if that remains
a valid value, and continue constructing DocumentMetadataUpdate only after both
required fields are present.

---

Nitpick comments:
In `@internal/dao/document.go`:
- Around line 248-250: Update the comments at internal/dao/document.go:248-250
and internal/handler/document.go:562-564 to describe only the current runtime
behavior: DAO time bounds are excluded because filtering occurs after
pagination, and handler page results are filtered in memory while total remains
the pre-time-filter count. Remove references to Python API compatibility or
migration history.
🪄 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: 49359a35-22fc-48ad-bc43-bbcf94c34f4a

📥 Commits

Reviewing files that changed from the base of the PR and between d4452ca and fae3029.

📒 Files selected for processing (6)
  • internal/dao/document.go
  • internal/entity/dataset.go
  • internal/handler/document.go
  • internal/router/router.go
  • internal/service/dataset.go
  • internal/service/document.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/service/dataset.go

Comment thread internal/handler/document.go Resolved
Comment thread internal/handler/document.go Resolved

@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 (1)
web/src/hooks/use-user-setting-request.tsx (1)

122-129: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Use the required query-key factory.

queryKey: [UserSettingApiAction.ListPipelines] is an inline React Query key. Define a same-file UserSettingKeys factory and reuse it for this query and any invalidation calls.

Proposed fix
+const UserSettingKeys = {
+  listPipelines: () => [UserSettingApiAction.ListPipelines] as const,
+} as const;
+
 const { data: pipelineListData } = useQuery({
-  queryKey: [UserSettingApiAction.ListPipelines],
+  queryKey: UserSettingKeys.listPipelines(),

As per coding guidelines: “Never write raw React Query queryKey arrays inline; use a domain query-key factory returning as const tuples.”

🤖 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 `@web/src/hooks/use-user-setting-request.tsx` around lines 122 - 129, Define a
same-file UserSettingKeys query-key factory that returns the ListPipelines key
as an as-const tuple, then replace the inline queryKey in the listPipelines
useQuery with that factory and reuse the same key for any related invalidation
calls.

Source: Coding guidelines

🤖 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 `@web/src/hooks/use-user-setting-request.tsx`:
- Around line 122-129: Define a same-file UserSettingKeys query-key factory that
returns the ListPipelines key as an as-const tuple, then replace the inline
queryKey in the listPipelines useQuery with that factory and reuse the same key
for any related invalidation calls.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8b514574-c7b4-48c8-bd4f-e364d6b16da8

📥 Commits

Reviewing files that changed from the base of the PR and between fae3029 and be22504.

📒 Files selected for processing (4)
  • docker/init-clickhouse.sql
  • internal/entity/dataset.go
  • internal/router/router.go
  • web/src/hooks/use-user-setting-request.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/router/router.go
  • internal/entity/dataset.go

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jul 20, 2026
@euvre euvre added ci Continue Integration and removed ci Continue Integration labels Jul 20, 2026
@euvre
euvre requested a review from wangq8 July 20, 2026 10:24

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: PR #16905 — Add Go service/handler tests for API contract parity

This is a substantial PR (+1552/-213 across ~45 files). Summary of changes and evaluation:

Go Service & Handler Changes

  1. Chat entity — removed GORM default: tags: Fields like similarity_threshold, vector_similarity_weight, top_n, top_k no longer have default: GORM tags. The Create method now uses Select("*") to persist explicit zero values. This is the correct approach — the service layer supplies defaults when omitted, and honoring explicit zeros matches the Python API contract. Good.

  2. Knowledgebase case-insensitive name lookup: GetByName now uses LOWER(name) = LOWER(?) to match MySQL's default case-insensitive collation. Migration adds a generated column name_ci + unique index on (tenant_id, name_ci) for valid rows only. The migration checks for existing duplicates before creating the index. This is well-engineered.

  3. Authorization error codes standardized: No authorization responses now return CodeAuthenticationError (109) instead of CodeDataError (102), with trailing period for message consistency. Correct.

  4. Accessible4Deletion fix: Changed from First() (returns ErrRecordNotFound → "no rows in result set" error message) to Count() so missing/unauthorized returns (false, nil), letting callers distinguish "not authorized" from DB errors.

  5. Document list handler: create_time_from / create_time_to filters are now applied post-query so total reflects the unfiltered count, matching the Python contract. The comment explains this clearly.

  6. Batch document metadata updates: Changed from ShouldBindJSON to raw json.Unmarshal + manual field parsing to handle null/type variations. More robust for the API contract.

  7. StartIngestionTask: Now reads dataset_id from URL param instead of request body. Response changed to {"success_count": N}. The old response returned the full parse result list, which was inconsistent with the Python contract.

Python Side Changes

  • Removal of unused async_chat import in chat_api.py — clean, no functional impact.
  • Formatting-only changes in begin.py, docling_parser.py, pdf_parser.py.
  • Removal of trailing newline in init-clickhouse.sql — cosmetic.
  • tool_decorator.py, tool_registry.py, think_log.py, qa.py changes — these appear in the file list but the truncated diff doesn't show them clearly.

Testing

Extensive new tests covering:

  • Chat: name validation, case-insensitive duplicate detection, tenant_id rejection, prompt-config defaults
  • Search: empty-name rejection (102), unauthorized update (109), create/update round-trip
  • Dataset: embedding-model format validation, field preservation on partial update, parser_config merge
  • Chat session: create (name validation, truncation, ownership) and delete (by IDs, delete_all, invalid ID)
    The tests use in-memory SQLite with TranslateError: true for proper error handling — solid approach.

Concerns

  • The diff is truncated for me so I couldn't review every changed file. In particular the agent/component/begin.py, rag/advanced_rag/ changes and rag/llm/tool_decorator.py appear in the file list but their diffs weren't fully visible. Please ensure those are reviewed separately if they carry logic changes.
  • StartIngestionTask response format change (from full result list to {"success_count": N}) is a breaking API change for any client consuming the old response. If this aligns with the Python API contract it's fine, but worth noting.

Verdict

LGTM overall — well-structured, well-tested, and the contract alignment fixes are necessary for API consistency. The migration is handled safely with duplicate detection and conditional index creation. The approach of removing GORM default tags and using Select("*") is the right fix for zero-value handling.

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR #16905 – Add Go service/handler tests for API contract parity

Summary

This PR brings the Go backend into line with the established Python API contract by:

  1. Aligning response codes & messages – Changing CodeDataError (102) → CodeAuthenticationError (109) for auth failures, and standardizing error message punctuation (trailing periods) to match the Python contract.
  2. Fixing numeric field defaults – Removing GORM default: tags from Chat entity numeric fields (similarity_threshold, vector_similarity_weight, top_n, top_k) so that explicitly-provided zero values are persisted instead of silently replaced by column defaults. Paired with DB.Select("*").Create(...).
  3. Case-insensitive name handling – KnowledgebaseDAO.GetByName now uses LOWER(name)=LOWER(?), and a migration adds a name_ci generated column + unique index for concurrent-safe duplicate detection.
  4. Robust JSON parsing – Dataset/handler now uses raw body + json.Unmarshal instead of ShouldBindJSON to accurately detect parser_config key presence. Metadata batch update parsing refactored into explicit helper functions.
  5. API contract fixes – StartIngestionTask request field renamed documents → document_ids, response changed to {"success_count": N}. Auth error codes fixed in document, stop-parse, and chat-session handlers.
  6. Extensive tests – ~1,000+ lines of new Go tests covering chat CRUD validation, search contracts, dataset creation, chat-session create/delete, and handler-level auth/ownership checks.

Strengths

  • Contract discipline – The systematic mapping of error codes (102 vs 109) and message punctuation to the Python contract is exactly right. This is what API parity requires.
  • Zero-value edge case – The Chat entity GORM tag removal + Select("*") in Create is a well-understood GORM footgun, and the fix is correct.
  • Migration safety – The migrateKnowledgebaseNameUnique function checks for existing duplicate names before adding the index, failing with a clear message. The virtual generated column approach (NULL for soft-deleted rows) is thoughtful.
  • Test quality – Tests are well-structured with proper setup/teardown (t.Cleanup), use in-memory SQLite, and test both success paths and edge cases (empty name, duplicate name, non-owner, long name truncation). The fake-store approach for chat-session tests is clean and fast.

Concerns / Suggested Improvements

1. Breaking change: StartIngestionTask request shape change (L1435–1455 in internal/handler/document.go)
The field was renamed from "documents" to "document_ids" and is now binding:"required". Any existing client (Python tests, frontend, CLI scripts) sending the old field name will get a 400 error. This should be called out explicitly in the PR description. If backward compatibility is needed, consider accepting both field names.

2. Breaking change: StartIngestionTask response shape
Was returning the raw parse result array; now returns {"success_count": N}. This is a visible API contract change that callers must adapt to. Same note as above.

3. LOWER(name)=LOWER(?) may harm query performance
On large knowledgebase tables, wrapping the column in LOWER() prevents index usage for this query. The name_ci generated column + unique index helps for uniqueness enforcement, but GetByName() is a read path that runs on every dataset access. Consider adding a regular index on (tenant_id, name_ci) if this is a hot path.

4. MySQL-specific migration
The ALTER TABLE ... ADD COLUMN ... GENERATED ALWAYS AS ... VIRTUAL and INFORMATION_SCHEMA queries are MySQL-specific. If the project officially supports other databases (PostgreSQL, SQLite for tests), this migration will fail silently or require separate paths. Currently the in-memory SQLite test setup doesn't run migrations, so this isn't immediately broken, but worth noting.

5. Accessible4Deletion (search) – error masking risk
Changed from First to Count. If the DB is unreachable, Count still returns an error, so that's fine. But if Count returns 0 due to a filter mismatch without an error, the caller treats it as "not authorized" rather than "not found". The comment says this is intentional, but callers lose the ability to distinguish "search does not exist" from "search exists but you don't own it." Consider whether the Python contract truly treats these the same.

6. StopParseDocuments error code change (109 → 102)
L1523–1528 changed CodeAuthenticationError → CodeDataError for the "You don't own the dataset" message. Is this consistent with the Python contract? The other handlers use 109 for ownership failures. If Python uses 102 for this specific endpoint, fine — but it deviates from the pattern established in the rest of this PR.

7. Metadata batch update – validation edge cases
The new parseMetadataSelector / parseMetadataUpdates / parseMetadataDeletes helpers do basic type checks but use type assertions (id.(string)) without a ok guard. If a document_ids element is a number instead of a string, this will panic at runtime. Consider adding safe type coercion or explicit error returns.

Verdict

Solid work. This PR systematically brings Go closer to the Python contract and adds much-needed test coverage. The breaking changes and a couple of edge-case panics are worth addressing before merging, but overall this is a high-quality PR.

Recommendation: Address the type-assertion panics in metadata batch parsing (concern #7), add a note about the API breaking changes in the PR description (concerns #1–2), and double-check the StopParseDocuments error code change (#6). The rest is ready to land.

@wangq8
wangq8 merged commit f45f03a into infiniflow:main Jul 20, 2026
5 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:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants