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

# SIL reference

> Struct Instrumentation Language (SIL 0.1.0) syntax, targets, reads, outputs, limits and worked examples for Observations.

SIL (Struct Instrumentation Language) is the JSON document format used to define [Observations](https://docs.struct.ai/observability/observations/overview.md) for running Python services — both permanent baseline captures and short-lived, auto-expiring triage overlays (`target: {"kind": "overlay", "id": "..."}`, `completion: {"expiresAfterSeconds": 1800}`).

Validate any SIL document before drafting with `struct observations validate --file obs.sil.json --json`. If your installed CLI includes `struct observations guide` or `struct docs`, use `struct observations guide [topic]` or `struct docs sil` to read the guide and examples offline.

## Document structure

```json theme={null}
{
  "version": "0.1.0",
  "runtime": "python",
  "observations": [
    {
      "id": "refunds.settled",
      "description": "Counts settled refunds by provider.",
      "versions": [
        {
          "definition": {
            "target": { "module": "services.refunds", "symbol": "RefundService.settle" },
            "at": { "event": "return" },
            "capture": {
              "provider": { "read": "args['provider']", "type": "string" }
            },
            "emit": {
              "event": {
                "name": "refunds.settled",
                "attributes": { "refunds.provider": { "field": "provider" } }
              }
            }
          }
        }
      ]
    }
  ]
}
```

| Field | Rules |
| - | - |
| `version` | Always `"0.1.0"`. |
| `runtime` | Use `"python"` for the hooks in this reference. |
| `id` | Unique logical Observation ID in the scope (`<area>.<what_happened>`). |
| `description` | Required one-sentence explanation of what is captured and why (at most 1 KiB UTF-8). Authoring metadata only — editing it does not create a new definition digest. |
| `versions` | 0 to 4 offered versions (`definition`), tried in order across rollouts. `[]` offers no capture; supply at least one version to install an Observation. |
| `target` | `module` is the dotted import path (`services/refunds.py` → `services.refunds`); `symbol` is the function or `Class.method`. Read the source code; never guess. |
| `at` | Execution point for point captures. Use `enter`, `return`, `unwind`, `before`, `after`, `except` or `location` as described below. For duration spans, use `start`, `end` and optional `on`. |
| `capture` | Named values read from running code. Each has `read` and `type`: `bool`, `int`, `float` or `string`. |
| `when` | Optional boolean predicate gating the definition, a rule or a metric. |
| `emit` | Outputs: `event`, `metrics`, `span` and/or `span_update`. |

## What can be targeted

* **Function boundaries.** `enter` runs when the function starts executing, `return` on normal completion, and `unwind` when an exception escapes it. Ordinary functions and methods support point captures and paired spans. SDK builds with native suspension support extend these hooks to `async def` functions, generators, async generators and verified `contextlib` context managers. Awaits and item yields leave the call open.
* **Public Python packages.** With `struct-sdk` 0.5.25 and `struct-sdk-native` 0.1.15, use the source-anchored hooks below inside `async def` functions. Async boundaries and spans across suspension require a newer SDK build with native suspension support. Check which build the process runs.
* **Source-anchored hooks.** Use these as standalone points in ordinary functions or coroutines. They require an exact match to the running source. Start a fresh call after installation to verify an interior point.
  * `{"event": "before", "operation": {"kind": "await_assignment", "call": "client.fetch", "assign_to": "response"}}` runs before `response = await client.fetch(...)`. Change `before` to `after` to capture after a successful assignment. A failed or cancelled await skips `after`.
  * `{"event": "except", "handler": {"source": "TimeoutError"}}` runs on entry to a unique `except TimeoutError` handler. A function containing `except*` fails handler source proof.
  * `location` runs before a verified simple statement. Set `at.event` to `location` and `at.location` to the statement's `line` (one-based), `column` (zero-based UTF-8 byte offset) and `source_digest` (`sha256:` followed by the SHA-256 hex digest of the exact Python file bytes).
* **Binding and Temporal.** Unverified decorators, generator-based `types.coroutine` functions and unsupported source points can produce `struct.observations.health` reports. Ordinary methods on supported Pydantic models and abstract base classes can bind. The runtime suppresses capture while Temporal reports an active workflow. Activities follow normal Python rules, including async activities. The suppression starts when the workflow is active, after sandbox imports and initial payload conversion.

## Reads

A `read` is a safe path, never an arbitrary expression (no function calls, operators, or whitespace outside quoted keys). At most **4 path steps** after the root (under `args`, `locals` and `start`, the first key names the binding and does not count).

| Read | Available at | Value |
| - | - | - |
| `args['name']`, `args['name'].attr`, `args['name']['key']` | Any point | Parameter by exact signature name |
| `locals['name']` | Any point | Local variable at that point |
| `result`, `result.attr`, `result['key']` | `return` only | Return value |
| `exception.type`, `exception.message`, `exception.is_cancellation`, `exception.stacktrace` | `unwind` and `except` only | Exception info. `type` is module + qualified class name (e.g., `payments.errors.CaptureDeclined`); builtins have no module (`TimeoutError`). `stacktrace` contains bounded traceback locations without source text or locals |
| `duration_s` (`float`), `duration_ns` (`int`) | Paired `end` / `on` rules | Elapsed duration between `start` and `end` |
| `start['name']` | Paired `on` rules | Value retained by the matching named capture in `start.capture` |
| `{"literal": 1}` | Any point | Typed constant matching `type` (`1` is `int`, `1.0` is `float`; never `null`) |

Events and spans omit unreadable values and record the reason in `struct.capture.field_states`. A metric skips its sample when the value or any attribute is unreadable. The SDK avoids executing properties and ORM descriptors during capture. For example, `locals['row'].status` can yield `blocked_read` for a SQLAlchemy row even when the application reads `row.status` successfully. If the application already assigned the value to a scalar local (`status`) or passed it to another function, capture that local or argument at the corresponding point.

## Outputs and conditions

* **Event (`emit.event`):** arrives as a log record with `log.event_name = <name>`. Optional `severity`: `trace`, `debug`, `info` (default), `warn`, `error`, `fatal`.
* **Metrics (`emit.metrics`):** array of `{type, name, unit, value, attributes?, when?}`. `type` is `counter`, `up_down_counter`, `histogram` or `gauge`. `unit` is required. `value` is a number or `{"field": "<capture>"}`. One metric name must keep one `type` and `unit` across the whole scope.
* **Span (`emit.span`):** requires `start` and `end` instead of `at` (see [Span with duration](#span-with-duration)). At most one Observation can create a span on a given target function.
* **Span update (`emit.span_update`):** a point definition can update an existing span with `"target": "current"`. Use `"target": "observation"` only when this definition creates a span.
* **Conditions (`when`):** `eq`, `ne`, `gt`, `ge`, `lt`, `le`, `and`, `or`, `not`, e.g. `{"eq": [{"field": "status"}, "failed"]}`.
* **Naming:** use lowercase names with dots and underscores (`refunds.provider`). Names cannot start with `struct.` or `otel.`. Metric names must start with a lowercase letter, contain only lowercase letters, digits, `_`, `.`, `/` or `-`, and be at most 255 characters. Keep event and span names short. Use standard OpenTelemetry names (`http.route`, `error.type`) only with their standard meaning. One trigger emits at most eight outputs.

## Limits and rules

* **Strict JSON:** no duplicate keys, no `NaN`/`Infinity`, integers must fit signed 64-bit, `1` (int) and `1.0` (float) keep distinct types.
* **Per-definition bounds:** at most **8** distinct code reads, **32** condition operations at one execution point, expression nesting **16** deep, **32** rules, **8** outputs per trigger, and **4** span links.
* **Events before metrics:** a monitor over an event or span can be created before any data exists (`count()` reads `0`). A monitor over a metric is refused until the metric has reported at least one sample. For `< floor` / heartbeat monitors, wait for at least one full window of data before creating the monitor.

## Reading captured data back

* **By Observation ID (traces or logs):** filter `struct.observation.id = '<id>' AND service.name = '<service>' AND resource.deployment.environment.name = '<env>'`. (`struct.observation.id` supports filter operators only; it cannot be grouped, selected or aggregated.)
* **By event name (logs):** `log.event_name = '<name>' AND service.name = '<service>' AND resource.deployment.environment.name = '<env>'`.
* **By span name (traces):** `span.name = '<name>'` with the same service and environment.
* **By metric name (metrics):** lowercase metric name with the same service and environment.
* **Live verification:** follow the [verification procedure](https://docs.struct.ai/observability/observations/overview.md) to check artifact readiness, SDK health and actual captured rows. Add a resource filter to confirm delivery from the intended worker in a shared scope.

## Worked examples

### Event on return (`event_on_return`)

Record an outcome with low-cardinality dimensions for grouping and monitoring:

```json theme={null}
{
  "version": "0.1.0",
  "runtime": "python",
  "observations": [
    {
      "id": "exports.delivered",
      "description": "Records each delivered export with its format and row count.",
      "versions": [
        {
          "definition": {
            "target": { "module": "services.export_service", "symbol": "ExportService.deliver" },
            "at": { "event": "return" },
            "capture": {
              "format": { "read": "args['export_format']", "type": "string" },
              "rows": { "read": "result['row_count']", "type": "int" }
            },
            "emit": {
              "event": {
                "name": "exports.delivered",
                "attributes": {
                  "exports.format": { "field": "format" },
                  "exports.row_count": { "field": "rows" }
                }
              }
            }
          }
        }
      ]
    }
  ]
}
```

### Failure event (`failure_event`)

Record exceptions raised by a function while ignoring cancellations:

```json theme={null}
{
  "version": "0.1.0",
  "runtime": "python",
  "observations": [
    {
      "id": "payments.capture_failed",
      "description": "Records each failed payment capture with the exception type and provider.",
      "versions": [
        {
          "definition": {
            "target": { "module": "services.payment_service", "symbol": "capture_payment" },
            "at": { "event": "unwind" },
            "capture": {
              "error_type": { "read": "exception.type", "type": "string" },
              "cancelled": { "read": "exception.is_cancellation", "type": "bool" },
              "provider": { "read": "args['provider']", "type": "string" }
            },
            "when": { "eq": [{ "field": "cancelled" }, false] },
            "emit": {
              "event": {
                "name": "payments.capture_failed",
                "severity": "error",
                "attributes": {
                  "error.type": { "field": "error_type" },
                  "payments.provider": { "field": "provider" }
                }
              }
            }
          }
        }
      ]
    }
  ]
}
```

### Span with duration (`span_with_duration`)

Wrap a function in a span, record its duration histogram on return, and mark errors on unwind. SDK builds with native suspension support can use the same definition for `async def`:

```json theme={null}
{
  "version": "0.1.0",
  "runtime": "python",
  "observations": [
    {
      "id": "reconciliation.run",
      "description": "Traces each reconciliation run with its duration and failures.",
      "versions": [
        {
          "definition": {
            "target": { "module": "jobs.refund_reconciliation", "symbol": "run_reconciliation" },
            "start": { "at": { "event": "enter" } },
            "end": { "events": ["return", "unwind"] },
            "emit": {
              "span": { "name": "reconciliation.run", "kind": "internal", "parent": "current" }
            },
            "on": [
              {
                "at": { "event": "return" },
                "capture": { "elapsed": { "read": "duration_s", "type": "float" } },
                "emit": {
                  "metrics": [
                    {
                      "type": "histogram",
                      "name": "reconciliation.run.duration",
                      "unit": "s",
                      "value": { "field": "elapsed" }
                    }
                  ],
                  "event": { "name": "reconciliation.completed" }
                }
              },
              {
                "at": { "event": "unwind" },
                "capture": { "error_type": { "read": "exception.type", "type": "string" } },
                "emit": {
                  "span_update": {
                    "target": "observation",
                    "status": { "code": "error" },
                    "attributes": { "error.type": { "field": "error_type" } }
                  },
                  "event": {
                    "name": "reconciliation.failed",
                    "severity": "error",
                    "attributes": { "error.type": { "field": "error_type" } }
                  }
                }
              }
            ]
          }
        }
      ]
    }
  ]
}
```

### Conditional metric (`conditional_metric`)

Emit an event on every return and increment a counter only when a condition matches:

```json theme={null}
{
  "version": "0.1.0",
  "runtime": "python",
  "observations": [
    {
      "id": "usage_export.rows",
      "description": "Records each usage export and counts the empty ones.",
      "versions": [
        {
          "definition": {
            "target": { "module": "services.usage_export", "symbol": "build_export" },
            "at": { "event": "return" },
            "capture": { "rows": { "read": "result['row_count']", "type": "int" } },
            "emit": {
              "event": {
                "name": "usage_export.built",
                "attributes": { "usage_export.row_count": { "field": "rows" } }
              },
              "metrics": [
                {
                  "type": "counter",
                  "name": "usage_export.empty",
                  "unit": "{export}",
                  "value": 1,
                  "when": { "eq": [{ "field": "rows" }, 0] }
                }
              ]
            }
          }
        }
      ]
    }
  ]
}
```

### Inside an `async def` (`async_after_await`)

Capture a boolean local after the successful assignment in `dispatched = await repository.dispatch_if_current(...)`:

```json theme={null}
{
  "version": "0.1.0",
  "runtime": "python",
  "observations": [
    {
      "id": "jobs.dispatch_checked",
      "description": "Records whether dispatch took place after the repository check.",
      "versions": [
        {
          "definition": {
            "target": { "module": "jobs.dispatch", "symbol": "dispatch_event" },
            "at": {
              "event": "after",
              "operation": {
                "kind": "await_assignment",
                "call": "repository.dispatch_if_current",
                "assign_to": "dispatched"
              }
            },
            "capture": { "dispatched": { "read": "locals['dispatched']", "type": "bool" } },
            "emit": {
              "event": {
                "name": "jobs.dispatch_checked",
                "attributes": { "jobs.dispatched": { "field": "dispatched" } }
              }
            }
          }
        }
      ]
    }
  ]
}
```


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