Skip to content

fix(knowledge-runtime): shorten db session boundary - #1569

Merged
qdaxb merged 1 commit into
wecode-ai:mainfrom
cocowh:fix/knowledge-runtime-db-session-boundary
Jun 30, 2026
Merged

qdaxb merged 1 commit into
wecode-ai:mainfrom
cocowh:fix/knowledge-runtime-db-session-boundary

Conversation

@cocowh

@cocowh cocowh commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • add a short-lived RuntimeConfigLoader to end DB transactions immediately after runtime config resolution
  • remove request-scoped DB sessions from knowledge runtime index/query/admin endpoints and executors
  • resolve multi-KB query configs before vector retrieval so external RAG I/O no longer holds MySQL sessions

Verification

  • uv run pytest in knowledge_runtime (109 passed, third-party Pydantic deprecation warning only)
  • uv run black --check knowledge_runtime tests
  • uv run isort --check-only knowledge_runtime tests
  • uv run flake8 --max-line-length=88 ... on changed knowledge_runtime source files
  • pre-push hook passed with CI=true AI_VERIFIED=1 git push

Summary by CodeRabbit

  • Refactor
    • Updated indexing, querying, and admin operations to use a new runtime configuration flow.
    • Simplified request handling so these endpoints no longer require database session wiring.
  • Tests
    • Added coverage for the new configuration loader behavior and updated existing executor tests to match the revised setup.

@coderabbitai

coderabbitai Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

FastAPI admin, index, and query endpoints no longer inject database sessions. A new RuntimeConfigLoader resolves runtime configs through short-lived sessions, and the executors now consume that loader directly. Tests were updated for the new constructor and resolution flow.

Changes

Runtime config resolution refactor

Layer / File(s) Summary
Runtime config loader
knowledge_runtime/knowledge_runtime/services/config_loader.py, knowledge_runtime/tests/test_config_loader.py
RuntimeConfigLoader adds index, query, and admin config resolution through a short-lived session, and its tests cover success, error, and batch-query paths.
Admin executor
knowledge_runtime/knowledge_runtime/services/admin_executor.py, knowledge_runtime/tests/test_admin_executor.py
AdminExecutor now accepts RuntimeConfigLoader and resolves admin config through it before delete, purge, drop, and list-chunks operations; the tests use the loader mock.
Index executor
knowledge_runtime/knowledge_runtime/services/index_executor.py, knowledge_runtime/tests/test_index_executor.py
IndexExecutor now resolves index config through RuntimeConfigLoader, and the tests instantiate it with a mocked loader for success and error paths.
Query executor
knowledge_runtime/knowledge_runtime/services/query_executor.py, knowledge_runtime/tests/test_query_executor.py
QueryExecutor resolves all requested knowledge-base configs through RuntimeConfigLoader, passes resolved QueryConfig into _query_knowledge_base, and the tests assert batched resolution and the updated constructor.
Endpoint handlers
knowledge_runtime/knowledge_runtime/api/endpoints/*.py
The admin, index, and query handlers remove injected database sessions and construct their executors directly from the request payload.

Sequence Diagram(s)

sequenceDiagram
  participant QueryExecutor
  participant RuntimeConfigLoader
  participant ConfigResolver
  participant KnowledgeQueryExecutor
  QueryExecutor->>RuntimeConfigLoader: resolve_query_configs(knowledge_base_ids, user_id)
  RuntimeConfigLoader->>ConfigResolver: resolve_query_configs(session, knowledge_base_ids, user_id)
  ConfigResolver-->>RuntimeConfigLoader: configs_by_kb_id
  RuntimeConfigLoader-->>QueryExecutor: configs_by_kb_id
  QueryExecutor->>KnowledgeQueryExecutor: _query_knowledge_base(config, request)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • wecode-ai/Wegent#1030: Modifies the same knowledge_runtime endpoints and executors while changing how session-backed config resolution is wired.
  • wecode-ai/Wegent#1224: Touches QueryExecutor config resolution and retrieval-override flow in the same module family.
  • wecode-ai/Wegent#1330: Also adjusts knowledge runtime indexing/query session lifetime handling across the same execution path.

Suggested reviewers

  • qdaxb
  • sunnights

Poem

🐰 I hopped through configs, quick and bright,
With loader paths lit up just right.
Sessions roll, then close, then cease—
Query carrots nibble in peace!
Thump thump, the tests all dance tonight.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 61.90% 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: shortening the DB session boundary in knowledge runtime.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

🧹 Nitpick comments (3)
knowledge_runtime/knowledge_runtime/services/config_loader.py (1)

39-100: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add tracing to the new config-resolution entrypoints.

These new sync service methods are the boundary this PR introduces, but none of them use @trace_sync or attach span details. That makes the shortened DB-session behavior invisible in telemetry and misses a repo rule for changed Python code. Please instrument the public resolve_* methods and record identifiers like knowledge_base_id / batch size on the span. Based on coding guidelines: "Use @trace_async or @trace_sync decorators from shared.telemetry.decorators for tracing async and sync functions respectively; use add_span_event() and set_span_attribute() for adding details to spans."

🤖 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 `@knowledge_runtime/knowledge_runtime/services/config_loader.py` around lines
39 - 100, The new public config-resolution methods in ConfigLoader are missing
required telemetry, so add `@trace_sync` from shared.telemetry.decorators to each
sync resolve_* entrypoint and attach span attributes/events inside them.
Instrument resolve_index_config, resolve_query_config, resolve_query_configs,
and resolve_admin_config so the trace captures identifiers like
knowledge_base_id, user_id, document_id, and the batch size for
resolve_query_configs, using set_span_attribute() and add_span_event() where
appropriate.

Source: Coding guidelines

knowledge_runtime/tests/test_admin_executor.py (1)

65-71: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert resolve_admin_config is called with the request KB ID.

These tests now stub resolve_admin_config.return_value, so they would still pass if the executor resolved a hard-coded or wrong knowledge_base_id. Add assert_called_once_with(knowledge_base_id=1) after each executor call to lock down the new loader boundary.

Also applies to: 101-107, 133-139, 181-187, 213-219, 243-249

🤖 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 `@knowledge_runtime/tests/test_admin_executor.py` around lines 65 - 71, The
admin executor tests are only stubbing resolve_admin_config and do not verify it
is invoked with the request knowledge base ID. After each delete_document_index
call in test_admin_executor, add an assertion on
admin_executor._config_loader.resolve_admin_config to check it was called once
with knowledge_base_id=1, using the same pattern in the other affected test
cases.
knowledge_runtime/knowledge_runtime/services/index_executor.py (1)

27-28: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Stale docstring reference.

The class docstring still says configs are resolved "using ConfigResolver", but resolution now flows through RuntimeConfigLoader. Minor doc drift.

📝 Suggested docstring tweak
-    1. Resolves configs from the database using ConfigResolver
+    1. Resolves configs from the database using RuntimeConfigLoader
🤖 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 `@knowledge_runtime/knowledge_runtime/services/index_executor.py` around lines
27 - 28, The class docstring for KnowledgeRuntimeExecutor is stale: it still
references ConfigResolver even though config resolution now happens through
RuntimeConfigLoader. Update the docstring text in KnowledgeRuntimeExecutor to
describe the current runtime config loading flow and remove the outdated
ConfigResolver mention so the documentation matches the implementation.
🤖 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.

Nitpick comments:
In `@knowledge_runtime/knowledge_runtime/services/config_loader.py`:
- Around line 39-100: The new public config-resolution methods in ConfigLoader
are missing required telemetry, so add `@trace_sync` from
shared.telemetry.decorators to each sync resolve_* entrypoint and attach span
attributes/events inside them. Instrument resolve_index_config,
resolve_query_config, resolve_query_configs, and resolve_admin_config so the
trace captures identifiers like knowledge_base_id, user_id, document_id, and the
batch size for resolve_query_configs, using set_span_attribute() and
add_span_event() where appropriate.

In `@knowledge_runtime/knowledge_runtime/services/index_executor.py`:
- Around line 27-28: The class docstring for KnowledgeRuntimeExecutor is stale:
it still references ConfigResolver even though config resolution now happens
through RuntimeConfigLoader. Update the docstring text in
KnowledgeRuntimeExecutor to describe the current runtime config loading flow and
remove the outdated ConfigResolver mention so the documentation matches the
implementation.

In `@knowledge_runtime/tests/test_admin_executor.py`:
- Around line 65-71: The admin executor tests are only stubbing
resolve_admin_config and do not verify it is invoked with the request knowledge
base ID. After each delete_document_index call in test_admin_executor, add an
assertion on admin_executor._config_loader.resolve_admin_config to check it was
called once with knowledge_base_id=1, using the same pattern in the other
affected test cases.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 13ca1404-4ab6-4401-8f2a-f6f374899b23

📥 Commits

Reviewing files that changed from the base of the PR and between 2153fa6 and 15c15fd.

📒 Files selected for processing (11)
  • knowledge_runtime/knowledge_runtime/api/endpoints/admin.py
  • knowledge_runtime/knowledge_runtime/api/endpoints/index.py
  • knowledge_runtime/knowledge_runtime/api/endpoints/query.py
  • knowledge_runtime/knowledge_runtime/services/admin_executor.py
  • knowledge_runtime/knowledge_runtime/services/config_loader.py
  • knowledge_runtime/knowledge_runtime/services/index_executor.py
  • knowledge_runtime/knowledge_runtime/services/query_executor.py
  • knowledge_runtime/tests/test_admin_executor.py
  • knowledge_runtime/tests/test_config_loader.py
  • knowledge_runtime/tests/test_index_executor.py
  • knowledge_runtime/tests/test_query_executor.py

@qdaxb
qdaxb merged commit d1f66c6 into wecode-ai:main Jun 30, 2026
24 checks passed
@cocowh
cocowh deleted the fix/knowledge-runtime-db-session-boundary branch September 3, 2026 03:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants