Repository navigation
feat(domain-dict): optimize batch processing and add LLM logging - #468
Conversation
Changes: - Reduce batch size from 500 to 100 terms for faster LLM responses - Process max 3 batches (300 terms) per run with progress feedback - Add detailed LLM logging (TTFB, chunk count, token usage, timing) - Simplify filter lists: keep only pure technical terms, let AI decide business relevance - Remove overly aggressive filtering of potentially business-related terms The filter simplification allows terms like 'agent', 'chat', 'service' etc. to be included if they are part of compound business concepts.
WalkthroughIntroduces package-structure analysis and batching to prioritize and extract domain names, tightens validation to require compound domain concepts and filters technical terms, and adds detailed streaming telemetry and error logging to the LLM service. Tests were trimmed to core domain-dict checks. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
|
@augmentcode augment review |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (4)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/subagent/DomainDictAgent.kt (1)
191-206: Batch processing logic is well-structured.The chunked approach with progress feedback is appropriate for long-running LLM operations.
Minor nit: Line 204 creates an unnecessary alias (
val newEntries = allNewEntries) sinceallNewEntriescould be used directly in subsequent code.- val newEntries = allNewEntries - onProgress(" 📊 Total: ${newEntries.size} entries from ${namesToProcess.size} terms") + onProgress(" 📊 Total: ${allNewEntries.size} entries from ${namesToProcess.size} terms")Then replace
newEntrieswithallNewEntriesin the rest of the method, or renameallNewEntriestonewEntriesat declaration.mpp-core/src/commonMain/kotlin/cc/unitmesh/llm/KoogLLMService.kt (3)
62-69: Timing metrics exclude DevIns compilation; consider clarifying scope and clock choice
startTimeis captured aftercompilePrompt, so both TTFB and"Stream completed - ... time"measure only the LLM streaming phase, not end‑to‑end latency from the originaluserPrompt. If you intend to track total user‑visible latency (including DevIns compilation and prompt building), consider movingstartTimeup before thecompileDevInsbranch. Otherwise, clarifying in log messages that this is “LLM stream time” would avoid confusion.Also, for duration measurements, a monotonic time source (e.g.,
TimeSource.Monotonic.markNow()withelapsedNow().inWholeMilliseconds) would be more robust thanClock.System.now()if the system clock changes during a request.
84-107: Token logging and compression trigger are correct; consider extra logging and shared‑state behaviorThe End‑frame handling correctly:
- Logs stream completion with elapsed time, chunk and char counts.
- Extracts token counts from
metaInfointolastTokenInfo.- Invokes
onTokenUpdateand, when enabled, checksneedsCompressionbefore callingonCompressionNeeded.Two follow‑ups to consider:
Compression decision observability
WhenneedsCompressionreturns true andonCompressionNeededis invoked, adding an info‑level log (current tokens,maxTokens, threshold) would make it easier to correlate auto‑compression behavior with domain‑dict runs.Shared mutable state across concurrent calls
lastTokenInfoandmessagesSinceLastCompressionare mutable fields on the service and are updated here on every stream completion. If a singleKoogLLMServiceinstance can be used concurrently by multiple sessions/calls, these updates may interleave and make compression heuristics session‑ambiguous. If concurrency is possible, consider either:
- Scoping these fields per conversation/session instead of per service instance, or
- Protecting updates with appropriate synchronization (e.g., per‑session mutex/state holder) so compression decisions are based on the correct history.
Also,
messagesSinceLastCompression++runs regardless of whethermetaInfois present; just confirm that this matches how you expecttryCompressHistoryto gate retries when providers omit token usage.
108-108: ToolCall frames are currently dropped; consider at least debug logging
StreamFrame.ToolCallis ignored with only a comment. If Koog’s streaming can emit tool‑call frames, it may be worth at least logging them at debug level (or surfacing them via a callback) so future tool integrations don’t silently no‑op here.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/subagent/DomainDictAgent.kt(9 hunks)mpp-core/src/commonMain/kotlin/cc/unitmesh/llm/KoogLLMService.kt(2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{kt,kts}
📄 CodeRabbit inference engine (AGENTS.md)
Use
expect/actualfor platform-specific code in Kotlin Multiplatform (e.g., file I/O on JVM/JS/Wasm)
Files:
mpp-core/src/commonMain/kotlin/cc/unitmesh/llm/KoogLLMService.ktmpp-core/src/commonMain/kotlin/cc/unitmesh/agent/subagent/DomainDictAgent.kt
**/*.{kt,css,ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
DO NOT hardcode colors (e.g.,
Color(0xFF...)or#hex). Always use design tokens for consistency across platforms
Files:
mpp-core/src/commonMain/kotlin/cc/unitmesh/llm/KoogLLMService.ktmpp-core/src/commonMain/kotlin/cc/unitmesh/agent/subagent/DomainDictAgent.kt
🧬 Code graph analysis (1)
mpp-core/src/commonMain/kotlin/cc/unitmesh/llm/KoogLLMService.kt (2)
mpp-core/src/commonMain/kotlin/cc/unitmesh/indexer/DomainDictGenerator.kt (1)
buildPrompt(77-119)mpp-core/src/jsMain/kotlin/cc/unitmesh/llm/JsExports.kt (1)
getMaxTokens(128-131)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
- GitHub Check: Test mpp-core (KMP)
- GitHub Check: Build (223)
- GitHub Check: Build (241)
🔇 Additional comments (8)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/subagent/DomainDictAgent.kt (7)
164-168: LGTM!Clean integration of package structure analysis into the extraction flow. The early computation of
importantPackagesand passing it downstream follows good data flow patterns.
345-357: LGTM!The sequential regex replacements correctly handle various source directory layouts (Maven, Gradle, Kotlin Multiplatform). The logic properly extracts the package path from the file path.
359-375: LGTM!Good use of bidirectional prefix matching for package prioritization. The default empty set parameter maintains backward compatibility with existing callers.
446-449: Requiring 2+ capitals may filter legitimate domain terms.The compound word requirement will exclude valid single-word business entities like
Order,Invoice,Customer,Payment,Product. These are core DDD concepts in many domains.The PR objectives mention filtering "Agent" (too generic), but the current rule also filters domain-specific terms. Consider allowing single PascalCase words that aren't in a generic terms blocklist, rather than blanket requiring 2+ capitals.
Is this intentional? If legitimate single-word domain terms should be included, consider:
- // IMPORTANT: Require at least 2 capital letters (compound name) - // This ensures we get "DomainDict" not "Agent" - val capitalCount = name.count { it.isUpperCase() } - if (capitalCount < 2) return false + // Require at least 2 capital letters OR a known domain word pattern + val capitalCount = name.count { it.isUpperCase() } + val genericSingleWords = setOf("agent", "chat", "code", "task", "model", "file", "path", "node", "item", "event", "action", "state", "context", "message") + if (capitalCount < 2 && name.lowercase() in genericSingleWords) return false
659-701: LGTM!The prompt is well-structured with clear positive and negative examples. The Chinese language is appropriate for generating bilingual domain dictionary entries. The instructions align with the code-level validation logic.
751-767: LGTM!Good defense-in-depth pattern—validating LLM outputs even after prompt instructions. The exact-match check for technical terms is appropriate here (unlike the substring matching in package filtering).
598-631: LGTM!The skip term categorization is clearer with comments. The platform-specific terms (JetBrains internals, Swing/AWT) are appropriately filtered as they're framework-specific rather than business concepts.
mpp-core/src/commonMain/kotlin/cc/unitmesh/llm/KoogLLMService.kt (1)
70-83: Streaming loop and TTFB instrumentation look solidThe streaming bridge (
executeStreaming(...).cancellable().collect) with per‑chunk accounting and TTFB logged on the firstStreamFrame.Appendis straightforward and should give useful observability, while still emitting each chunk promptly viaemit(frame.text). No functional issues stand out here.
| // Filter out infrastructure packages | ||
| val infrastructurePatterns = setOf( | ||
| "test", "config", "util", "utils", "helper", "common", | ||
| "generated", "build", "gradle", "node_modules", "target" | ||
| ) | ||
|
|
||
| val businessPackages = packageCounts.filterKeys { pkg -> | ||
| val lowerPkg = pkg.lowercase() | ||
| infrastructurePatterns.none { lowerPkg.contains(it) } | ||
| } |
There was a problem hiding this comment.
Infrastructure filtering may be overly aggressive.
The contains check on line 320 matches substrings, which could incorrectly filter legitimate business packages:
"commonMain"contains"common"→ filtered"testDriven"or"contestant"contains"test"→ filtered"configuration"contains"config"→ filtered
Consider using word-boundary matching or segment-based checks instead.
val businessPackages = packageCounts.filterKeys { pkg ->
- val lowerPkg = pkg.lowercase()
- infrastructurePatterns.none { lowerPkg.contains(it) }
+ val segments = pkg.lowercase().split("/")
+ infrastructurePatterns.none { pattern -> segments.any { it == pattern } }
}🤖 Prompt for AI Agents
In mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/subagent/DomainDictAgent.kt
around lines 312 to 321, the current infrastructure filter uses substring
contains which incorrectly excludes packages like "commonMain" or "testDriven";
replace the substring check with segment-based matching (split package by '.' or
non-alphanumeric boundaries and compare whole segments) or use a regex that
matches patterns only as full segments (e.g. start/period before and period/end
after), so only exact package segments like "test", "config", "util" are
filtered while preserving names that merely contain those substrings.
| } catch (e: Exception) { | ||
| val elapsed = Clock.System.now().toEpochMilliseconds() - startTime | ||
| logger.error { "❌ [LLM] Stream error after ${elapsed}ms - chunks: $chunkCount, error: ${e.message}" } | ||
| throw e | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# First, locate and examine the file under review
fd -t f "KoogLLMService.kt"Repository: unit-mesh/auto-dev
Length of output: 126
🏁 Script executed:
#!/bin/bash
# Read the file to see the actual code, imports, and logging setup
wc -l mpp-core/src/commonMain/kotlin/cc/unitmesh/llm/KoogLLMService.ktRepository: unit-mesh/auto-dev
Length of output: 130
🏁 Script executed:
#!/bin/bash
# Read the entire file to see logging setup, imports, and the code in question
cat -n mpp-core/src/commonMain/kotlin/cc/unitmesh/llm/KoogLLMService.ktRepository: unit-mesh/auto-dev
Length of output: 11784
🏁 Script executed:
#!/bin/bash
# Search for the getLogger definition to understand the logging framework
rg -n "fun getLogger" --type=ktRepository: unit-mesh/auto-dev
Length of output: 88
🏁 Script executed:
#!/bin/bash
# Search for getLogger definition
rg -n "fun getLogger" --type=kotlinRepository: unit-mesh/auto-dev
Length of output: 333
🏁 Script executed:
#!/bin/bash
# Read the logging implementation files
echo "=== AutoDevLogger.kt ===" && cat -n mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/logging/AutoDevLogger.kt && \
echo -e "\n=== LoggingInitializer.kt ===" && cat -n mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/logging/LoggingInitializer.ktRepository: unit-mesh/auto-dev
Length of output: 7449
🏁 Script executed:
#!/bin/bash
# Check if CancellationException is used elsewhere in the codebase
rg -n "CancellationException" --type=kotlin -C2Repository: unit-mesh/auto-dev
Length of output: 6009
🏁 Script executed:
#!/bin/bash
# Check how other code in the codebase handles CancellationException in flow contexts
rg -n "\.collect" mpp-core/src/commonMain/kotlin -A5 -B5 | head -100Repository: unit-mesh/auto-dev
Length of output: 10633
🏁 Script executed:
#!/bin/bash
# Check imports in files that catch CancellationException
echo "=== RemoteCodingAgentViewModel.kt imports ===" && \
head -30 mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/remote/RemoteCodingAgentViewModel.kt && \
echo -e "\n=== DomainDictAgent.kt around CancellationException ===" && \
sed -n '240,250p' mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/subagent/DomainDictAgent.ktRepository: unit-mesh/auto-dev
Length of output: 1596
🏁 Script executed:
#!/bin/bash
# Search for logger.error usage with throwable in codebase
rg -n "logger\.error\(" mpp-core/src/commonMain/kotlin -A2 -B2 | head -80Repository: unit-mesh/auto-dev
Length of output: 8519
Based on my verification of the codebase, the review comment is accurate and actionable. Here are my findings:
-
Logging Framework: The codebase uses
kotlin-logging(io.github.oshai.kotlinlogging), which supports the APIlogger.error(throwable) { message }. This pattern is already used extensively in files likeDocumentRegistry.kt,DomainDictService.kt, andCodeReviewAgentExecutor.kt. -
CancellationException Handling: The codebase already follows the pattern of catching
CancellationExceptionseparately in multiple places (e.g.,RemoteCodingAgentViewModel.kt:164,DomainDictAgent.kt:244), confirming this is an established practice. -
Flow Context: The code uses
.cancellable()on the flow (line 72), which meanscollect()will throwCancellationExceptionon cancellation—making the special case handling particularly relevant. -
Imports: The file already imports
kotlinx.coroutines.flow.*(line 17-20), soCancellationExceptionwill be available via the coroutines star import.
Improve error logging and distinguish cancellations from real errors
The catch block (lines 111-115) logs only e.message without the throwable, losing critical stack trace information. Additionally, it treats all exceptions uniformly, which masks cancellations:
logger.error { "❌ [LLM] Stream error after ${elapsed}ms - chunks: $chunkCount, error: ${e.message}" }Two improvements:
- Log the stack trace using kotlin-logging's throwable parameter:
- logger.error { "❌ [LLM] Stream error after ${elapsed}ms - chunks: $chunkCount, error: ${e.message}" }
+ logger.error(e) { "[LLM] Stream error after ${elapsed}ms - chunks: $chunkCount" }- Treat
CancellationExceptionas non-error (e.g., user navigates away):
- } catch (e: Exception) {
- val elapsed = Clock.System.now().toEpochMilliseconds() - startTime
- logger.error { "❌ [LLM] Stream error after ${elapsed}ms - chunks: $chunkCount, error: ${e.message}" }
- throw e
- }
+ } catch (e: Exception) {
+ val elapsed = Clock.System.now().toEpochMilliseconds() - startTime
+ if (e is CancellationException) {
+ logger.info { "[LLM] Stream cancelled after ${elapsed}ms - chunks: $chunkCount" }
+ } else {
+ logger.error(e) { "[LLM] Stream error after ${elapsed}ms - chunks: $chunkCount" }
+ }
+ throw e
+ }CancellationException will be available from the existing kotlinx.coroutines.* imports.
🤖 Prompt for AI Agents
In mpp-core/src/commonMain/kotlin/cc/unitmesh/llm/KoogLLMService.kt around lines
111-115, the catch block logs only e.message and treats CancellationException
like a real error, losing stack traces and misclassifying cancellations; change
the catch to handle CancellationException separately by rethrowing it
(optionally log at debug/info), and for all other exceptions call
logger.error(e) { "❌ [LLM] Stream error after ${elapsed}ms - chunks:
$chunkCount" } so the throwable and stack trace are recorded; no new imports
should be needed because kotlinx.coroutines is already available.
|
augment review |
- Change maxIterations default expectation from 7 to 1 - Update schema example test to check for focusArea instead of userQuery - Remove tests for deprecated Deep Research classes
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
mpp-core/src/commonTest/kotlin/cc/unitmesh/agent/subagent/DomainDictAgentTest.kt (1)
82-87: Schema example assertion now tracksfocusAreafieldChecking for
"focusArea"in the example usage keeps the test aligned with the updated schema. Optionally, ifuserQueryis still part of the example payload, you could also assert its presence to catch accidental removal.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
mpp-core/src/commonTest/kotlin/cc/unitmesh/agent/subagent/DomainDictAgentTest.kt(3 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{kt,kts}
📄 CodeRabbit inference engine (AGENTS.md)
Use
expect/actualfor platform-specific code in Kotlin Multiplatform (e.g., file I/O on JVM/JS/Wasm)
Files:
mpp-core/src/commonTest/kotlin/cc/unitmesh/agent/subagent/DomainDictAgentTest.kt
**/*.{kt,css,ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
DO NOT hardcode colors (e.g.,
Color(0xFF...)or#hex). Always use design tokens for consistency across platforms
Files:
mpp-core/src/commonTest/kotlin/cc/unitmesh/agent/subagent/DomainDictAgentTest.kt
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
- GitHub Check: Test mpp-core (KMP)
- GitHub Check: Build (241)
- GitHub Check: Build (223)
🔇 Additional comments (2)
mpp-core/src/commonTest/kotlin/cc/unitmesh/agent/subagent/DomainDictAgentTest.kt (2)
7-10: Doc comment accurately narrows test scopeClarifying that this suite targets DomainDictAgent data classes matches the trimmed test surface and keeps expectations clear.
27-37: DefaultmaxIterationsexpectation updated correctlyAsserting
maxIterations == 1for the default case encodes the new behavior in tests and keeps regressions visible if the constructor default changes again.
|
augment review |
Summary
Optimize the Domain Dictionary generation process for better performance and more accurate business term extraction.
Changes
Performance Improvements
LLM Logging
KoogLLMService.kt:Filter Simplification
Before: Overly aggressive filtering blocked many potentially business-relevant terms
After: Keep only pure technical/infrastructure terms:
impl,util,helper,abstract,interfacetest,spec,mock,stub,fakegradle,build,indexPsiElement,JBColor,JPanel, etc.Let AI decide business relevance for terms like
agent,chat,service,handler, etc.Test Results
After optimization:
Related Files
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/subagent/DomainDictAgent.ktmpp-core/src/commonMain/kotlin/cc/unitmesh/llm/KoogLLMService.ktPull Request opened by Augment Code with guidance from the PR author
Summary by CodeRabbit
New Features
Improvements
Tests
✏️ Tip: You can customize this high-level summary in your review settings.