Repository navigation
Add Go service/handler tests for API contract parity - #16905
Conversation
- 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.
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe 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. ChangesChat contracts
Dataset lookup and update flow
Search access and response contracts
Document listing, ingestion, and metadata
Formatting cleanup
Estimated code review effort: 5 (Critical) | ~120 minutes Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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. Comment |
There was a problem hiding this comment.
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 winValidate
ext.embd_idthe same way asEmbeddingModel.
Theextbranch still skipsvalidateDatasetEmbeddingModelfor"", soext: {"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 anext.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 winRedundant condition in
validateDatasetEmbeddingModel.Given the preceding
strings.Contains(embeddingModel, "@")guard,strings.SplitN(embeddingModel, "@", 2)is guaranteed to return exactly 2 elements, andparts[0] == ""/parts[1] == ""is already subsumed by the very nextstrings.TrimSpace(parts[0]) == "" || strings.TrimSpace(parts[1]) == ""check. The firstif len(parts) != 2 || parts[0] == "" || parts[1] == ""branch is unreachable/duplicate logic.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."♻️ 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") }🤖 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 winAdd a case-insensitive duplicate-name test for
CreateDataset.
TestDatasetServiceCreateDatasetRejectsDuplicateNameonly exercises an exact-case match. SinceGetByName's case-insensitivity change (kb.go) applies toCreateDatasettoo, anddataset_update_test.goalready hasTestDatasetServiceUpdateDatasetRejectsDuplicateNameCaseInsensitivefor 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 winAvoid
LOWER(name)here. It prevents the existingnameindex 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
📒 Files selected for processing (15)
internal/dao/kb.gointernal/handler/chat.gointernal/handler/chat_test.gointernal/handler/search.gointernal/handler/search_handler_test.gointernal/service/chat.gointernal/service/chat_list_test.gointernal/service/chat_rest_update_test.gointernal/service/chat_session_contract_test.gointernal/service/dataset.gointernal/service/dataset_create_test.gointernal/service/dataset_update_test.gointernal/service/search.gointernal/service/search_test.gotest/testcases/restful_api/conftest.py
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
- 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
There was a problem hiding this comment.
♻️ Duplicate comments (1)
internal/service/dataset.go (1)
2484-2495: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy liftEnforce dataset-name uniqueness in the database.
The check-then-write logic around
CreateDataset(and similarly the rename path inUpdateDataset) 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 existingCodeDataError"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
📒 Files selected for processing (8)
internal/dao/chat.gointernal/dao/kb.gointernal/handler/dataset.gointernal/handler/search.gointernal/service/chat.gointernal/service/dataset.gointernal/service/dataset_create_test.gotest/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
…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".
There was a problem hiding this comment.
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
📒 Files selected for processing (5)
internal/dao/kb.gointernal/dao/migration.gointernal/dao/search.gointernal/service/dataset.gointernal/service/search.go
🚧 Files skipped from review as they are similar to previous changes (2)
- internal/dao/kb.go
- internal/service/dataset.go
…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.
…contract-test-parity
…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.
There was a problem hiding this comment.
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 tradeoffRemove compatibility-only legacy branch.
As per coding guidelines, please prefer deletion over compatibility shims and remove compatibility-only surfaces. The
legacystreaming 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
📒 Files selected for processing (14)
api/apps/restful_apis/chat_api.pydeepdoc/parser/docling_parser.pyinternal/dao/kb.gointernal/dao/migration.gointernal/dao/search.gointernal/service/dataset.gointernal/service/search.gorag/advanced_rag/agentic_rag.pyrag/advanced_rag/harness/tools/__init__.pyrag/advanced_rag/harness/tools/registry.pyrag/advanced_rag/harness/tools/search.pyrag/advanced_rag/think_log.pyrag/llm/tool_decorator.pytest/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
There was a problem hiding this comment.
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 tradeoffRemove compatibility-only legacy branch.
As per coding guidelines, please prefer deletion over compatibility shims and remove compatibility-only surfaces. The
legacystreaming 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
📒 Files selected for processing (14)
api/apps/restful_apis/chat_api.pydeepdoc/parser/docling_parser.pyinternal/dao/kb.gointernal/dao/migration.gointernal/dao/search.gointernal/service/dataset.gointernal/service/search.gorag/advanced_rag/agentic_rag.pyrag/advanced_rag/harness/tools/__init__.pyrag/advanced_rag/harness/tools/registry.pyrag/advanced_rag/harness/tools/search.pyrag/advanced_rag/think_log.pyrag/llm/tool_decorator.pytest/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_cicolumn oridx_kb_tenant_name_ciindex 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 Nonestopspick_documentsfrom 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\1in a standard string as an octal escape. Use a raw stringr"[\1]"or"[\g<1>]"sore.subsees 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
…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.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
internal/dao/document.go (1)
248-250: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDocument 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 whiletotalremains 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
📒 Files selected for processing (6)
internal/dao/document.gointernal/entity/dataset.gointernal/handler/document.gointernal/router/router.gointernal/service/dataset.gointernal/service/document.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/service/dataset.go
# Conflicts: # internal/handler/document.go
There was a problem hiding this comment.
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 winUse the required query-key factory.
queryKey: [UserSettingApiAction.ListPipelines]is an inline React Query key. Define a same-fileUserSettingKeysfactory 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
📒 Files selected for processing (4)
docker/init-clickhouse.sqlinternal/entity/dataset.gointernal/router/router.goweb/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
wangq8
left a comment
There was a problem hiding this comment.
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
-
Chat entity — removed GORM
default:tags: Fields likesimilarity_threshold,vector_similarity_weight,top_n,top_kno longer havedefault:GORM tags. The Create method now usesSelect("*")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. -
Knowledgebase case-insensitive name lookup:
GetByNamenow usesLOWER(name) = LOWER(?)to match MySQL's default case-insensitive collation. Migration adds a generated columnname_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. -
Authorization error codes standardized:
No authorizationresponses now returnCodeAuthenticationError (109)instead ofCodeDataError (102), with trailing period for message consistency. Correct. -
Accessible4Deletion fix: Changed from
First()(returnsErrRecordNotFound→ "no rows in result set" error message) toCount()so missing/unauthorized returns(false, nil), letting callers distinguish "not authorized" from DB errors. -
Document list handler:
create_time_from/create_time_tofilters are now applied post-query so total reflects the unfiltered count, matching the Python contract. The comment explains this clearly. -
Batch document metadata updates: Changed from
ShouldBindJSONto rawjson.Unmarshal+ manual field parsing to handle null/type variations. More robust for the API contract. -
StartIngestionTask: Now reads
dataset_idfrom 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_chatimport inchat_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.pychanges — 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_idrejection, 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_configmerge - Chat session: create (name validation, truncation, ownership) and delete (by IDs,
delete_all, invalid ID)
The tests use in-memory SQLite withTranslateError: truefor 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 andrag/llm/tool_decorator.pyappear 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
left a comment
There was a problem hiding this comment.
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:
- Aligning response codes & messages – Changing
CodeDataError(102) →CodeAuthenticationError(109) for auth failures, and standardizing error message punctuation (trailing periods) to match the Python contract. - Fixing numeric field defaults – Removing GORM
default:tags fromChatentity 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 withDB.Select("*").Create(...). - Case-insensitive name handling –
KnowledgebaseDAO.GetByNamenow usesLOWER(name)=LOWER(?), and a migration adds aname_cigenerated column + unique index for concurrent-safe duplicate detection. - Robust JSON parsing – Dataset/handler now uses raw body +
json.Unmarshalinstead ofShouldBindJSONto accurately detectparser_configkey presence. Metadata batch update parsing refactored into explicit helper functions. - API contract fixes –
StartIngestionTaskrequest field renameddocuments→document_ids, response changed to{"success_count": N}. Auth error codes fixed in document, stop-parse, and chat-session handlers. - 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
Chatentity GORM tag removal +Select("*")inCreateis a well-understood GORM footgun, and the fix is correct. - Migration safety – The
migrateKnowledgebaseNameUniquefunction checks for existing duplicate names before adding the index, failing with a clear message. The virtual generated column approach (NULLfor 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.
Summary
This PR supplements Go tests and aligns several Go validation/response contracts with the established Python API contract (the category-2
GO_ONLY_SKIPSentries intest/testcases/restful_api/conftest.py).CodeDataError/ 109CodeAuthenticationError) with the Python contract (e.g.`name` can not be empty.,No authorization.).KnowledgebaseDAO.GetByNamecase-insensitive to match MySQL's default collation, so duplicate-name detection is consistent across case.tenant_idrejection, prompt-config defaults;parser_configmerge;delete_all, invalid ID) contracts.GO_ONLY_SKIPSlist.