> ## 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 Protect

> Activate Python Protect, configure its Version and inspect Decisions.

Protect is an explicit capability on deployments that advertise it. Confirm that your Product grants Protect
authority before activating it.

## Lifecycle and dependencies

Protect uses the `impact.protect/1` protocol at the documented provider and text/JSON boundaries. Runtime
execution, Decision delivery and readable Product evidence are separate outcomes. Verify enforcement and
classifier quality through actual protected work.

Async applications use `protect = await runtime.activate_protect(version_id=...)` after
`await impact.init_async()`. The returned async handle has synchronous `protect.status()`,
`await protect.flush(timeout_ms=...)` and `await protect.close()`. Synchronous activation returns a
`ProtectHandle` with local `status()`, bounded `flush(timeout_ms=...)` and `close()`. Both views close through
the same runtime-owned lifecycle, so closing a handle and then shutting down the runtime does not repeat
completed cleanup. A failed close reports `closing` and leaves cleanup retryable. Reactivate after the prior
close succeeds.

`await runtime.shutdown()` also closes its owned Protect activation. Cancellation preserves the caller's
`CancelledError` and closes an unclaimed late activation. An owner acquired by another live caller stays
active.

Protect activation is explicit. Ordinary imports and `init()` do not load models, initialize ONNX Runtime,
download weights or change provider decisions. Base `impact` leaves native inference engines
application-owned. Install `impact[protect]` for the selected convenience tuple: ONNX Runtime 1.31.1,
tokenizers 1.0.0rc3 and NumPy 2.5.4 on Python 3.12+, or NumPy 2.4.6 on Python 3.11. Applications retaining
compatible ONNX Runtime 1.30.0/tokenizers 0.23.2 install base `impact` instead. On non-Windows systems set
`ORT_DISABLE_TELEMETRY=1` before any ONNX Runtime initialization. The lazy loader refuses initialization
without it and never changes customer environment or OpenTelemetry. Setting it after another module
initialized the runtime is not proof of the original opt-out. Windows ETW and other native behavior on Windows
remain unassessed. See
[ONNX Runtime privacy](https://github.com/microsoft/onnxruntime/blob/v1.31.1/docs/Privacy.md).

Applications can explicitly install the ONNX Runtime `1.32.0.dev20261106001` preview with
`tokenizers==1.0.0rc3` and base `impact`. Select the exact host wheel and SHA-256 from the
[official nightly index](https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/ORT-Nightly/pypi/simple/onnxruntime/)
as an application dependency. The Protect extra uses the ordinary PyPI release. Install the nightly from the
official nightly index. The observed native CPU tuple uses macOS 14+ on ARM64. Other nightly hosts remain
unassessed.

## Activate Protect

Enable the Product key's Protect grant and explicitly activate the initialized SDK:

```python theme={null}
import impact

runtime = impact.init()
protect = runtime.activate_protect(runtime_label="support-worker")
print(protect.status())
```

[Product-key discovery](https://docs.impact.ai/sdk/python/setup.md#application-startup) resolves the authenticated Product, Environment
and Protect origin. The Python controller requires HTTPS and uses the origin's WSS `/ws/sentinel` with Bearer
authority and `X-Impact-Purpose: protect`. Use trusted TLS even for a loopback origin. The controller
automatically reconnects and re-registers its same runtime identity, selected Version and label when supplied.
Unchanged configuration is acknowledged again without reloading models. Connection, delivery, application,
health and useful protected work remain distinct observations.

## Select the Environment and Version

A customer-runner Environment can be selected without changing Presence or Trace export's base Environment:

```python theme={null}
import os

protect = runtime.activate_protect(
    environment_id=os.environ["IMPACT_PROTECT_ENVIRONMENT_ID"],
    version_id=os.environ["IMPACT_PROTECT_VERSION_ID"],
    runtime_label="support-worker",
    report_scores=True,
)
```

Protect's `version_id` is the canonical Builder whole-material Version UUID, distinct from the reported
context `version_id` / `IMPACT_VERSION_ID` reference and callable selectors. The version-specific sample reads
that actual configured UUID from `IMPACT_PROTECT_VERSION_ID` and passes it explicitly. The example reads the
variable in application code. Likewise, `IMPACT_PROTECT_ENVIRONMENT_ID` supplies the actual authorized
Environment UUID for the optional override. The server resolves the selected formal Version's digest.
Caller-supplied `version_digest` values are unsupported and refuse before discovery or activation. Generic
init/deployment labels are not substituted for `version_id`. Omitted Version input does not qualify a
Version-specific runtime. Labels are trimmed valid text of 1–120 UTF-16 units without controls. Equivalent
activation options share one registration and conflicting options refuse. The runtime also exposes
`invoke_protect_provider_test(boundary, invoke)` for the existing authorized Product enforcement-command
journey. The synchronous runtime invokes a synchronous application callback once. The async runtime awaits the
async callback on its caller loop. This helper preserves the command's scoped identity and requires the actual
selected provider boundary to apply a Decision. Policy authority and Product acceptance remain with the
platform.

## Classifier data and configuration

`report_scores` defaults to `False`. Opt-in HTTP Decisions include each genuinely checked finite 0–1 score,
including zero. Unavailable checks omit the score. Empty text has no evaluated chunk and follows the captured
unavailable posture, without inventing a measured zero. Monitor and allow-and-record preserve the native empty
result. Enforce applies its configured unavailable blocking. The runtime retains raw Policy threshold/PCA and
the pinned Arctic XS/S/M/L pipeline-2 catalogue. Immutable classifier references are acquired with same-origin
purpose authentication and size/hash/media compatibility checks. Models are acquired lazily only for an
applied Policy. Set `model_directory` or `IMPACT_PROTECT_MODEL_DIRECTORY` for the cache. Optional `model_ids`
restrict delivered models. Existing files can be supplied without an acquisition requirement:

```python theme={null}
protect = runtime.activate_protect(
    encoder_installs=[impact.EncoderInstall(
        "arctic-xs", "/srv/protection/arctic-xs/model.onnx", "/srv/protection/arctic-xs/tokenizer.json",
    )],
)
```

Protect verifies retained file bytes before native loading and uses the pinned embedding and classifier
pipeline. Each runtime owns its exact `configSequence`/`configRevision` and Policy/artifact tuple: selected
adoption changes that runtime while unselected runtimes retain their original basis until their own adoption.
Off removes applied on Policies without acquiring a new model. An expiry renewal keeps the same sequence and
revision. A higher sequence may carry the same revision when its configuration body matches. Stale sequences
and changed material under a retained revision are refused. Failure, expiry and partial state remain visible.
Enforce follows the captured unavailable posture and blocks unless `allow_and_record`. Monitor preserves
native work and records unavailable checks. Late original stream Decisions keep their captured configuration
rather than being recast against the newest material.

## Provider boundaries

The observed provider boundary is native OpenAI Chat Completions. Input checks precede the native provider
request. Output enforcement uses the result of that call. Off and Monitor preserve configured client retries,
native results, metadata, errors, lazy streams and caller cancellation. Existing sync/async wrappers retain
the actual worker, provider read, body and iterator close until they join. Verify native inference termination
separately from Python worker cancellation. A pending or failed cleanup remains an error. Pending unary
Monitor and explicit `allow_and_record` calls finish normally during shutdown, with captured `runtime_closed`
unavailable Decisions. Shutdown retains their real join. Required Enforce/block still fences release. Customer
clients remain caller-owned. Other provider operation sets remain unassessed.

For Anthropic typed parsing, a text replacement makes the message/block `parsed_output` unavailable (`None`),
including the final helper snapshot. Impact does not validate the replacement into a new application model or
rerun user validators/schema hooks. Off, Monitor and unchanged output retain the original native parsed value
and identity. An enforced helper snapshot is unavailable until its output has been checked.

Python retains at most 32 active native sends, reads and Protection workers. At that limit, Monitor and
explicit `allow_and_record` preserve the application's next native call and report
`provider_retention_unavailable` against its captured Policy configuration, without a measured score or a
safe-check claim. An unretained call reports its output check unavailable before the native send. Its eventual
body remains application-owned and uninspected. Required Enforce/block refuses unavailable send admission
before the provider call. Failed read handoff after headers closes that response before consumer release.
Shutdown joins retained work within its deadline and does not claim that unretained application work
terminated. The protocol requires a digest even when that future output is unknown. Such output reports use
the exact `unavailableBasis` value
`provider_retention_unavailable:output_body_unavailable:proposed_digest_placeholder` with unavailable
check/effect, no score and the required SHA-256 of an internal empty placeholder. Treat the body as unknown
under this marker.

## Decision delivery

Protect sends Decisions from a bounded outbox to the purpose-authenticated HTTP `/v1/protect/decisions` route.
Retries keep the same Decision occurrence and body without repeating a provider call or rescoring.
`protect.flush(timeout_ms=6000)` and shutdown make bounded delivery attempts. Status reports pending,
failed-attempt and lost counts. The reports carry digests, lengths, provenance and actual effects. Proposed or
released plaintext stays out of the reports. `protect_test` and `protect_test_result` require a genuine
enforcement callback, otherwise the test is unavailable. Process exit may lose unacknowledged in-memory
Decisions. Confirm admission and readback in Product independently of local flush.

Linear JSON artifacts use binary64 coefficients and PCA output, left-to-right dot-product accumulation, and
bias added after summation. Both SDKs use the same bounded sigmoid reduction so the same embedding, artifact
and threshold produce the same linear score and decision. Native encoder and ONNX execution retain their own
precision and platform requirements. Verify classifier quality separately.


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