Token Box Model: Context Algebra and Deterministic Layout for LLMs
Status (March 2026): The normative Token Box Model is defined in §11 of the FACET v2.1.3 specification. All compliant implementations MUST follow this algorithm when performing context layout. Deviation from the algorithm constitutes a conformance violation.
There is a class of engineering decisions that seem obvious in retrospect — but only because someone spent enough time asking the right question. Not "how to truncate a prompt better," but "what is context, actually, from a systems engineering perspective?"
The answer I arrived at can be stated precisely: context is a finite resource with a distribution algebra. Not a string. Not a list of chunks. Not "whatever fits in the window." A resource — with a budget, invariants, priorities, and formal behavioral guarantees under overflow.
The Token Box Model is the formalization of this answer as a deterministic layout algorithm, embedded in Phase 4 of FACET execution.
Diagnosis: Why Existing Approaches Are Broken
Before talking about the solution, it is worth honestly stating what is broken. Because most teams do not notice the problem — until it manifests in production at 3 AM.
Problem 1: Limits Are Applied Too Late
In a typical LLM pipeline, the process looks like this:
assemble string → send to provider → receive 413 error
The prompt is already assembled. The API call money is spent (or reserved). The error is somewhere in an HTTP response. No guarantees about what was truncated.
This is an architectural anti-pattern: validating constraints after, not before, executing an expensive operation.
Problem 2: Truncation Is Non-Deterministic and Opaque
If a provider or middleware layer truncates the context — the developer usually does not know. The result: silent degradation of model behavior. The system prompt might have been cut in half. A critical instruction — removed. But the model responded to something anyway, and the logs show 200 OK.
Silent deletion of critical instructions is not an error in the logs. It is an error in the product.
Problem 3: Dependency on the Provider's Tokenizer
Different models use different tokenizers. gpt-4o and claude-3-5-sonnet tokenize the same string differently. This means: a system that "fits" with one provider silently overflows with another. Migrating between providers becomes a guessing game.
Problem 4: No Formal Priority Order
When there is not enough space — what gets dropped? Conversation history? Few-shot examples? The system prompt? Every team invents their own heuristic, which is:
- undocumented
- untested
- behaves differently in edge cases
- not reproducible across runs
The result: system behavior under context pressure is defined not by an engineering decision, but by implementation accident.
Reframing: Context as a Financial Budget
Let me offer an analogy I find most precise.
Imagine a corporate quarterly budget. It has:
- A total limit (token budget)
- Protected line items (salaries, rent — cannot be cut to zero)
- Flexible line items (travel, marketing — can be reduced by priority)
- A formal algorithm for decision-making under deficit
Nobody manages a company budget by "sum up all expenses and see what happens." Protected items first. Then flexible, by priority. If protected items exceed the limit — that is a crisis that needs to be surfaced immediately.
The Token Box Model applies this same logic to LLM context. This is not a metaphor — it is a literal architecture.
The Unit of Measurement: FACET Units vs. Provider Tokens
The first foundational decision in Token Box Model is the choice of measurement unit.
FACET v2.1.3 specification, §11.1:
Layout MUST measure content in FACET Units:
facet_units(s) = byte_length(UTF-8(NFC+LF normalized s))
FACET Units are bytes of the UTF-8 normalized string. Not tokens.
Why not tokens? Because tokens are an artifact of a specific tokenizer from a specific provider. They:
- vary from model to model
- can change between versions of the same model
- require calling a tokenizer (additional dependency)
- make the layout algorithm non-portable
FACET Units are deterministic by definition. One string always produces one byte count. Regardless of provider. Regardless of model version. Regardless of locale and environment.
facet_units("Привет, мир!") = 23 // UTF-8, Cyrillic — 2 bytes per char
facet_units("Hello, world!") = 13 // ASCII — 1 byte per char
facet_units("你好") = 6 // CJK — 3 bytes per char
Provider token counts may appear in telemetry — but they MUST NOT affect normative layout. This is a principle: the layout algorithm depends on zero external services.
Section Architecture
The second key element is the structural unit of context. In Token Box Model, this is a Section.
Each message block (@system, @user, @assistant) produces exactly one Section during layout. A Section is not just content. It is content plus a set of formal layout constraints.
Section Fields
| Field | Type | Default | Semantics |
|---|---|---|---|
id |
string | auto-derived | Section identifier |
priority |
int | 500 | Compression order (lower = compressed first) |
min |
int | 0 | Minimum size in FACET Units |
grow |
float | 0 | Weight for expansion when space is available |
shrink |
float | 0 | Weight for compression when over budget |
strategy |
lens pipeline | none | Compression strategy |
content |
string | required | Text content |
Automatic ID Derivation
If id is not explicitly set, the implementation MUST derive it deterministically (§11.2.1 of the specification):
system → "system#1", "system#2", ...
user → "user#1", "user#2", ...
assistant → "assistant#1", "assistant#2", ...
Numbering follows appearance order in the Resolved Source Form. This provides stable section identity across runs.
Critical Sections: The Invariant of Inviolability
A Section is Critical if shrink == 0.
@system
priority: 1000
shrink: 0 // ← Critical section. Inviolable.
content: "You are a payment processing assistant. Never skip validation steps."
Critical sections form the lower bound of the budget. If their combined size exceeds the budget — execution MUST immediately fail with error F901 (§11.3 of the specification). No attempts to "fit it somehow." No silent degradation.
This is a philosophically important decision: an explicit failure is better than an implicit compromise with safety.
The Deterministic Packing Algorithm
The heart of Token Box Model is a five-step deterministic layout algorithm (§11.3 of the specification). "Deterministic" here means: given identical inputs — byte-for-byte identical output on any conformant implementation.
Let: B = budget in FACET Units, size[i] = facet_units(content[i]).
Step 1: Critical Load Calculation
FixedLoad = Σ size[i] for all i where shrink[i] == 0
If FixedLoad > B → F901, stop. Execution terminates in Phase 4, before a single token is spent on a provider call.
Step 2: Total Fit Check
TotalLoad = Σ size[i] for all sections
If TotalLoad <= B → all sections fit, preserve order, proceed to Phase 5. No unnecessary operations.
Step 3: Flexible Section Sort
Flexible sections: Flex = { i | shrink[i] > 0 }.
Sort by stable composite key:
priorityascending (lower priority = compressed first)shrinkdescending (higher weight = compressed more aggressively)- Original position in the section array ascending (stable tiebreaker)
Key property: this sort is deterministic. There is not a single source of non-determinism — no randomness, no locale dependence, no dependence on network packet arrival order.
Step 4: Iterative Compression and Truncation
Iterate Flex in sorted order while TotalLoad > B:
4a. Apply strategy:
If the section has a strategy (lens pipeline) — apply it to content[i]. Recompute size[i]. In Pure Mode — Level-0 lenses only (deterministic, no I/O), otherwise F801.
4b. Truncate to min:
If still over budget after strategy — truncate content[i] to min bytes.
Truncation MUST be performed from the end. Truncation MUST NOT split UTF-8 sequences.
4c. Drop section:
If size[i] == min and still over budget — drop the entire section (it is non-critical).
Step 5: Final Ordering
After layout, section order in Canonical JSON is mandated by the specification (§18.1.2):
All @system → in Resolved Source Form order
All @user → in Resolved Source Form order
All @assistant → in Resolved Source Form order
The layout algorithm NEVER reorders sections. It only removes or compresses sections within their role group.
Concrete Example: A System with Three Sections
Consider a real scenario — a RAG agent with a system prompt, conversation history, and retrieved documents.
@context
budget: 8000
defaults:
priority: 500
shrink: 0
@system
id: "core-instructions"
priority: 1000
shrink: 0 // Critical. Never compressed.
content: $system_prompt
@user
id: "chat-history"
priority: 200 // Low priority — compressed first
shrink: 1.0
min: 500 // Minimum — last user message
strategy: $history |> trim() |> summarize_history()
content: $chat_history
@user
id: "rag-documents"
priority: 400
shrink: 0.7
min: 1000 // Minimum — at least one document
strategy: $docs |> sort_by("relevance", desc=true) |> take_top_k(k=3)
content: $retrieved_docs
@user
id: "user-query"
priority: 900 // High priority — compressed last among flexible
shrink: 0.1
min: 0
content: $current_query
Overflow scenario:
Budget = 8000 FACET Units, sizes:
core-instructions: 1200 (critical,shrink=0)chat-history: 3500rag-documents: 4200user-query: 150- Total: 9050 > 8000
Algorithm:
FixedLoad = 1200(critical only).1200 < 8000— continue.TotalLoad = 9050 > 8000— compression needed. Deficit: 1050 units.- Sort flexible:
chat-history(priority=200) →rag-documents(priority=400) →user-query(priority=900). - Start with
chat-history(priority=200):- Apply
summarize_history()→ compresses to 1800 units (-1700) - Recalculate:
TotalLoad = 9050 - 1700 = 7350 < 8000→ stop, budget satisfied
- Apply
rag-documentsanduser-query— left untouched.
Result: core-instructions (1200) + chat-history (1800, compressed) + rag-documents (4200) + user-query (150) = 7350 units. Fits within budget of 8000. Critical section untouched.
This result is reproducible. Run again with the same inputs — get byte-for-byte the same context.
Integration in FACET Execution: Phase 4
Token Box Model is not a standalone tool. It is Phase 4 in the five-phase FACET execution model (§10).
Phase 1: Resolution — normalization, imports, merge
Phase 2: Type Checking — types, schemas, contracts
Phase 3: R-DAG — reactive variable computation
Phase 4: Layout (TBM) — Token Box Model, context finalization ← here
Phase 5: Render — Canonical JSON, provider payload
Phase 4 receives computed messages and section metadata from Phase 3 as input, and outputs a finalized ordered list of sections that fit within the budget.
Critically: Phase 4 completes before Phase 5. Phase 5 is Canonical JSON generation and the provider call. This means: if Token Box Model detects critical section overflow (F901) — the provider never receives the request. No money spent. No latent failures. Clean, early, explicit failure.
Compression Strategies: Lenses as Plug-in Compressors
The strategy field in a Section accepts a lens pipeline — a sequence of deterministic content transformations.
@user
id: "conversation"
shrink: 1.0
strategy: $content |> trim() |> lowercase() |> json(indent=0)
content: $dialogue
In Pure Mode (deterministic, no external I/O) — only Level-0 lenses:
trim() — strip whitespace
lowercase() — lowercase (locale-independent)
replace(p, r) — regex replacement (RE2-safe subset)
indent(level) — change indentation
json(indent=0) — compact JSON (removes formatting)
split(sep) — split string
Every lens pipeline MUST (§9.8 of the specification):
- be deterministic
- be idempotent on identical input
- be total — not throw on any valid input
- not depend on locale, time, environment variables, filesystem, or network
These are not arbitrary functions. They are algebraic operators over strings with proven properties. Only such operators may participate in deterministic layout.
In Execution Mode (exec), Level-1 lenses are available (with caching) — for example, external summarizer services. But their results are cached by a deterministic key (Appendix C of the specification), so a repeated request yields the same result.
What It Closes: An Inventory of Solved Problems
Token Box Model is not "another way to manage context." It is the formal closure of specific error classes.
✓ Closed: Non-deterministic truncation
Before: different runs → different context (depends on string sizes, concatenation order, provider behavior).
After: deterministic algorithm with deterministic sort. Byte-for-byte identity across all conformant implementations.
✓ Closed: Silent deletion of critical instructions
Before: the system prompt can be truncated with no signal. The model degrades silently.
After: shrink=0 — a formal inviolability contract. Any attempt to violate it → F901, halt.
✓ Closed: Provider tokenizer dependency
Before: gpt-4o fits, claude-3.5 does not. Unpredictable behavior when switching providers.
After: FACET Units = UTF-8 bytes. The same result regardless of provider. Provider tokens — telemetry only.
✓ Closed: Late failure discovery
Before: overflow → provider error → after the request executes.
After: Phase 4 executes before Phase 5. F901 = early, explicit, free failure.
✓ Closed: Untestable behavior under context pressure
Before: the edge case "what happens when context is full" — an unspoken heuristic.
After: behavior is fully specified. Testable via @test with explicit asserts on canonical.messages and telemetry.budget_units.
@test "history-compression-on-overflow"
vars:
chat_history: "..." // 3500 bytes
retrieved_docs: "..." // 4200 bytes
current_query: "Explain the payment flow"
assert:
: canonical.messages | length == 4
: telemetry.budget_units <= 8000
: canonical.messages[0].content contains "payment processing assistant"
✓ Closed: Non-cacheable contexts
Before: context is a string that gets reassembled slightly differently each time. Cache is invalid.
After: deterministic context is cacheable by document hash (§18.3 of the specification). Identical context = identical hash = valid cache.
The Innovation: What Distinguishes Token Box Model
Context management has been discussed since the earliest days of LLMs. Libraries, patterns, and best practices exist. What, then, is the innovation?
The innovation is in the level of formalization and its position in the stack.
Most existing solutions operate at the level of "smart helpers": a truncate_to_fit() function, a ContextManager class, a smart_trim utility. This is an application layer on top of an informal foundation. Every team invents their own version, incompatible with others.
Token Box Model is a normative layout standard. It is specified in §11 of a document with REC-PROD status. An implementation that violates the algorithm is not FACET-conformant. This is not a recommendation. It is a contract.
Specific technical innovations:
1. A provider-independent unit of measurement. Nobody had previously formalized a "provider-agnostic" unit for context budgeting. FACET Units are the first normative specification of such a unit.
2. A two-tier section model (Critical / Flexible). Formally separating content into "protected" and "flexible" with explicit semantics for each — a new primitive for context management.
3. Deterministic sort with position tiebreaker. Using position in the source document as a stable tiebreaker — an engineering choice that ensures reproducibility even with equal priority/shrink values.
4. Compression strategies as Level-0 lenses. Connecting compressors through a system of typed deterministic functions — an algebraic architecture, not an ad hoc callback. Every compressor has a formal signature verifiable in Phase 2.
5. Early failure as a first-class citizen. F901 in Phase 4 is not an error to suppress. It is a normative boundary: the system refuses to violate critical invariants even at the cost of cancelling the request. This is a position.
The Philosophical Foundation: Determinism as an Engineering Value
Let me close with what, in truth, started the development of FACET.
LLMs are probabilistic systems. Their outputs are non-deterministic by definition. This is good: stochasticity is precisely what generates useful variability.
But the infrastructure around LLMs does not need to be stochastic. And it should not be. The context we pass to the model is our contribution to the dialogue. We control it completely. If we cannot guarantee that a critical instruction reaches the model in the form we wrote it — we do not control the system.
Token Box Model is a way to reclaim that control. Not over the model. Over the context.
Context is not text. Context is a resource with algebra.
Once this axiom is accepted — everything else follows from it with necessity: units of measurement, critical sections, deterministic sort, early failure, cacheability. This is not a set of features. These are consequences of a single principle.
Emil Rokossovskiy — Author of the FACET Specification. Version v2.1.3 published February 19, 2026.