# Monitor Native Object Values and Activity

These instructions apply to the current Admin Console.

{% hint style="info" %}
Alerts are in early access and may not be available in your account. [Contact Contextual support](mailto:help@contextual.io) to request that Alerts be enabled for your tenant.
{% endhint %}

> **Early access:** Solution Metrics alerts are available only for tenants enabled for this capability. This includes Native Object state, audit activity, and attachment-size alerts. Regular Alerts access alone does not enable these features.

Use **state alerts** to compare a Native Object's numeric value with a threshold. Use **activity alerts** to detect activity or inactivity in its audit history.

## Choose State or Activity

| Question | State alerts | Activity alerts |
| --- | --- | --- |
| What does it measure? | A value from an object's current state, such as its balance. | Recorded operations within a window, such as new invoices in the last 15 minutes. |
| Collection | `native-object:TYPE_ID`; constrained attachment rules use `contextual:files`. | `contextual:native-object-instances-history`. |
| First aggregate | `latest` or `earliest`. | Supported activity aggregates, including `count`, `count_distinct`, `sum`, and `avg`. |
| Population | Per-object groups or a supported explicitly narrowed population. | One exact Native Object type, optionally narrowed or grouped further. |
| Time | Current state at the evaluation time, not just objects changed within the rule window. | Activity during the authored window. |
| Missing observations | Do not substitute zero. A vanished active series can become stale. | Successful counts can establish zero; missing groups can be zero-filled only for previously active count series. Other missing values are not automatically zero. |
| Historical preview | Unavailable (`501`). | Supported for eligible queries and observable populations, within preview limits. |

Counting object updates does not establish how many objects currently exist or how many business events occurred. For activity questions, use the audit-history collection. For state, choose a numeric value and a stable, bounded population rather than asking for a whole-collection aggregate.

## Before You Start

1. Confirm early access is enabled for the tenant. `GET /capabilities` must report `capabilities.solutionMetrics.state: enabled`. The top-level `actions.author` value alone is insufficient: ordinary Alerts authoring can be available while this capability is paused.
2. Use the [API authentication and organization scope](https://docs.contextual.io/tenants/tenant-apis/alerts-api.md#base-url-and-authentication) for your environment. You need rule-create or rule-update permission to validate/preview, source access such as `native-object:account:read`, and the appropriate permissions to save, update, route, and inspect results.
3. Have an administrator enable [background metrics access](https://docs.contextual.io/operate/alerts/background-metrics-access.md) before enabling a metrics rule. The examples start disabled so you can review configuration and routing first. A disabled draft still requires early-access availability and authoring permissions.
4. For activity alerts, enable audit history on the selected Native Object type before generating test activity. Authoring checks this prerequisite with your access. Keep it enabled while activity alerts are in use. Enabling audit history does not add records for earlier activity.
5. Choose a disposable test population and a destination whose recipients expect test notifications. Use the Alerts API to create these rules. The Admin Console has no general Solution Metrics rule editor.

If the tenant is not enabled, these templates are omitted from its catalog and authoring requests are refused. A `403` can also mean missing permissions; inspect the error code and capability response. Temporarily unavailable capability information can return `503`, which is different from an unsupported historical preview.

## State: Monitor a Business Field

This example assumes a Native Object type `account`, a numeric field `data.balance`, and a string field `data.accountId`. Replace those names with fields from your actual type. Set `data.accountId` to `alerts-docs-test` only on the disposable objects you want to monitor. Balance and threshold use the same units as your stored data; Alerts does not convert currencies or units.

Send this complete rule to `POST /rules/validate`:

```json
{
  "name": "Test account balance above 10000",
  "enabled": false,
  "severity": "warning",
  "notify": "destinations",
  "source": "clickhouse-metric",
  "definitionKind": "threshold",
  "metricRefKind": "solution-metrics-query",
  "comparator": "gt",
  "threshold": 10000,
  "window": "5m",
  "for": "0s",
  "query": {
    "coll_name": "native-object:account",
    "dedup": true,
    "select": [
      { "path": "data.balance", "agg": "latest", "type": "number", "alias": "balance" }
    ],
    "where": [
      { "path": "data.accountId", "operator": "=", "value": "alerts-docs-test" }
    ],
    "group_by": [{ "path": "$document_key" }]
  }
}
```

This tracks each matching object independently. `dedup` selects current document versions before population filtering. The `accountId` filter narrows the test population; `$document_key` supplies each object's stable group identity. Keep the population below the 100-series limit. The first select is the threshold value; additional selects are informational, not additional conditions.

The rule compares the current balance with 10,000. A balance of exactly 10,000 does not breach. An account that has not changed in the last five minutes can still supply its current value: `window` does not turn this into “accounts updated recently.” `for: 0s` allows firing on the first successful breaching observation; use a nonzero duration if sustained breaches are required.

Do not add `balance > 10000` as a query filter just to repeat the threshold. That would remove an account when its balance falls, preventing the rule from observing the non-breaching value needed for ordinary recovery. Keep population selection separate from the condition where possible.

### Verify State and Recovery

After you [save, route, and enable the state rule](#save-and-route-the-rule), use a matching test account to verify firing and recovery.

1. Keep one matching test account at balance `1000` and confirm successful evaluation.
2. Change its balance to `12000`, preserving its object identity and `accountId`. Allow for ingestion and evaluation, then inspect the firing instance and delivery outcome separately.
3. Change that same balance back to `1000`, keeping the object in the query. A successful non-breaching observation should resolve its alert. Check the destination if recovery notifications are enabled.
4. Treat deletion, changing `accountId`, and loss of observations as different cases. They can remove the series or prevent evaluation; they do not demonstrate recovery.

Historical state-alert preview returns `501`. Validate the rule and use controlled live observations to verify it; do not treat that response as a reason to substitute a count or change the collection.

## Activity: Detect No New Objects

This example watches POST audit activity for the Native Object type `invoice`. Replace the type ID with a disposable type whose audit history is enabled. It checks one aggregate for the type, rather than one alert per invoice.

Send this complete rule to `POST /rules/validate`:

```json
{
  "name": "No new test invoices in 15 minutes",
  "enabled": false,
  "severity": "warning",
  "notify": "destinations",
  "source": "clickhouse-metric",
  "definitionKind": "threshold",
  "metricRefKind": "solution-metrics-query",
  "comparator": "lt",
  "threshold": 1,
  "window": "15m",
  "for": "0s",
  "query": {
    "coll_name": "contextual:native-object-instances-history",
    "select": [{ "agg": "count", "alias": "post_operations" }],
    "where": [
      { "path": "data.typeId", "operator": "=", "value": "invoice" },
      { "path": "data.operation", "operator": "=", "value": "POST" }
    ]
  }
}
```

A successful count of zero breaches; one or more matching POST records does not. This measures recorded activity, not all currently existing invoices or a business date inside an invoice. `data.operation` describes the audited Native Object operation. `$operation` describes the storage change operation and is not a substitute for this filter.

Keep exactly one equality filter on `data.typeId`; it establishes the subject type and its read permission. Do not group across type IDs. `count` omits `path`. This activity query does not request state deduplication, which could collapse the records you intend to count.

For a spike instead, use `comparator: gt` and `threshold: 10` to detect more than ten matching operations in a 15-minute window. Revalidate every edited rule. To render the activity-absence template, send `typeId` and `window` in the `parameters` object to `POST /templates/native-object-post-activity-absence/render`.

```json
{ "parameters": { "typeId": "invoice", "window": "15m" } }
```

The `native-object-post-activity-spike` template takes `typeId` and defaults to more than ten matching POST operations in 15 minutes. To render either template, follow the [Alerts API template workflow](https://docs.contextual.io/operate/alerts/manage-rules.md#with-the-api).

### Preview and Verify Activity

1. Request a [bounded historical preview](https://docs.contextual.io/operate/alerts/validate-and-preview.md) for the validated draft. Inspect coverage and completed windows, not just the breach count. Preview compares sampled observations; it does not simulate sustained timing, delivery, or every instant in the lookback.
2. [Save, route, and enable the activity rule](#save-and-route-the-rule). Create a test invoice through its normal supported API and confirm that its POST audit record reaches the queried history. A successful observation with that record in the window should be non-breaching.
3. Stop creating matching test invoices. After the last POST leaves the 15-minute window, a successful count of zero should cause firing. Other users or automation creating invoices of the same type will keep this example from becoming quiet.
4. Create another matching invoice and allow its audit record to arrive. A successful count of at least one should resolve the alert. Confirm receiver acceptance separately.

An upstream failure is not zero activity. If you extend this example with grouping, a missing group cannot establish that a never-observed entity is inactive. Live zero-fill applies only to previously active count series after a successful query; historical preview does not invent a population from current incidents or other sampled windows.

## Save and Route the Rule

Start with a validated state or activity rule draft that has `enabled: false` and the ID of a test destination. Saving and routing the rule writes configuration. Enabling it can send notifications.

1. Inspect `valid` and all guardrail results from validation. A successful HTTP response alone is insufficient.
2. Save the disabled body with `POST /rules`. Omit `id` and record the returned `_metaData.id` and hash.
3. Create a destination subscription with `POST /subscriptions`, using the saved rule ID and your test destination:

```json
{
  "ruleId": "SAVED_RULE_ID",
  "targetKind": "destination",
  "destinationId": "TEST_DESTINATION_ID",
  "channels": ["webhook"],
  "enabled": true,
  "notifyOnResolve": true
}
```

4. Once background metrics access is ready, read the rule and send its complete writable configuration to `PUT /rules/{id}` with `enabled: true` and the current hash in `x-if-hash-match`. Omit `_metaData`; reconcile a `412` rather than overwriting a changed record.
5. Inspect evaluation, alert history, and delivery through **Operate → Alerts** or the [operations API](https://docs.contextual.io/tenants/tenant-apis/alerts-api/alert-operations.md). Use controlled test data to verify firing. Where recovery applies, verify that a successful non-breaching evaluation resolves the alert. Confirm that the test destination receives the firing notification and any configured recovery notification.
6. Disable or delete the test rule when finished. Rule deletion removes its rule-bound subscriptions. Remove unused test destinations only after checking other references, and restore or remove test data through its owning service.

The `notify` field alone does not create a route. Matching organization policies and silences can also affect delivery; see [Route notifications to Slack or a webhook](https://docs.contextual.io/operate/alerts/destinations-and-subscriptions.md).

## Alert When an Object or Attachment Exceeds a Size Limit

### Monitor Object Size

Render `native-object-oversized` with `{ "parameters": { "typeId": "invoice" } }` to monitor stored documents larger than 1.5 MiB. The rule evaluates the latest stored document size for each object of that type.

### Monitor Attachment Size

Render `POST /templates/rla-attachment-oversized/render` with the exact Native Object type and the size limit in MiB.

```json
{ "parameters": { "typeId": "invoice", "sizeMiB": 2 } }
```

Two MiB is 2,097,152 bytes. The rule checks the latest active attachment metadata for the selected type and tracks each attachment independently. When adjusting the limit, preserve the exact type filter, active-file filter, per-attachment grouping, deduplication, and compatible candidate threshold. See the [attachment query restrictions](https://docs.contextual.io/operate/alerts/metrics-and-queries.md#native-object-and-attachment-queries).

Both size rules look at current state, so historical preview is unavailable. Validate the draft, [save and route the rule](#save-and-route-the-rule), then use a controlled live test to verify evaluation and delivery. Deleting a record or making it leave the query can produce a stale alert. Keep the selected population below the rule’s 100-series limit.

See the [stored query shape reference](https://docs.contextual.io/tenants/tenant-apis/alerts-api/configuration.md#stored-query-shape) for accepted fields, aggregates, filters, and dimensions.

## If Early Access Is Paused

Existing rules and incidents are preserved; pausing does not create a recovery event. New state and activity rule authoring, including validation and preview, is refused. Authorized API inspection, deletion, and exact disable-only edits remain available during a known pause. Evaluation and new notifications pause, but the change can take time to apply. Evaluations already in progress and notifications already scheduled for delivery can still finish.

A pause is not an immediate delivery cancellation. Platform, AI, and lifecycle alerts remain available if ordinary Alerts access stays enabled. Check capabilities and current evaluation status before changing a valid rule to work around an access restriction.
