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

# Observations

> Add targeted spans, events and metrics to running Python services without code changes or redeploys, and verify live delivery.

Observations let you dynamically capture structured events, spans and metrics from running Python services using SIL (Struct Instrumentation Language) — with no code edits and no redeploy.

Observations capture live business and operational signals from running Python services without modifying application code or redeploying. Start here before writing monitors so your alerts can watch exact domain outcomes, exceptions and internal latencies.

Read the [SIL reference](https://docs.struct.ai/observability/observations/sil-reference.md) for syntax and examples. Use `struct observations guide [topic]` when `struct observations --help` lists `guide`.

## Prerequisites

* A claimed workspace with Struct Observability enabled.
* A service running an Observation-capable `struct-sdk` build on CPython 3.12 or 3.13. Check the version in the deployed process before selecting a hook, especially for `async def` boundaries.
* **Observation configuration access:** a signed `pk-` ingest key created with `struct keys ingest create` reads Observation configuration for every service and environment by default (or only the `--grant <service:environment>` pairs passed at creation, editable with `struct keys ingest grant`/`ungrant`). An `sk-` API key with `--scope telemetry:write --scope observations:read --grant <service:environment>` also works.
* If the service exports to a custom ingest endpoint (`STRUCT_INGEST_URL` other than `https://ingest.struct.ai`), `STRUCT_API_URL` must also be set on the service process so the SDK knows which API host to poll for Observation configuration.

## Workflow: validate → draft → diff → publish → verify

An Observation scope uses one `(serviceName, environment)` pair. Copy the target process's exact `service.name` and `resource.deployment.environment.name` from its telemetry. The SDK can set `service.name` via `struct_sdk.init(service_name=...)` or `OTEL_SERVICE_NAME`. Multiple workers can share a scope, for example `jobs/production`. Use a telemetry resource attribute such as `resource.container_app` on Azure Container Apps to identify the worker and its rows. A config read grant covers the scope.

### 1. Inspect the code and write SIL

Read the target Python source files first. Confirm:

* Exact dotted import path (`module`, e.g., `services.refunds` for `services/refunds.py`).
* Exact function or `Class.method` (`symbol`).
* The [hooks supported by the deployed SDK](https://docs.struct.ai/observability/observations/sil-reference.md#what-can-be-targeted). Source-anchored hooks also need an exact match to the running source.
* Exact parameter/local variable names and attribute/dict keys to read.

### 2. Validate exact SIL bytes

```bash theme={null}
struct observations validate --file obs.sil.json --json
```

Validation runs on Struct's SIL compiler and stores nothing. Fix every diagnostic (`parse`, `schema` or `semantic`) before drafting.

### 3. Create an immutable draft

Save a draft request JSON (`draft.json`). Pass `expectedTargetRevision: 0` when creating a new scope; for an existing scope, read `baselineRevision` from `struct observations status <scope-id> --json`.

```json theme={null}
{
  "serviceName": "checkout-api",
  "environment": "production",
  "target": { "kind": "baseline" },
  "expectedTargetRevision": 0,
  "operations": [
    { "kind": "addObservation", "observationId": "refunds.settled" }
  ]
}
```

Create the draft, attaching the exact SIL text with `--document`:

```bash theme={null}
struct observations draft --file draft.json --document obs.sil.json --json
```

Drafting validates against the scope's current state and stores an immutable draft without publishing. Supported baseline operations:

* `addObservation` — add a new observation taken from `--document`.
* `setVersions` / `prependVersions` — replace or prepend offered versions for an existing observation.
* `stopObservation` / `restoreObservation` — pause capture (keeping history) or re-enable it.
* `removeObservation` — remove the observation from the baseline.
* `setDescription` — update authoring description without changing definition identity.

For temporary triage and debugging captures that auto-expire, use an **overlay** target instead of `baseline` (see [Short-lived Observations for triage and investigation](#short-lived-observations-for-triage-and-investigation) below).

### 4. Review the diff and publish

```bash theme={null}
struct observations diff <draft-id> --json
struct observations publish <draft-id> --json
```

If `publish` returns an uncertain or timeout error, retry the **same** `<draft-id>` (publication is idempotent per draft ID). If another change moved the baseline (`target_revision_stale`), read the new `baselineRevision` from `struct observations status <scope-id> --json` and create a fresh draft.

### 5. Self-confirm live delivery (do not stop at `ready`)

`struct observations status <scope-id> --revision <rev>` checks only whether Struct built the downloadable artifact (`preparing` → `ready`). **Ready does not mean the SDK installed the Observation or that data is arriving.**

Always check live delivery after publishing. Give the SDK time to poll and exercise the target function. Run the following commands when `struct observations --help` lists `verify`.

```bash theme={null}
struct observations scopes --json
struct observations verify <scope-id> --since 1h --json
```

Pass `--observation <observation-id>` to verify one Observation. If your installed CLI lacks `verify`, inspect `struct.observations.health` (`struct telemetry guide observation_health_reports`) and query the expected signal. For events and spans, filter using `struct.observation.id`, `service.name` and `resource.deployment.environment.name`. Query metrics by metric name within the same scope. For a shared scope, add the resource filter that identifies the intended worker and check its rows. `verify` summarizes delivery for the whole scope.

| Field / status | Meaning | Next action |
| - | - | - |
| `artifactPending` (`artifact_pending`) | Struct is still building the config artifact for `headRevision` | Wait briefly and re-run `verify` |
| `unhealthy` (or non-empty `processHealthIssues`) | Running SDK reported an unresolved `struct.observations.health` error (`incompatible`, `target_pending`, `configuration_forbidden`, `capacity_rejected`, etc.) | Read `reason` and `code`, fix the SIL or SDK config, republish and re-verify |
| `delivering` | Captured traces or logs (`traceCount`, `logCount`), or declared metrics (`metricsSeen`), were found in the window (health events excluded) | Confirmed live — inspect each expected output before building monitors on it |
| `no_data_yet` | Artifact is ready and no health error is active, but 0 captured rows arrived in the window | Trigger the code path, check `service.name` / `deployment.environment.name` match the scope, or confirm the service restarted with the latest config |
| `stopped` | Observation is intentionally stopped | No action unless you intend to restore it |

**Completeness checks:** `verify` checks up to **25** Observations per scope (`truncated: true` if more), up to **6** declared metric names per Observation (`metricsTruncated: true` if more), and up to **5 pages × 200** SDK health rows (`healthTruncated: true` if exceeded). Before declaring an entire scope healthy and verified, check those three flags: run targeted `--observation <id>` calls for omitted IDs, query omitted metric names directly, and when `healthTruncated` is true narrow `--since` or page through raw `struct.observations.health` records (folding by `(stream_id, condition_key)` and highest `process_sequence` so recovered conditions are not treated as active).

**Verifying an updated Observation (`setVersions` / `prependVersions`):** historical counts and fresh `lastSeenAt` timestamps do not identify the installed version. Record the publication timestamp, exercise the target afterward, and query for the updated event/span name, changed attributes or changed capture behavior. For metrics-only updates, query the expected metric samples and attributes after publication; `lastSeenAt` covers traces and logs only.

To inspect raw SDK health records directly:

```bash theme={null}
struct telemetry guide observation_health_reports
```

## Short-lived Observations for triage and investigation

During active alert triage, incident investigation, or debugging a hard-to-reproduce production issue, you often need targeted live evidence (specific function arguments, locals, return values, branch outcomes, or exception details) without modifying permanent baseline monitoring or opening a debug-logging PR.

Use a **temporary overlay**: an isolated, time-bounded set of Observations that **auto-expires automatically** (the SDK enforces the deadline on a suspend-aware clock even if your session ends).

### Create a short-lived triage overlay

Save `overlay-draft.json` with `target: {"kind": "overlay", "id": "<triage-id>"}`, `expectedTargetRevision: 0`, and `completion` (`expiresAfterSeconds` or timezone-aware `expiresAt`):

```json theme={null}
{
  "serviceName": "checkout-api",
  "environment": "production",
  "target": { "kind": "overlay", "id": "triage-webhook-500s" },
  "completion": { "expiresAfterSeconds": 1800 },
  "expectedTargetRevision": 0,
  "operations": [
    { "kind": "addObservation", "observationId": "triage.webhook.payload_state" }
  ]
}
```

Validate, draft, diff and publish it the same way as a baseline Observation.

```bash theme={null}
struct observations validate --file triage.sil.json --json
struct observations draft --file overlay-draft.json --document triage.sil.json --json
struct observations diff <draft-id> --json
struct observations publish <draft-id> --json
```

Read SDK health and captured rows using the verification procedure above. Filter logs or traces by `struct.observation.id = 'triage.webhook.payload_state' AND service.name = 'checkout-api' AND resource.deployment.environment.name = 'production'`.

### Extend or end a triage overlay early

List active overlays and read the overlay's current `revision` from `overlays[].revision`:

```bash theme={null}
struct observations status <scope-id> --observations --json
```

Once root cause is confirmed, end the overlay immediately instead of waiting for expiry (`endOverlay` must be the only operation in its draft, using that overlay's `revision` as `expectedTargetRevision`):

```json theme={null}
{
  "serviceName": "checkout-api",
  "environment": "production",
  "target": { "kind": "overlay", "id": "triage-webhook-500s" },
  "expectedTargetRevision": 1,
  "operations": [
    { "kind": "endOverlay" }
  ]
}
```

Draft and publish that file to withdraw all temporary captures from the overlay. To extend an active overlay instead, publish a draft with `{"kind": "setOverlayExpiry", "completion": {"expiresAfterSeconds": 1800}}`. Note that `struct observations stop` acts on **baseline** observations only — always use `endOverlay` to terminate an overlay. If a triage capture proves useful long term, publish it cleanly to `"target": {"kind": "baseline"}`.

## Monitor Observation health

Add an Observation-health monitor for every scope that uses Observations so binding failures, incompatibilities or config-poll refusals alert automatically:

```bash theme={null}
struct telemetry guide observation_health
```

Set `noDataBehavior` to `ignore` and `forSeconds` to `0` (or a brief hold). Remember that `struct.observations.health` records describe Observation configuration and binding health — they do not prove application telemetry is arriving.

## Clean up noisy or obsolete Observations

Inspect captured volume with `struct telemetry usage --json` or a count query filtered by `struct.observation.id`:

```bash theme={null}
struct telemetry query --json --document '{"kind": "query", "range": {"last": "1h"}, "result": "scalar", "queries": [{"name": "rows", "signal": "logs", "filter": "struct.observation.id = '\''refunds.settled'\'' AND service.name = '\''checkout-api'\'' AND resource.deployment.environment.name = '\''production'\''", "aggregation": "count()"}]}'
```

To tighten a noisy Observation, add a `when` predicate in a new version (`setVersions`) so it records only failures or slow calls. To stop a baseline Observation completely:

```bash theme={null}
struct observations status <scope-id> --json   # read baselineRevision
struct observations stop <observation-id> --scope <scope-id> --expected-revision <baseline-rev> --json
```


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