fix(llmrec): match norma joinSystem trim/drop-empty semantics and document retention

This commit is contained in:
BaaRai
2026-11-20 18:43:03 +01:00
parent 4841016892
commit dd5c371ead
3 changed files with 74 additions and 13 deletions
+10 -2
View File
@@ -14,6 +14,14 @@ This phase measures context composition without changing any prompt, compaction
Telemetry runs independently of `llm_record` (`recordBodies`): enabling `ARTEX_CONTEXT_TELEMETRY=1` works even when full request/response body recording is disabled, and stores **no prompt, tool, or message content** — only byte lengths, counts, token usage, and metadata.
### Stopping, retention, and write cost
When `ARTEX_CONTEXT_TELEMETRY=1` is active, each LLM call incurs one lightweight `INSERT` into `llm_context` (~200 bytes/row plus index entries, no bodies), so the table grows by one row per completion call. Unset `ARTEX_CONTEXT_TELEMETRY` (and restart) once the measurement campaign is finished to stop all writes and sizing work, or purge old rows periodically:
```sql
DELETE FROM llm_context WHERE ts < now() - interval '30 days';
```
---
## Measurement Semantics (`llmrec.MeasureContext`)
@@ -21,8 +29,8 @@ Telemetry runs independently of `llm_record` (`recordBodies`): enabling `ARTEX_C
Every enabled `Stream` and `Complete` call measures the assembled `llm.CompletionRequest` right before it is handed to the inner provider, and persists one row to `llm_context` (migration `0009_llm_context.sql`) on completion or error:
- **`system_static_bytes` & `system_dynamic_bytes`**:
- `norma`'s `CompletionRequest.System` is a slice of segments joined with blank lines (`"\n\n"`).
- When `DynamicBoundary > 0`, `System` is split at `b = min(DynamicBoundary, len(System))`: `System[:b]` is measured into `system_static_bytes` and `System[b:]` into `system_dynamic_bytes` (each joined with `"\n\n"`).
- `norma`'s `CompletionRequest.System` is a slice of segments that `llm.joinSystem` trims (`strings.TrimSpace`), drops when empty, and joins with blank lines (`"\n\n"`). `MeasureContext` applies the exact same trim, drop-empty, and `"\n\n"` join rules per slice.
- When `DynamicBoundary > 0`, `System` is split at `b = min(DynamicBoundary, len(System))`: `System[:b]` is measured into `system_static_bytes` and `System[b:]` into `system_dynamic_bytes`.
- When `DynamicBoundary <= 0`, there is no provider-visible cache split, so the entire `System` slice is measured as one block in `system_static_bytes` and `system_dynamic_bytes` is `0`.
- **Why this choice**: `agent/deferred.go` returns `boundary = 0` when no global deferred-MCP block exists and `boundary = len(system)` when one does. Placing the single unsplit block in `system_static_bytes` ensures `system_static_bytes + system_dynamic_bytes` always equals total system bytes and `system_dynamic_bytes > 0` strictly signals a dynamic suffix placed after a cache breakpoint.
- **`tool_count` & `tools_bytes`**: `len(req.Tools)` and `len(json.Marshal(req.Tools))` (`0` when no tools). Go's `encoding/json` sorts map keys deterministically.
+17 -11
View File
@@ -46,10 +46,11 @@ type ContextMetrics struct {
//
// - System: when DynamicBoundary > 0, req.System is split at
// min(DynamicBoundary, len(req.System)) into SystemStaticBytes ([:b]) and
// SystemDynamicBytes ([b:]), joining segments within each slice with "\n\n"
// to match norma's prompt assembly. When DynamicBoundary <= 0, the whole
// req.System is measured as a single static block (SystemStaticBytes) and
// SystemDynamicBytes is 0.
// SystemDynamicBytes ([b:]). Within each slice, each segment is trimmed with
// strings.TrimSpace, empty segments are dropped, and remaining segments are
// joined with "\n\n", matching norma's llm.joinSystem. When
// DynamicBoundary <= 0, the whole req.System is measured as a single static
// block (SystemStaticBytes) and SystemDynamicBytes is 0.
// - Tools: ToolCount = len(req.Tools); ToolsBytes = len(json.Marshal(req.Tools))
// (0 when no tools). Go's encoding/json sorts map keys deterministically.
// - Messages: MessageCount = len(req.Messages). Each message is measured by
@@ -114,18 +115,23 @@ func MeasureContext(req llm.CompletionRequest) ContextMetrics {
return m
}
// joinedSegmentBytes returns the byte length of segs joined with "\n\n"
// without allocating a joined string.
// joinedSegmentBytes returns the byte length of segs after trimming whitespace
// from each segment, dropping empty segments, and joining the remaining ones
// with "\n\n" — matching norma's llm.joinSystem without allocating a joined
// string.
func joinedSegmentBytes(segs []string) int64 {
if len(segs) == 0 {
return 0
}
var total int64
for i, s := range segs {
if i > 0 {
nonEmpty := 0
for _, s := range segs {
s = strings.TrimSpace(s)
if s == "" {
continue
}
if nonEmpty > 0 {
total += 2 // "\n\n"
}
total += int64(len(s))
nonEmpty++
}
return total
}
+47
View File
@@ -149,6 +149,53 @@ func TestMeasureContextExactSizesAndBoundaryModes(t *testing.T) {
t.Fatalf("DynamicBoundary=5 system = (%d, %d), want (%d, 0)",
got3.SystemStaticBytes, got3.SystemDynamicBytes, len("AAA\n\nBBBB"))
}
// Case 4: whitespace-padded and empty segments match norma's llm.joinSystem
// (strings.TrimSpace per segment, drop empty, join remaining with "\n\n").
for _, tc := range []struct {
name string
segs []string
boundary int
wantStat int64
wantDyn int64
}{
{
name: "padded and empty unsplit",
segs: []string{" STATIC ", "", "\n", "TAIL\n\n"},
boundary: 0,
wantStat: int64(len("STATIC\n\nTAIL")),
wantDyn: 0,
},
{
name: "padded split at boundary 2",
segs: []string{" A ", " B ", " C "},
boundary: 2,
wantStat: int64(len("A\n\nB")),
wantDyn: int64(len("C")),
},
{
name: "only empty and whitespace",
segs: []string{"", " "},
boundary: 1,
wantStat: 0,
wantDyn: 0,
},
{
name: "empty segments around boundary",
segs: []string{" ", "HEAD ", "", "\t\n", " TAIL"},
boundary: 2,
wantStat: int64(len("HEAD")),
wantDyn: int64(len("TAIL")),
},
} {
t.Run(tc.name, func(t *testing.T) {
got := MeasureContext(llm.CompletionRequest{System: tc.segs, DynamicBoundary: tc.boundary})
if got.SystemStaticBytes != tc.wantStat || got.SystemDynamicBytes != tc.wantDyn {
t.Fatalf("MeasureContext(%q, b=%d) = (%d, %d), want (%d, %d)",
tc.segs, tc.boundary, got.SystemStaticBytes, got.SystemDynamicBytes, tc.wantStat, tc.wantDyn)
}
})
}
}
func TestContextTelemetryFlagOffAndOnPostgres(t *testing.T) {