Semantic Drift: LLMs Paraphrasing Enum Values
You ask a model for synthetic order records and get "status": "currently being shipped" where your system expects IN_TRANSIT. If the field is only typed as a string, validation passes, the record loads, and a consumer further down either drops it or routes it to a default branch. Nothing raises an error. The model understood what the field meant and expressed it in its own words, which is precisely the problem.
This is semantic drift: a canonical enum value replaced by a paraphrase, a synonym or a case variant. It is intermittent, which makes it worse than a consistent error. A prompt can look clean in review and still drift on a later run, a longer batch or a new model version.
Drift matters in two places. Generated test data with paraphrased values tests the wrong paths. And many LLM features return enum-like output themselves, a classifier choosing a category or an agent choosing a tool argument, where a paraphrase is a production bug. This article covers constraining generation, strict validation, a careful approach to normalisation, and how to measure drift as a pass rate when the model is the system under test.
Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.
Why models paraphrase enum values
A model is trained to produce fluent, appropriate text, not to preserve string literals. Asked for "a realistic order status", it samples from everything that means order status: SHIPPED, Shipped, "dispatched", "out for delivery". Each is a reasonable completion. Without an explicit constraint there is no reason for it to prefer your exact token over an equally likely synonym. The model is not confused; it simply was not anchored to your vocabulary.
Drift is different from inventing a new enum-looking value, and from mangling a structured identifier, described in token boundary drift in compound IDs. Here the output is good prose in the wrong place. It survives JSON parsing and type checks and fails only in business logic.
Constrain generation with the exact values
List the allowed values in the prompt as literals and say that nothing else is acceptable. Vague wording such as "use a valid status" invites interpretation.
For the "status" field use exactly one of these strings, unchanged:
["PENDING", "IN_TRANSIT", "DELIVERED", "CANCELLED", "RETURNED"]
Do not paraphrase, translate or change case. Any other value is an error.
Where your provider supports schema-constrained output, pass the enum in the schema as well, so decoding itself is restricted. For large enums, or when the distribution of values matters, take the choice away from the model: pick the value in code with a seeded sampler, then ask the model only for fields that should be consistent with it, such as a delivery note that matches a RETURNED status. That also lets you control the mix of values instead of accepting whatever the model favours; models tend to over-produce the interesting statuses and under-produce the dull ones, a skew covered in cardinality skew in synthetic enum data.
Validate strictly, before anything becomes a fixture
from jsonschema import Draft202012Validator
STATUSES = ["PENDING", "IN_TRANSIT", "DELIVERED", "CANCELLED", "RETURNED"]
ORDER_SCHEMA = {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"order_id": {"type": "string", "pattern": "^ORD-[0-9]{8}$"},
"status": {"enum": STATUSES},
"created_at": {"type": "string"},
},
"required": ["order_id", "status", "created_at"],
"additionalProperties": False,
}
validator = Draft202012Validator(ORDER_SCHEMA)
def validate_batch(records: list[dict]) -> tuple[list[dict], list[dict]]:
valid, invalid = [], []
for rec in records:
errors = [e.message for e in validator.iter_errors(rec)]
(invalid if errors else valid).append({"record": rec, "errors": errors} if errors else rec)
return valid, invalid
Keep the rejected records and report the drift rate for each run. A rising rate is information about the prompt or the model, and a silent drop throws it away. Fail the generation job above a threshold your team agrees, then commit only the validated output so tests read a fixed file rather than calling a model.
Normalise only toward known values
A tempting fix is to call .upper() on whatever comes back. That turns delivered into DELIVERED, which is fine, and "out for delivery" into "OUT FOR DELIVERY", which is still invalid but now looks like a constant. Worse, it creates the impression that drift is handled. If you normalise, map onto the allowed set and reject everything else:
CANONICAL = {s.casefold().replace("_", " "): s for s in STATUSES}
def normalise_status(value: str) -> str:
key = " ".join(value.casefold().replace("_", " ").replace("-", " ").split())
if key in CANONICAL:
return CANONICAL[key]
raise ValueError(f"not a known status: {value!r}")
Synonyms ("shipped" for IN_TRANSIT) are a product decision, not a formatting one; if you accept them, list them explicitly. The normaliser is a pure function, so property-based testing suits it well. A Hypothesis test can assert that every canonical value, in any case and with underscores or spaces, maps back to itself, and that arbitrary text either maps to an allowed value or raises:
from hypothesis import given, strategies as st
@given(st.sampled_from(STATUSES), st.sampled_from([str.lower, str.upper, str.title]))
def test_case_variants_round_trip(status, change_case):
assert normalise_status(change_case(status.replace("_", " "))) == status
@given(st.text())
def test_output_is_always_canonical_or_rejected(text):
try:
assert normalise_status(text) in STATUSES
except ValueError:
pass
Property tests belong on deterministic code like this, not on live model calls, where random inputs add cost and noise without adding coverage. Property-based testing for data validation goes further with the technique.
When the model's output is the enum
Classification features, routing steps and agent tool calls produce enum values as their output. Drift there is a defect in the feature, so it needs an evaluation, not just a validator. Build a labelled dataset of inputs with expected labels, run the feature several times per case, and record two numbers per case: how often the output was an exact allowed value, and how often it was the expected one.
def score_classifier(classify, cases: list[dict], runs: int = 5) -> dict:
"""classify(text) -> str is the feature under test, injected."""
exact = correct = total = 0
for case in cases:
for _ in range(runs):
label = classify(case["text"])
total += 1
exact += label in STATUSES
correct += label == case["expected"]
return {"valid_label_rate": exact / total, "accuracy": correct / total, "samples": total}
Report both rates over time and alongside the model version and prompt version that produced them. A model or prompt change that keeps accuracy but lowers the valid-label rate means your code is now leaning on the normaliser more, and that is worth knowing before a paraphrase the normaliser cannot map arrives. Keep the labelled cases versioned; every paraphrase you see in practice becomes a new case.
Mistakes that let drift through
- One manual check of the prompt. Output varies between runs and model versions. Validate every generation run.
- Typing enum fields as plain strings. Schema checks only catch drift if the schema lists the values.
- Normalising without rejecting. Normalisation should end in a known value or an error.
- Forgetting numbers and booleans. A priority of 1, 2 or 3 can come back as 4 or "high"; the same constraints apply.
Semantic drift is a correctness problem at the point of generation. Constrain the vocabulary, validate strictly, normalise only toward known values, and measure drift as a rate when the model is the thing being tested. To wrap these checks into a reusable pipeline, see building a custom test data generator.
Note: This article is for informational purposes only and is not a substitute for professional advice. If you need guidance on specific situations described in this article, consider consulting a qualified professional.