11 KiB
LLM Context Size Telemetry (P3.5 Phase A)
ARTEX_CONTEXT_TELEMETRY=1 enables opt-in, size-only per-call telemetry for every llmrec Stream and Complete call. It is disabled by default: when off, no request sizing runs and no rows are written to PostgreSQL.
This phase measures context composition without changing any prompt, compaction policy, or model behavior, so Phases B (ARTEX_BOUNDED_CONTEXT) and C (ARTEX_CACHE_PREFIX / ARTEX_COMPACTION_MEMO) can be evaluated against real numbers first.
Configuration
| Environment variable | Values | Default |
|---|---|---|
ARTEX_CONTEXT_TELEMETRY |
1, true, on, yes (case-insensitive) |
off |
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.
Measurement Semantics (llmrec.MeasureContext)
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'sCompletionRequest.Systemis a slice of segments joined with blank lines ("\n\n").- When
DynamicBoundary > 0,Systemis split atb = min(DynamicBoundary, len(System)):System[:b]is measured intosystem_static_bytesandSystem[b:]intosystem_dynamic_bytes(each joined with"\n\n"). - When
DynamicBoundary <= 0, there is no provider-visible cache split, so the entireSystemslice is measured as one block insystem_static_bytesandsystem_dynamic_bytesis0. - Why this choice:
agent/deferred.goreturnsboundary = 0when no global deferred-MCP block exists andboundary = len(system)when one does. Placing the single unsplit block insystem_static_bytesensuressystem_static_bytes + system_dynamic_bytesalways equals total system bytes andsystem_dynamic_bytes > 0strictly signals a dynamic suffix placed after a cache breakpoint.
tool_count&tools_bytes:len(req.Tools)andlen(json.Marshal(req.Tools))(0when no tools). Go'sencoding/jsonsorts map keys deterministically.message_count,messages_user_bytes,messages_assistant_bytes,messages_other_bytes,last_message_bytes: eachllm.Messageis measured bylen(json.Marshal(msg))and accumulated by role (user,assistant, or other);last_message_bytesis the serialized byte size of the final message.tool_result_bytes: serialized byte length oftool_resultcontent blocks inside messages. Reported as an informational subset ofmessages_user_bytes(not added to the partition denominator, avoiding double counting).
Pro-rata token attribution
Rather than shipping per-provider tokenizers, each section's share of real input_tokens is computed per call by byte proportion:
total_bytes(call) = system_static_bytes + system_dynamic_bytes + tools_bytes
+ messages_user_bytes + messages_assistant_bytes + messages_other_bytes
share(section) = SUM(input_tokens * (section_bytes / total_bytes))
/ SUM(input_tokens) -- over calls with total_bytes > 0 and input_tokens > 0
The six partition shares sum to 1.0. cache_read_ratio = SUM(cache_read) / NULLIF(SUM(input_tokens), 0) (in ARTEX/Norma, input_tokens already includes cached tokens).
Querying & Aggregation
HTTP endpoint (admin JWT required, no UI in Phase A)
GET /api/llm/context/summary?days=30&top=20&task=<optional-task-id>
Returns enabled, by_worker_model (calls, totals, cache_read_ratio, input_p50/p90/p99/max, avg tool/message/last-message size, and pro-rata shares), and top_tasks ordered by total input_tokens.
Standalone SQL query (psql)
WITH base AS (
SELECT *,
(system_static_bytes + system_dynamic_bytes + tools_bytes
+ messages_user_bytes + messages_assistant_bytes + messages_other_bytes) AS total_bytes
FROM llm_context
WHERE ts >= now() - interval '30 days'
)
SELECT COALESCE(NULLIF(worker,''), '(unknown)') AS worker,
COALESCE(NULLIF(model,''), '(unknown)') AS model,
COUNT(*) AS calls,
SUM(input_tokens) AS input_tokens,
ROUND((SUM(cache_read)::numeric / NULLIF(SUM(input_tokens), 0))::numeric, 3) AS cache_read_ratio,
PERCENTILE_CONT(0.50) WITHIN GROUP (ORDER BY input_tokens) AS p50_input,
PERCENTILE_CONT(0.90) WITHIN GROUP (ORDER BY input_tokens) AS p90_input,
PERCENTILE_CONT(0.99) WITHIN GROUP (ORDER BY input_tokens) AS p99_input,
ROUND((SUM(CASE WHEN total_bytes > 0 AND input_tokens > 0 THEN input_tokens * (system_static_bytes::double precision / total_bytes) ELSE 0 END)
/ NULLIF(SUM(CASE WHEN total_bytes > 0 AND input_tokens > 0 THEN input_tokens::double precision ELSE 0 END), 0))::numeric, 3) AS share_sys_static,
ROUND((SUM(CASE WHEN total_bytes > 0 AND input_tokens > 0 THEN input_tokens * (system_dynamic_bytes::double precision / total_bytes) ELSE 0 END)
/ NULLIF(SUM(CASE WHEN total_bytes > 0 AND input_tokens > 0 THEN input_tokens::double precision ELSE 0 END), 0))::numeric, 3) AS share_sys_dynamic,
ROUND((SUM(CASE WHEN total_bytes > 0 AND input_tokens > 0 THEN input_tokens * (tools_bytes::double precision / total_bytes) ELSE 0 END)
/ NULLIF(SUM(CASE WHEN total_bytes > 0 AND input_tokens > 0 THEN input_tokens::double precision ELSE 0 END), 0))::numeric, 3) AS share_tools,
ROUND((SUM(CASE WHEN total_bytes > 0 AND input_tokens > 0 THEN input_tokens * (messages_user_bytes::double precision / total_bytes) ELSE 0 END)
/ NULLIF(SUM(CASE WHEN total_bytes > 0 AND input_tokens > 0 THEN input_tokens::double precision ELSE 0 END), 0))::numeric, 3) AS share_user,
ROUND((SUM(CASE WHEN total_bytes > 0 AND input_tokens > 0 THEN input_tokens * (tool_result_bytes::double precision / total_bytes) ELSE 0 END)
/ NULLIF(SUM(CASE WHEN total_bytes > 0 AND input_tokens > 0 THEN input_tokens::double precision ELSE 0 END), 0))::numeric, 3) AS share_tool_result_subset,
ROUND((SUM(CASE WHEN total_bytes > 0 AND input_tokens > 0 THEN input_tokens * (messages_assistant_bytes::double precision / total_bytes) ELSE 0 END)
/ NULLIF(SUM(CASE WHEN total_bytes > 0 AND input_tokens > 0 THEN input_tokens::double precision ELSE 0 END), 0))::numeric, 3) AS share_assistant
FROM base
GROUP BY 1, 2
ORDER BY input_tokens DESC;
Phase A Baseline Report & Recommendation on Phases B and C
Measurement scope note: No live production LLM run was executed in this local verification environment. The figures below come from the reproducible representative fixture in
db/llm_context_test.go(TestLLMContextRepresentativeFixtureReport), parameterized from ARTEX's actualplannerSystem(~12.5 KiB),workerSystem(~11 KiB), tool schema sets (14–16 tools, ~9–10.5 KiB), 5 planner rounds (2 turns each), and 2 worker intents (10 turns each with 3.5–8.5 KiB Bash/tool outputs), combined with a static audit ofagent/planner.go,agent/worker.go,agent/prompt.go, andagent/deferred.go. Operators should capture 3–5 real tasks withARTEX_CONTEXT_TELEMETRY=1before flipping Phases B or C on by default.
Representative Fixture Breakdown
| Lane / Model | Calls | Total Input | p50 / p90 / Max | Cache Read Ratio | sys_static |
sys_dynamic |
tools |
user (tool_result subset) |
assistant |
|---|---|---|---|---|---|---|---|---|---|
worker / claude-sonnet-4 |
20 | 299,000 | 15,075 / 21,535 / 22,525 | 84.9% | 18.4% | 0.0% | 17.6% | 57.3% (46.4%) |
6.8% |
planner / claude-sonnet-4 |
10 | 79,060 | 7,906 / 8,971 / 9,387 | 48.5% | 39.5% | 0.0% | 29.1% | 29.2% (0.7%) |
2.2% |
Explicit Recommendations
Phase B — Bounded Context (ARTEX_BOUNDED_CONTEXT)
- Recommendation: Proceed (opt-in first), highest ROI on deep
workerruns. - Expected gain: In the representative worker trajectory,
messages_useraccounts for 57.3% of total input tokens, withtool_resultoutputs alone representing 46.4% (and growing quadratically across turns on long Bash/scanner sessions). Bounding/compacting old tool outputs on workers (keeping recent turns verbatim and summarizing/truncating staletool_resultpayloads) targets the largest single token sink (realistic 25–45% input-token reduction on 10–30 turn workers, and lower p90/p99 latency). - Risk: Aggressive trimming of earlier tool outputs can drop credentials, endpoints, or exact error lines needed for exploit chaining or evidence binding, and mutating earlier messages inside a live multi-turn session invalidates the prompt cache prefix (turning cheap
cache_readturns into uncached re-prefills if triggered too frequently). Bound only at explicit compaction boundaries or spill largetool_resultbodies at insertion time before they enter the cached prefix.
Phase C — Cache Prefix Stabilization (ARTEX_CACHE_PREFIX / ARTEX_COMPACTION_MEMO)
- Recommendation: Proceed with high-confidence surgical prefix split (
ARTEX_CACHE_PREFIX); deferARTEX_COMPACTION_MEMOuntil live telemetry confirms compaction frequency. - Codebase finding & expected gain: Static inspection shows
system_dynamicis 0.0% across all lanes today becauseagent/deferred.gosetsDynamicBoundary = 0(no deferred MCP) orlen(system)(everything before the boundary), while volatile per-call / per-intent strings sit inside the static system prompt:{{.Now}}(agent/prompt.go:46,time.Now().Format("2006-01-02 15:04:05 MST"), changing every second) is rendered inside bothplannerSystemandworkerSystem.workerArtifactSpec(runDir)embeds the per-intenttasks/<id>/i<N>path insideworkerSystem.- Moving
{{.Now}},runDir, and per-round constraints/lessons afterDynamicBoundary(intosystem_dynamic) makes thesystem_static+toolsprefix (68.6% of planner input, 36.0% of worker turn-1 input) byte-identical across planner rounds and across sibling workers within the same task — lifting plannercache_read_ratiofrom ~48.5% toward ~75–85% and eliminating turn-1 cache misses on every worker spawn.
- Risk: Low for
ARTEX_CACHE_PREFIX(pure prompt-segment relocation usingnorma's existingDynamicBoundarycontract, though custom user-edited prompts containing{{.Now}}need a clean fallback). Medium forARTEX_COMPACTION_MEMO(injecting compaction memos alters model reasoning continuity and only pays off on tasks that actually hit compaction repeatedly — verify withARTEX_CONTEXT_TELEMETRY=1on real runs first).