> ## Documentation Index
> Fetch the complete documentation index at: https://docs.impact.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Python Simulation

> Register a Python application entry as an authorized Simulation target.

Simulation is an explicit capability on deployments that offer it. Standard Trace setup uses the
[Python quickstart](https://docs.impact.ai/quickstart.md#python-example).

## Register an application entry

Simulation registers an existing application entry with Impact's Simulation workflows. Enable the Product
key's Simulations grant, initialize with the actual deployed application version, then explicitly register the
entry. For connection settings, use the [Product-key discovery route](https://docs.impact.ai/sdk/python/setup.md#application-startup).
The SDK resolves the authorized connection and one unambiguous enabled target.

```python theme={null}
import impact

# Supply the actual deployed ref through IMPACT_VERSION_ID when it is known.
runtime = impact.init()


def run_request(request, *, signal, emit):
    def work(interaction):
        # The application owns history, effects, cancellation and any real handoff.
        result = run_application(request, interaction=interaction, signal=signal, emit=emit)
        return impact.SimulationResult(
            text=result.text,
            interaction_id=interaction.interaction_id,
            continuation=result.continuation,
        )

    pending = request.get("continuation")
    if pending is not None:
        # Validate the previous invocation, current target and handle in real app state.
        transfer = load_pending_transfer(pending["previousInvocationId"], pending["handle"])
        return impact.continue_interaction(
            transfer.carrier, work, session_id=request["sessionId"], user_id=request["user"]["id"]
        )
    return impact.interaction(
        work, interaction_id=request["interactionId"], session_id=request["sessionId"],
        user_id=request["user"]["id"], name="application.request",
    )

target = runtime.register_simulation_target(
    effects={"boundary": "simulated"},
    max_concurrency=2,
    capabilities={"input": ["text", "structured"], "streaming": True, "multiTurn": True, "tools": True},
    invoke=run_request,
)
```

Use the same application `run_request` for ordinary traffic and registered targets. `run_application` and
`load_pending_transfer` stand for the application's own work and pending state. Supply the Interaction wrapper
and continuation through the application entry. A pending handle must refer to the application's actual stored
transfer and accepted predecessor, not conversation text. Explicit result Interaction identity is preserved. A
mismatch with the accepted request is reported separately. Confirm logical completion in the Interaction
outcome.

## Select a target and Environment

Supply `target_id` when more than one target is available. Explicit `target_revision` and `product_version_id`
select the discovery binding and the response must echo them exactly. If initialization supplied a deployment
Version, Python registration requires that same Version. Use a matching runtime for a different binding.
Selectors can be opaque refs or deployed commits. The authenticated registry validates the existing
callable/material/placement binding. They neither create a canonical Builder Version UUID nor grant capability
authority. A key with Simulations but no Traces creates no managed telemetry exporter. Fully explicit
endpoint, credential, target/revision, Environment and version registration remains supported. An explicit
capture-off runtime with no ingest configuration can still use that path.

If the actual authorized selectors are already in application configuration, pass them explicitly. The public
Environment selector keyword is `environment=`.

```python theme={null}
target = runtime.register_simulation_target(
    target_id=authorized_target_id,
    target_revision=authorized_target_revision,
    environment=authorized_environment,
    product_version_id=deployed_version_ref,
    effects={"boundary": "simulated"},
    invoke=run_request,
)
```

Use the actual authorized target, revision and Environment identity supplied by the platform. This capability
selector chooses the authorized target placement. `ImpactContext.environment` supplies a reported environment
name. Canonical Environment identity and permission come from the authenticated binding. These existing
selectors are sent in the Product discovery request and must be echoed exactly. A different or missing
selected target rejects before registration. `environment_id` belongs to the internal connection resolver and
is not a keyword of the public `register_simulation_target()` API.

## Register an async handler

For async application handlers, register on the async runtime from the application's running event loop:

```python theme={null}
runtime = await impact.init_async()

async def invoke(request, *, signal, emit):
    return impact.SimulationResult(text=await run_application(request, signal=signal, emit=emit))

target = await runtime.register_simulation_target(
    effects={"boundary": "simulated"},
    invoke=invoke,
)
# At application teardown:
await target.close()  # Or await runtime.shutdown().
```

The async handler runs on the loop that awaits its registration, including its context/span scope. Each
registration binds independently. The `AsyncRuntime` view can be used from another running loop. Cancellation
sets the `threading.Event` signal and cancels the actual handler task, so ordinary `asyncio.CancelledError`
and `finally` cleanup run on that same loop. Close gives cooperative task cleanup a bounded drain. The
application owns any rollback of side effects. Keep the registration loop running through target/runtime
shutdown. Async registration requires an awaitable result. An `async def` handler or a regular callable that
returns an awaitable is invoked on the caller loop. Synchronous runtime registration accepts synchronous
handlers. They run in worker threads and must check `signal.is_set()`. Python cannot forcibly stop or roll
back synchronous work. An async application may explicitly offload blocking business work with
`asyncio.to_thread()` in its own handler. If that await is cancelled, the thread keeps running and the
application owns its cooperative join.

## Capabilities, limits and recovery

Declare only actual application capabilities. Input defaults to text. Streaming, multi-turn and tools default
to false. `target.status()` reports connection state, `in_flight` and `pending_acknowledgements`. Verify that
the platform accepts the ready target. The concurrency limit defaults to 8 (maximum 100), including completed
work still awaiting terminal acknowledgement. The active runtime accepts at most 32 registrations.

Requests preserve structured/text input, history, identities, deadlines, effect scope and optional
prior-response or starting-state references. `emit({"type": ..., "payload": ...})` accepts `text_delta`,
`tool_call`, `tool_result` and `status`. JSON progress is snapshotted in a bounded 64-frame/4-MiB
acknowledgement window per invocation. Exhaustion stops further progress and reports uncertain execution
without a sequence gap. Invocation, accepted-request, Run, case and turn IDs retain their technical meanings.
The application uses the ordinary Interaction wrapper and explicit pending continuation for logical requests.
Turn history is an input to the application. Simulation origin remains explicit even when the target is an
actual Product application. A native trace ID does not certify Product readback. The optional request
`continuation` contains the existing `previousInvocationId` and opaque `handle`. The application result can
return its next `continuation` handle. Handles retain their exact value and allow 1–4,000 UTF-16 units.
Python's whole request/result JSON must remain UTF-8 encodable. Lone surrogate code units cause a refusal.
Request and result payloads each remain bounded to 512 KiB. No handle grants Product or execution authority.

Reconnect replays retained observations under a renewed lease without reinvoking the handler. Observed
cancellation does not claim rollback or terminal cancellation when the application instead completes.
`target.close()` closes one registration. `runtime.shutdown()` closes all registrations. Await both when using
an async view. Starting state, resource isolation and cleanup remain application-owned.

Replays with the same accepted-request key and body converge through the original request deadline, including
after terminal acknowledgement. A changed body conflicts. Each registration retains at most 1,024 active or
unexpired terminal identities. At that bound, new offers receive retryable `busy` rather than evicting an
identity that could repeat an effect. Expired requests cannot run again. This is in-memory protection for the
registration, not durable recovery across process restart. Explicit endpoints require HTTPS/WSS except on
loopback. Missing or malformed request/lease correlation closes the protocol before application effects.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.