Normalize typed synthetic duration and byte quantities with dimension checks; reject bare numbers and incompatible arithmetic.
A valid number can represent the wrong quantity
Two tools return durations for a synthetic worker experiment. One reports 250 milliseconds; the other reports 1.5 seconds. An agent adds the numbers and reports 251.5 seconds. Both inputs were valid numeric values, the addition was syntactically correct, and a JSON schema that checked only number would accept the result. The missing contract is the quantity represented by each number.
The same problem appears with bytes versus kibibytes, counts versus rates, and absolute timestamps versus elapsed durations. Language models can often infer the intended unit from surrounding prose, but an execution boundary should not depend on that inference. Carry a machine-readable unit or a contractually fixed unit with every numeric quantity, then normalize it before arithmetic. Keep the model's explanatory language separate from the adapter's dimensional rules.
This guide uses only synthetic time and data-size quantities. Its arithmetic is an offline teaching calculation, not measured latency, throughput or memory consumption. The objective is to make incompatible operations fail before a plausible-looking number reaches a plan, a report or another tool. The small unit vocabulary is deliberate: a constrained registry is easier to inspect than a parser accepting arbitrary expressions.
Separate values, units and dimensions
A value is the magnitude supplied by a tool. A unit gives that magnitude a scale, such as seconds or milliseconds. A dimension groups compatible units, such as time. The pair 250 ms and 1.5 s can be added after conversion because their dimensions agree. A duration and a byte count cannot be added, even if their numeric representations happen to be identical.
Choose canonical units at the application boundary. In the example, time becomes seconds and data size becomes bytes. Preserve the original value and unit in the evidence record when they help explain a conversion. The normalized quantity is used for arithmetic; the original pair is used for traceability. Avoid converting back and forth at each model turn, which introduces repeated rounding and makes it harder to establish what was actually computed.
RFC 8428 provides a useful primary example of a data format that represents measurement values and units explicitly. The contract below is an original, much smaller application format; it is not a SenML implementation and does not claim interoperability with that standard. Its lesson is the separation of a number from the meaning needed to interpret it.
Normalize a constrained quantity vocabulary
Use exact decimal inputs for this synthetic example so conversion behavior is easy to inspect. Numeric strings preserve the decimal value the fixture specifies. The function rejects non-finite values, unsupported units and negative magnitudes. That nonnegative rule is specific to these duration and size fields; it would be inappropriate for every kind of physical quantity. A general library must make such domain restrictions explicit.
# Author: Sandeep Belgavi. Original synthetic quantity contract.
from decimal import Decimal, InvalidOperation
from dataclasses import dataclass
UNITS = {"s": ("time", Decimal("1")),
"ms": ("time", Decimal("0.001")),
"B": ("data", Decimal("1")),
"KiB": ("data", Decimal("1024"))}
@dataclass(frozen=True)
class Quantity:
dimension: str
magnitude: Decimal
def quantity(value, unit):
if not isinstance(value, str) or not isinstance(unit, str) or unit not in UNITS:
raise ValueError("explicit decimal text and a supported unit required")
try:
number = Decimal(value)
except InvalidOperation as exc:
raise ValueError("invalid decimal") from exc
if not number.is_finite() or number < 0:
raise ValueError("quantity must be finite and nonnegative")
dimension, scale = UNITS[unit]
return Quantity(dimension, number * scale)
def add(left, right):
if left.dimension != right.dimension:
raise ValueError("incompatible dimensions")
return Quantity(left.dimension, left.magnitude + right.magnitude)
assert add(quantity("250", "ms"), quantity("1.5", "s")).magnitude == Decimal("1.750")
assert quantity("2", "KiB").magnitude == Decimal("2048")The calculation gives 1.750 seconds. It does not establish that two tasks execute sequentially or that adding their durations estimates end-to-end latency. If they overlap, the aggregation rule changes. Dimensional compatibility is necessary for meaningful arithmetic, but it does not supply the causal relationship between the measurements. The application must know whether it is summing sequential work, taking a maximum or calculating a rate.
Put quantity semantics into tool contracts
A tool result can carry fields such as value, unit, quantity_kind and source_revision. The quantity kind distinguishes concepts that share a dimension but have different meanings, such as elapsed time and an absolute timestamp. If a tool always returns milliseconds, a fixed-unit field name can be sufficient, provided the schema and adapter both enforce it. Renaming a field during serialization must not drop that guarantee.
Do not allow the model to choose an arbitrary conversion factor. It may request a supported display unit, while deterministic code selects the factor from the registry. Unknown units should trigger a clarification or an unsupported-unit response. Guessing that m means milliseconds rather than meters or minutes makes a successful parse look more trustworthy than it is. Case handling also belongs to the contract rather than to a convenient lowercase operation.
Conversions involving offsets require different treatment. Temperature scales, calendar periods and time zones cannot all be represented by multiplying a magnitude by one constant. The deliberately narrow example supports only multiplicative conversions. Rejecting unsupported quantities is more honest than claiming the helper is a general unit system. A larger application should use a tested dimensional library and define which quantities its adapters are allowed to expose.
Preserve uncertainty and aggregation rules
A computed number can be exact with respect to its inputs while the inputs themselves are uncertain. If a tool reports an estimate, carry its provenance and uncertainty separately from the normalized magnitude. Do not turn a synthetic fixture or a vendor specification into an observed measurement by passing it through a precise decimal calculation. Display labels should distinguish measured, estimated and calculated values.
Rates need both numerator and denominator semantics. Dividing 2048 bytes by two seconds gives 1024 bytes per second for that interval, but averaging several rates without considering interval lengths can be misleading. Keep raw quantities and intervals available so a downstream aggregate can reconstruct the intended computation. The model can explain the result; a typed calculation function should determine it.
Likewise, counts of tokens from different tokenizers are not automatically comparable simply because both are called tokens. Their measurement procedure is part of the quantity's identity. This guide does not define a universal token conversion. It illustrates why a label alone can be insufficient when two tools use different measurement conventions or source versions.
Migrate bare numeric results safely
Inventory tool fields that participate in arithmetic or threshold decisions. Add unit metadata at the producer, then normalize at one boundary before those values enter shared state. Avoid inferring units from existing numeric ranges: 1000 can be a reasonable value in several systems. For old results without a documented unit, mark them ambiguous and require an explicit migration rule rather than silently assuming a scale.
Introduce the new representation alongside the old field during a compatibility window. Compare calculated outcomes on synthetic fixtures spanning small values, large values and boundary cases. When a consumer switches to the typed representation, ensure it no longer reads the old bare number accidentally. Version the contract if a field's unit changes; a field name that stays the same does not make such a change compatible.
Verify semantic refusals independently of formatting
Expected outcomes should include the mixed-unit sum, an equivalent same-unit sum, a byte conversion and rejection of time-plus-data. Add unsupported-unit, negative, non-finite and malformed-decimal fixtures. Test zero explicitly; it is a valid magnitude here and must not be replaced by a default. A presentation layer may round the display, but exported results should retain the canonical value used by the calculation.
No model call is required to test these boundaries. Supply the exact malformed result that a provider or adapter could produce and assert that the computation refuses it before changing downstream state. Then test the adapter's real serialized output in an integration environment. These are contract checks, not evidence that a model understands units or that any observed workload achieved a particular performance level.
For a fixed computation, deterministic code is enough. An agent may be useful for choosing which supported analysis to request or explaining the trace, but arithmetic and dimensional compatibility should remain inspectable. A number becomes useful evidence only when the system preserves what it measures, how it is scaled and which operations are meaningful for it.
Run the example yourself
The synthetic fixtures, expected output and tests behind this guide are in the companion code on GitHub; its README lists the prerequisites, exact commands, expected output and limits.