16 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.
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:
DELETE FROM llm_context WHERE ts < now() - interval '30 days';
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 thatllm.joinSystemtrims (strings.TrimSpace), drops when empty, and joins with blank lines ("\n\n").MeasureContextapplies the exact same trim, drop-empty, and"\n\n"join rules per slice.- When
DynamicBoundary > 0,Systemis split atb = min(DynamicBoundary, len(System)):System[:b]is measured intosystem_static_bytesandSystem[b:]intosystem_dynamic_bytes. - 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 a surgical
workerprefix split (ARTEX_CACHE_PREFIX); verifyplannercross-round cache behavior andARTEX_COMPACTION_MEMOwith liveARTEX_CONTEXT_TELEMETRY=1data before changing them. -
Actual system-prompt volatility by lane (built-in prompts):
system_dynamicis 0.0% across all lanes today becauseagent/deferred.gosetsDynamicBoundary = 0(no global deferred MCP) orlen(system)(everything before the boundary). Auditing the built-in templates and assembly inagent/worker.goandagent/planner.goshows what actually varies:Lane Stable per task Volatile per intent / round workerBase workerDefaultTmpl(ProxyAddr,DataDir),untrustedContentTail,workerTrafficBlock,noiseProfileBlock,frameLessonsBlock(task-level),constraintBlock(task-level, stable unless operator edits constraints),def.FindingGuidance,<available-deferred-tools>workerArtifactSpec(runDir)(tasks/<id>/i<intentID>),renderIntentTask(intent), intent target-assets JSON block, closing launch instructionplannerplannerSystem(goal,dataDir,workDir/taskDir,untrustedDataRules,artifactSpec(taskDir),noiseProfileBlock),frameLessonsBlock,def.FindingGuidance,<available-deferred-tools>constraintBlock(ts)is recomputed each round (stable unless operator changes constraints; situational graph overview already lives in the user turn)Custom prompts only — {{.Now}}(agent/prompt.go:46, 1-second resolution). Built-in templates do not reference{{.Now}}(Go'stext/templateignores the unusedNowfield); it only affects operator-customized prompts that explicitly use{{.Now}}. -
Expected gain:
workerturn-1 cache reuse (real, code-backed): TodayworkerArtifactSpec(runDir)is concatenated into the singlesysBodybeforenoiseProfileBlock, lessons, constraints,renderIntentTask(intent), and the target-assets block, so every sibling worker spawn busts the prompt cache fromrunDironward. The minimalARTEX_CACHE_PREFIX=1split shipped in Phase C places the prefix beforeworkerArtifactSpec(runDir)(body+untrustedContentTail+workerTrafficBlock) beforeDynamicBoundary = 1(system_static) and leaves everything fromworkerArtifactSpec(runDir)onward (workerArtifactSpec(runDir)+noiseProfileBlock+ lessons + constraints +renderIntentTask(intent)+ target assets JSON + closing launch line +def.FindingGuidance+<available-deferred-tools>) afterDynamicBoundary = 1(system_dynamic) in its exact original order. This keeps the visible joined prompt byte-identical and keeps the intent protected from compaction insideSystemwhile allowing sibling workers in the same task to share the cachedsystem_static + toolsprefix on turn 1 (in the fixture,system + toolsis 36.0% of aggregate worker input and ~76.8% of turn-1 input, 21.5 KiB / 28.0 KiB, though the fixture does not isolate the per-intent suffix; measure the exact shareable prefix live). Moving the remaining task-stable blocks (noiseProfileBlock, lessons, constraints,def.FindingGuidance,<available-deferred-tools>) before the boundary would require reordering sections relative toworkerArtifactSpec(runDir)and is left as a potential future optimization outside this PR.plannercross-round cache ratio (unverified hypothesis): The fixture above assumed a turn-1 cache miss on every planner round (yielding 48.5%), which is not demonstrated by the built-in code becauseplannerSystemis stable per task. Real cross-round misses could still happen from provider cache TTL expiry between rounds, constraint edits, or tool-RAG tool-list churn — treat any planner cache gain as a hypothesis to measure withARTEX_CONTEXT_TELEMETRY=1on real tasks rather than a proven savings.
-
Risk: Low for the
workerARTEX_CACHE_PREFIXsplit (pure boundary split usingnorma's existingDynamicBoundarycontract, with zero text reordering; custom prompts using{{.Now}}stay an explicit edge case). Medium forARTEX_COMPACTION_MEMO(injecting compaction memos alters model reasoning continuity and only pays off on tasks that repeatedly trigger compaction — verify with liveARTEX_CONTEXT_TELEMETRY=1data first).
Phase C: Worker Cache Prefix Split (ARTEX_CACHE_PREFIX=1)
ARTEX_CACHE_PREFIX=1 (accepts 1, true, on, yes, case-insensitive; off by default) enables a minimal, zero-reordering system-prompt split for the worker lane only so sibling workers in the same task share a cacheable static prefix without changing the text visible to the model:
- Static segment (
System[0], beforeDynamicBoundary = 1):body + untrustedContentTail + workerTrafficBlock. - Dynamic segment (
System[1], afterDynamicBoundary = 1):workerArtifactSpec(runDir) + noiseProfileBlock + lessons + constraints + renderIntentTask(intent) + target assets + launch instruction + FindingGuidance + <available-deferred-tools>(in exact original order). The leading"\n\n"fromworkerArtifactSpecis absorbed because providers join segments with"\n\n", keepingstrings.Join(System, "\n\n")byte-identical to the legacy unsplit prompt. - Unchanged: When
ARTEX_CACHE_PREFIXis unset/false, worker segments andDynamicBoundaryare byte-identical to the legacy layout.planner,mainagent,chat, andgoalsare completely unchanged regardless of the flag. - Custom prompts caveat: The split covers only the built-in suffix starting at
workerArtifactSpec(runDir). If an operator customizes theworkerprompt in the database to include{{.Now}}(1-second resolution), that timestamp remains insideSystem[0]and will keep the static prefix volatile across spawns. - Measuring live impact: Enable both
ARTEX_CONTEXT_TELEMETRY=1andARTEX_CACHE_PREFIX=1on real tasks and comparesystem_static/system_dynamicshares andcache_read_ratioviaGET /api/llm/context/summary.