# Simulation and stress testing

Klineo provides two different simulation surfaces: Digital Twin studies compare modeled capital plans across deterministic paths; liquidity replay evaluates a strategy against an ordered observation series. Both produce evidence for review. Neither alone authorizes a transaction or guarantees future market behavior.

## Digital Twin studies

A Digital Twin study combines an issuer intent's five capital variants with a seed, horizon, opening portfolio, opening depth, inventory split, and scenario. New studies use `digital-twin-pcg64-fixed-v2`, a deterministic fixed-point engine with a versioned PCG64 random stream. Identical complete inputs and engine version reproduce the same output.

Save the full `inputSnapshot`, including the scenario and capital variants, when preserving a result. The seed alone cannot reproduce a study whose inputs have changed. Historical v1 output has a separate evidence-replay function; new HTTP studies use v2.

| Input | Current HTTP constraints | How to choose it |
| --- | --- | --- |
| `seed` | Trimmed string, 8–200 characters for manual requests | Use a stable review identifier and retain it with the result |
| `pathCount` | Exactly `2000` or `10000` | Use 2,000 paths for an interactive study; 10,000 paths enters the queued lane |
| `stepCount` | Integer from 1 through 365 | Declare the modeled horizon; a step does not implicitly mean a day |
| `startingPortfolioQuote` | Positive atomic string | Opening portfolio value in the selected quote denomination |
| `startingDepthQuote` | Positive atomic string | Opening depth assumption in the same quote denomination |
| `startingInventoryPips` | Integer from 0 through 1,000,000 | Opening project-token allocation |
| `targetTradeSizeQuote` | Positive atomic string | Inherited from the current issuer intent for every variant |

The engine requires all five distinct variants. The manual endpoint also requires `expectedIssuerIntentResourceVersion`, binding the request to the intent generation the user reviewed. Reload a changed intent before rerunning rather than submitting against an old version.

## Scenarios

Supported labels are `HISTORICAL_REPLAY`, `BULL`, `BEAR`, `SIDEWAYS`, `LIQUIDITY_CRISIS`, `TOKEN_UNLOCK`, `LARGE_BUYER`, `LARGE_SELLER`, `LIQUIDITY_WITHDRAWAL`, `GAS_SPIKE`, `ORACLE_OUTAGE`, and `COMBINED`.

The supplied parameters determine the model. A label does not fetch historical data or automatically configure a shock. Review drift and volatility per step, one-sided flow, liquidity withdrawal, gas increase, oracle outage, fees, and unlock tranches explicitly.

`driftPipsPerStep` accepts signed integers from -1,000,000 through 1,000,000. Volatility, withdrawal, one-sided flow, gas increase, and fee inputs use the unsigned pips scale. Protocol and platform fee percentages together cannot exceed 1,000,000 pips of modeled gross fees.

Historical replay requires exactly one bounded signed return for each modeled step. That return series is caller-supplied evidence. An oracle outage index is zero-based and must lie inside the horizon. After an outage, the model suppresses qualifying rebalances and records reserve-risk behavior rather than substituting an available price. Unlock inputs declare token amounts, expected sale participation, confidence, and optional correlation groups; they remain assumptions, not evidence that recipients will sell.

The modeled withdrawal occurs at an engine-defined step: index 3 for `LIQUIDITY_CRISIS` and index 2 otherwise, capped to the final step of shorter horizons. Flow and unlock shocks enter at the middle step. These timing rules matter when comparing short and long studies.

## Read the results

Each variant returns p5, p25, p50, p75, and p95 values for ending value, slippage, drawdown, turnover, gas, fee income, inventory, and minimum depth. It also reports protocol and platform fees, reserve-breach probability, and deterministic scenario-driver deltas.

Percentiles describe the distribution inside this model. They are not calibrated confidence intervals for real-world returns. Reserve-breach probability is the fraction of modeled paths with a breach. Fee income is modeled net fee income after the separately reported protocol and platform fees.

The recommendation first considers variants that satisfy issuer intent and have modeled reserve-breach probability no greater than 100,000 pips. If none qualifies, the engine falls back to deployable variants, then to the comparison set, and selects the highest median ending value. Consequently, a `recommendedVariant` can still fail the intent. Inspect variant eligibility and warnings before making a decision.

Scenario-driver impacts are disclosed deterministic approximations with method `DETERMINISTIC_COUNTERFACTUAL_DELTA_V1`. They do not establish observed causal attribution and should not be read as separately additive realized profit or loss.

## Interactive, queued, and public evidence

A permitted manual request from a current `VALIDATED` or `ACTIVE` issuer intent runs a 2,000-path study off the request thread and returns its completed record. A 10,000-path request persists an immutable queued study with an empty variants array and `recommendedVariant: null`, then enqueues the quantitative job. Read its eventual completed record; an accepted queue response is not a finished report.

The computation service has four active computations per process, a five-minute deadline, and a bounded worker heap. These are process safeguards rather than an organization's Research quotas. Interrupted or failed computations return no partial accepted result. Persistence and worker leases apply additional admission checks.

Publication lineage binds the input hash, issuer intent identity and version, artifact hash, and vault context. A study is eligible for later publication admission only when its source is valid and bound to an existing vault. Sandbox and unbound studies are ineligible. Eligibility itself does not publish the study or grant execution permission. Preserve private unlock and intent inputs in private storage; public evidence requires its separate disclosure and publication workflow.

## Liquidity observation replay

`runSimulation` evaluates a strategy over at least two observations. It carries its own inventory, positions, fees, and costs from event to event, without replacing the simulated portfolio with later historical balance fields. Optional hypothetical opening inventory must supply both token and quote atomic amounts.

| Evidence mode | What it means | Review use |
| --- | --- | --- |
| `CANONICAL_V3_REPLAY` | Ordered V3 event evidence with a policy, block and event identity, source health, and replay state | Can support the separately verified proposal evidence path |
| `DIAGNOSTIC_AGGREGATE` | Aggregate observations lack the full executable provenance | Diagnostic comparison; cannot authorize execution |

Canonical events use block number, transaction index, and log index ordering. Duplicate event identities, conflicting hashes for one block, inconsistent decimals or tick spacing, and mixed canonical/aggregate series are rejected. Passive market-only observations cannot be consumed as executable simulation evidence.

Replay exposes an action path, suppression reasons, inventory path, warnings, and decision checkpoints. A suppressed action reveals which constraint prevented the modeled change. Review it alongside fee, gas, delay, reserve, and drawdown results. Canonical candidate swaps model exact-input fees and within-tick V3 curve movement; this is not a universal cross-tick or mempool execution model.

The result compares the strategy with holding opening inventory and a passive full-range V3 benchmark. `netResultQuote` is signed economic ending value minus the hold value. `endingValueQuote` is nonnegative custody value, while `economicEndingValueQuote` also includes modeled liabilities exceeding available assets. Use the economic value for performance comparisons. `unfundedCostLiabilityQuote` exposes that shortfall; drawdown can exceed 100% when modeled liabilities exceed reference value.

Replay stress inputs include a terminal price gap, one-way-flow haircut, keeper delay, oracle outage cutoff, omitted terminal observations for a reorg scenario, gas increase, and incentive removal. Their effect is the disclosed model effect rather than a complete reconstruction of every possible outage or reorganization. Pool fee inputs use the gross-input fee-pips model, not exact historical fee-growth attribution. Short histories limit inference, and a successful historical replay can still be rejected by current-state transaction simulation.

## Use the app

Review the current intent and opening assumptions, choose a scenario, and run the study. Compare costs, reserve breaches, drawdowns, depth, and intent satisfaction across the five variants. Retain the seed and complete snapshot for reproducibility. For liquidity replay, inspect evidence mode and suppressed actions before relying on results. Move to [Decisions and execution](/mechanics/decisions) only after reviewing the evidence and policy bindings.
