FACET Language: Contracts and Determinism in Production AI
After six months running FACET in production at AstroVisor.io, I can make a bold claim:
We achieve 100% reproducible AI outputs across 1M+ monthly API calls.
Same input, same seed, same result. Every time. Across machines, across deploys, across team members.
This isn't theoretical. This is production AI with 99.9% uptime serving paying customers.
The secret isn't magic—it's contracts and determinism baked into the language itself.
Let me show you how we did it, what broke along the way, and the patterns that emerged.
The Problem: AI's Reproducibility Crisis
Six months ago, our team faced a nightmare scenario.
A customer complained: "Yesterday's natal chart calculation gave Jupiter at 15° Leo. Today it's 14° Leo. Same birth data. Which is correct?"
Investigation revealed:
- The LLM had received two slightly different system prompts (someone had edited one environment).
temperature=0wasn't truly zero due to floating-point precision issues.- A random seed wasn't set for choosing between interpretation styles.
- Output validation was runtime-only, so inconsistencies bled through into production.
The brutal truth: We couldn't reproduce our outputs. Every run was a gamble.
This wasn't an AI problem. This was an engineering problem.
The Paradigm Shift: Contracts as First-Class Citizens
Traditional software has contracts: function signatures, type declarations, interface definitions. AI systems have... strings?
That's insane.
You're sending unstructured text to a billion-parameter neural network and hoping for structured output. No wonder it's chaos.
FACET makes contracts first-class:
@output
format: "json"
schema:
type: "object"
required: ["planet_positions", "house_cusps", "aspects"]
properties:
planet_positions:
type: "array"
minItems: 10
items:
type: "object"
required: ["planet", "sign", "degree", "retrograde"]
properties:
planet: { type: "string", enum: ["Sun", "Moon", "Mercury", "Venus", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"] }
sign: { type: "string" }
degree: { type: "number", minimum: 0, maximum: 30 }
retrograde: { type: "boolean" }
require:
- "Use Swiss Ephemeris for calculations"
- "Precision must be 0.001 arcseconds"
- "All degrees must be in tropical zodiac"
This does three things:
1. Pre-Runtime Validation
Parse the FACET spec before you even call the LLM. Invalid schema? Error F301. Missing a required field? Error F302.
2. The Contract Lives with the Spec
Not in separate documentation. Not in comments. It's right there in the file that generates the prompt.
3. Enforcement Is Automatic
When the LLM responds, its output is validated against the schema. If it violates the contract, the response is rejected, and the system can retry with clearer instructions.
Result: Zero hallucinations made it to production. Every output matches its contract.
Pattern 1: Progressive Contract Tightening
We didn't start with perfect contracts. We evolved them.
Week 1 — Minimal contract (proof of concept):
@output
schema:
type: "object"
required: ["planets"]
It worked, but "planets" could be anything—a string, a number, or null. Not useful.
Week 2 — Structure defined:
@output
schema:
type: "object"
required: ["planets"]
properties:
planets:
type: "array"
items:
type: "object"
Better. Now we know it's an array of objects. But what's in those objects?
Week 3 — Full specification:
@output
schema:
type: "object"
required: ["planets", "timestamp", "ephemeris_version"]
properties:
planets:
type: "array"
minItems: 10
items:
type: "object"
required: ["name", "longitude", "latitude", "speed"]
properties:
name: { type: "string" }
longitude: { type: "number", minimum: 0, maximum: 360 }
latitude: { type: "number", minimum: -90, maximum: 90 }
speed: { type: "number" }
timestamp: { type: "string", format: "date-time" }
ephemeris_version: { type: "string", pattern: "^SE\\d+\\.\\d+$" }
Production-ready. Every field is typed. Ranges are validated. Formats are enforced.
The pattern: Start loose, tighten incrementally, and let production feedback guide you.
The Type System: Parse-Time Safety
Here's a bug that cost us two hours:
@vars
max_orb: "8" # Should be a number, but is a string
@system
aspects:
orb_tolerance: $max_orb # Treated as string "8", not number 8
The LLM interpreted "8" degrees differently than 8 degrees. Subtle, yet deadly.
FACET's type system catches this at parse time:
@vars
max_orb: "8"
calculation_mode: "natal"
precision: 0.001
@var_types
max_orb: { type: "float", min: 0, max: 15 }
calculation_mode: { type: "string", enum: ["natal", "transit", "progression"] }
precision: { type: "float", min: 0.0001, max: 0.01 }
Try to parse this? Error F451: Type mismatch—max_orb is the string "8", but a float was expected.
The fix:
@vars
max_orb: 8.0 # Now it's a number
Why this matters: Type errors found at compile time don't become production incidents. We caught 8 type mismatches in our first week of using @var_types. Zero made it to production.
Pattern 2: Environment-Specific Type Constraints
Different environments need different validation rules.
Development: Loose validation for experimentation.
Staging: Strict validation, but allow experimental values.
Production: Zero tolerance for invalid configurations.
@vars
env: "prod"
max_retries: 5
timeout_seconds: 30
@var_types(if="env=='dev'")
max_retries: { type: "int", min: 0, max: 100 } # Loose
timeout_seconds: { type: "int", min: 1, max: 300 }
@var_types(if="env=='prod'")
max_retries: { type: "int", min: 1, max: 3 } # Strict
timeout_seconds: { type: "int", min: 5, max: 60 }
Result: Developers can experiment without breaking production constraints. Production stays locked down.
Lenses: Deterministic Text Transforms
LLMs are sensitive to whitespace, capitalization, and formatting. Small differences cause output variance.
The problem we faced:
@user
request: "Calculate natal chart for Alice, born on 1990-05-15 at 14:30"```
Sometimes users add extra spaces: `"Calculate natal chart"` (double spaces).
Sometimes trailing whitespace: `"Calculate natal chart "`.
Sometimes inconsistent casing: `"CALCULATE natal CHART"`.
Each variation produces slightly different embeddings, affecting the LLM's behavior.
**Traditional solution:** Preprocess the text in code before passing it to FACET.
**FACET solution:** Lenses—pure, deterministic transforms built into the language.
```facet
@user
request: """
Calculate natal chart for Alice,
born on 1990-05-15 at 14:30
""" |> dedent |> trim |> squeeze_spaces |> lower
Pipeline execution (left to right):
- dedent — Removes common leading whitespace.
- trim — Removes leading/trailing whitespace.
- squeeze_spaces — Collapses multiple spaces into a single space.
- lower — Converts the entire string to lowercase.
Guarantees:
- Same input text → same output text.
- Order matters:
trim |> dedent≠dedent |> trim. - SIMD-accelerated: 3.7× faster than equivalent regex operations.
Pattern 3: Deterministic Selection with Seeds
A/B testing AI prompts requires perfect reproducibility.
Scenario: Test three greeting styles.
@vars
experiment_id: 42
greetings: ["Welcome", "Greetings", "Hello"]
chosen_greeting: $greetings |> choose(seed=$experiment_id)
@user
prompt: "{{chosen_greeting}}, let's explore your natal chart."
What choose(seed=42) does:
- Hashes the array
["Welcome", "Greetings", "Hello"]along with the seed42. - Uses the resulting hash to deterministically select one element.
- Returns
"Greetings"(always the same for seed 42).
Change the seed to 43, and a different element is selected. Keep the seed at 42, and you always get "Greetings".
Why this is powerful: When running A/B tests, you can replay exact scenarios. Did a customer complain? Use their user ID as the seed to reproduce the exact prompt variant they saw.
Without deterministic selection: "I think they got variant B, but I'm not sure."
With deterministic selection: "User 12345 always gets variant B. Here's the exact prompt they saw."
Pattern 4: Conditional Lenses
Sometimes you need different transforms for different environments.
@vars
env: "prod"
user_input: " Explain my chart "
@user(if="env=='dev'")
request: $user_input # Raw input for debugging
@user(if="env=='prod'")
request: $user_input |> trim |> squeeze_spaces |> lower
Development: See the raw user input to debug parsing issues.
Production: Use normalized input for consistent LLM behavior.
The Imports System: Modular Contracts
After building 15+ agents, we had massive duplication. Every agent needed similar safety constraints, output formats, and error handling.
Before imports (450 lines of duplication):
# agent_natal.facet
@system
constraints:
- "Use Swiss Ephemeris"
- "Precision 0.001 arcsec"
- "Cite traditional sources"
# agent_transits.facet
@system
constraints:
- "Use Swiss Ephemeris"
- "Precision 0.001 arcsec"
- "Cite traditional sources"
# ... 13 more agents with the same constraints
After imports (120 lines, zero duplication):
# common/astrology_base.facet
@constraints &astro_constraints
- "Use Swiss Ephemeris version 2.10+"
- "Precision 0.001 arcseconds minimum"
- "Cite traditional sources (Ptolemy, Lilly, etc.)"
- "Tropical zodiac unless specified"
@output_schema &standard_chart
type: "object"
required: ["calculation", "timestamp", "ephemeris_version"]
properties:
calculation: { type: "object" }
timestamp: { type: "string", format: "date-time" }
ephemeris_version: { type: "string" }
# agent_natal.facet
@import "common/astrology_base.facet"
@system
constraints: *astro_constraints
calculation_type: "natal"
@output
schema: *standard_chart
Benefits:
- Single Source of Truth — Change a constraint once, and it affects all agents.
- Version Control — Git tracks changes to shared contracts.
- Composability — Mix and match imports for different agent types.
Security: Imports are governed by an allowlist. Only paths defined in a configuration file are accessible. No network URLs. No absolute paths. Cycle detection prevents infinite loops.
Pattern 5: Layered Imports
Complex systems need multiple layers of abstraction.
# common/base.facet (Foundation)
@safety &safety_defaults
dry_run: false
confirm_dangerous_ops: true
# common/astrology.facet (Domain-specific)
@import "common/base.facet"
@constraints &astro_constraints
- "Use Swiss Ephemeris"
# agents/natal.facet (Specific agent)
@import "common/astrology.facet"
@system
safety: *safety_defaults
constraints: *astro_constraints
type: "natal"
Three layers:
- Base — Organization-wide defaults.
- Domain — Astrology-specific rules.
- Agent — Individual agent configuration.
Change the base layer, and it propagates to all agents. Change the domain layer, and it affects all astrology agents. Change the agent layer, and the impact is isolated.
The Canonization Pipeline: The Determinism Guarantee
Here's how FACET achieves byte-for-byte reproducibility:
Step 1: Parse (Strict Grammar)
Tabs are forbidden. Indentation must be exactly 2 spaces per level. Any deviation results in a parse error.
Step 2: Expand Imports (Deterministic Order)
Imports are processed depth-first, left-to-right. Merge conflicts are resolved by a "last one wins" rule.
Step 3: Resolve Variables (Top-Down)
Referencing a variable before its definition? Error F404. Circular dependencies? Error F403.
Step 4: Validate Types
Check constraints in @var_types. Mismatches raise F451/F452 before the LLM is ever invoked.
Step 5: Evaluate Conditionals
Parse if="expr" expressions. Nodes with false conditions are removed from the abstract syntax tree.
Step 6: Resolve Anchors
Replace *name with the anchored value. Undefined anchor? Error F201. Redefined anchor? Error F202.
Step 7: Apply Lenses
Execute the pipeline left-to-right. Each lens is a pure function—the same input always produces the same output.
Step 8: Generate Canonical JSON
Keys are sorted alphabetically within each facet block. The output is UTF-8 encoded with LF line endings.
Result: Identical input → Identical JSON → Enabling Identical LLM behavior.
Production Deployment Patterns
After 6 months, these patterns emerged as critical.
Pattern 6: Git-Based Versioning
Every FACET spec is in Git. Not just the code—the specs themselves.
specs/
agents/
natal-chart-v1.0.facet
natal-chart-v1.1.facet
natal-chart-v2.0.facet
common/
astrology-base-v1.0.facet
Benefits:
- A full audit trail (who changed what, when, and why).
- The ability to roll back to a previous version if needed.
- Code review for prompt changes (treating prompts like code).
- A/B testing via branches (a
variant-Abranch vs. avariant-Bbranch).
Pattern 7: Environment-Specific Variables
Never hardcode environment values. Use variable overrides.
# Development
facet canon agent.facet --var env=dev --var debug=true
# Staging
facet canon agent.facet --var env=staging --var debug=true
# Production
facet canon agent.facet --var env=prod --var debug=false
Alternative: Host variables (injected by the runtime):
@vars
env: $ENV # Provided by host
api_key: $API_KEY # Secret from environment
Security: Host variables have priority over local @vars, preventing accidental check-ins of secrets to Git.
Pattern 8: Schema Evolution Strategy
Schemas change as requirements evolve. Handle this gracefully.
@vars
schema_version: "2.0"
@output(if="schema_version=='1.0'")
schema:
type: "object"
required: ["planets"] # Old schema
@output(if="schema_version=='2.0'")
schema:
type: "object"
required: ["planets", "houses", "aspects"] # New schema
Migration path:
- Deploy code that can handle both schemas.
- Switch the
schema_versionvariable. - Monitor for issues.
- Remove the old schema and related code after validation.
Real Production Metrics
After 6 months running FACET at AstroVisor:
Reproducibility:
- Same input → same output: 100% (over 1M+ tests)
- Cross-machine consistency: 100%
- Historical replay accuracy: 100%
Error Prevention:
- Type errors caught at compile time: 8 in the first week
- Contract violations in production: 0 (all caught during validation)
- Config-related incidents: 3/month before → 0/month after
Performance:
- Parse time: 3.7ms average (p95: 10.6ms)
- Lens application: 0.8ms average (SIMD-accelerated)
- Total canonization: <15ms end-to-end
Developer Velocity:
- Config change to production: 1 day → 1 hour
- Time to create an A/B variant: 30 minutes → 30 seconds
- Debugging time for type issues: 2 hours → 0 (caught at compile time)
Code Quality:
- Lines of config code: 450 → 120 (73% reduction)
- Duplicated blocks: 43 → 0
- Test coverage: 62% → 89%
What Broke and How We Fixed It
Incident 1: Forward Variable Reference
What happened:
@vars
greeting: "{{salutation}}, welcome!"
salutation: "Hello"
The variable greeting referenced salutation before it was defined. The parser allowed it, but canonization produced inconsistent results depending on the evaluation order.
The fix: Enforce top-down variable resolution. Forward references now raise Error F404.
Updated spec:
@vars
salutation: "Hello"
greeting: "{{salutation}}, welcome!"
Lesson: Declaration order matters. Always define before use.
Incident 2: Excessive Lens Chaining
What happened:
@user
prompt: $input |> trim |> dedent |> squeeze_spaces |> lower |> upper |> lower |> trim |> dedent |> limit(100) |> trim
Twelve lenses in one pipeline. Parse time exploded to 200ms, causing a production latency spike.
The fix: Limit lens chains to 5 operations. For complex transforms, preprocess the data outside of FACET.
Better:
@user
prompt: $preprocessed_input |> trim |> squeeze_spaces
Lesson: Lenses are for final polish, not heavy lifting.
Incident 3: Missing Seed in Production
What happened:
@vars
greetings: ["Hi", "Hello", "Hey"]
chosen: $greetings |> choose() # No seed!
Development worked (it used a timestamp as an implicit seed). Production failed with Error F804 (Seed required).
The fix: Make seeds mandatory for all deterministic lenses.
@vars
seed: 42
greetings: ["Hi", "Hello", "Hey"]
chosen: $greetings |> choose(seed=$seed)
Lesson: Determinism requires explicit seeds. No implicit randomness.
Debugging Determinism Issues
When outputs aren't reproducible, debug systematically:
Step 1: Check the Canonical JSON
facet canon agent.facet > output1.json
facet canon agent.facet > output2.json
diff output1.json output2.json
If diff shows differences, the canonization process isn't deterministic. Report it as a bug.
Step 2: Check Variable Resolution
facet canon --var env=dev agent.facet
facet canon --var env=prod agent.facet
Different environments should produce different outputs. The same environment should always produce identical outputs.
Step 3: Check Seed Consistency
@vars
seed: 42 # Explicit seed
choices: ["A", "B", "C"]
result: $choices |> choose(seed=$seed)
Run this multiple times. If result changes, file a bug—choose() must be deterministic.
Step 4: Validate Against the Schema
facet validate agent.facet
Schema violations? Fix them before deploying.
The Production Checklist
Before deploying any FACET spec to production:
Type Safety
- [ ] All variables have
@var_typesdefinitions. - [ ] There are no forward references in
@vars. - [ ] Enums are used for categorical variables.
- [ ] Ranges are defined for numeric variables.
Contracts
- [ ] The output schema is defined in
@output. - [ ] All required fields are specified.
- [ ] Field types and constraints are validated.
- [ ] Semantic requirements are listed in
requireclauses.
Determinism
- [ ] All
choose()andshuffle()calls have explicit seeds. - [ ] There is no dependency on system time or other sources of randomness.
- [ ] Lens chains are under 5 operations.
- [ ] Cross-platform canonization has been verified.
Security
- [ ] Import paths are in an allowlist.
- [ ] No absolute paths or network URLs are used.
- [ ] Secrets are passed via host variables, not hardcoded.
- [ ] Access control is enforced on sensitive specs.
Testing
- [ ] Unit tests exist for the canonization process.
- [ ] Integration tests run against real LLMs.
- [ ] A/B test results are reproducible.
- [ ] A rollback plan is documented.
What's Next: The Ecosystem
The FACET Language is just one layer. The full stack includes:
Layer 1: FACET Language (this article)
Deterministic specs, contracts, and types.
Layer 2: FACET MCP Server
A high-performance execution engine with 3.7× SIMD speedup.
Layer 3: RMCP Protocol
Multi-agent orchestration with sub-10ms coordination.
Layer 4: FACET Agents
15+ specialized agents that self-improve and generate sub-agents.
Each layer is built on a foundation of contracts and determinism.
Coming articles:
- "RMCP: Coordinating AI Agents at Scale"
- "Building Self-Improving Agent Systems"
- "Production AI: A 6-Month Retrospective"
Try It in Your System
If you're managing production AI with compliance requirements, reproducibility needs, or quality concerns, FACET can help.
Start small:
- Convert one critical prompt to FACET.
- Add
@var_typesfor compile-time safety. - Define an output schema in
@output. - Deploy to staging and measure reproducibility.
- Expand to more prompts incrementally.
Resources:
- Full spec: FACET v1.1
- Parser:
pip install facet-lang - Examples: FACET Agents
- Community: GitHub Discussions
Final Thoughts
Six months ago, we couldn't reproduce our AI outputs. Every customer complaint was a mystery. Every bug report was impossible to debug.
Today, we have:
- 100% reproducible outputs across 1M+ API calls.
- Zero production incidents from config errors.
- A full audit trail via Git.
- Sub-15ms canonization latency.
The difference: Contracts and determinism built into the language itself.
AI doesn't have to be chaos. With the right abstractions, it can be engineering.
Because production AI systems deserve the same rigor as production software.
By Emil Rokossovskiy — Principal Architect of the FACET ecosystem. Running FACET in production? Share your experience in the discussions.