HTTP & Runtime

Refusal outcomes

A refusal outcome is a structured record that an operation refused to do work, and why. It covers the failure mode where an operation is deliberately turned away before it touches anything: a producer refused for writing outside its type prefix or into a namespace that does not exist, a consumer refused because its cursor is behind the producer’s sequence.

A refusal is correct behavior. It is not an error, it does not belong in the error envelope, and it should not move the request error rate — the operation did exactly what its contract says. What makes it worth recording is that a refusal spike is an incident: it means a producer is misconfigured, a namespace was deleted, or a consumer lost its place. Those are the failures that stay invisible when the only signals are 5xx counts and latency.

This page covers the runtime primitive that records the outcome, the metric it emits, and the CDK construct that alarms on it.

Recording a refusal outcome

Recording goes through the same P2 Metric hook that already carries apptheory.request and apptheory.event. There is no second observability surface, no second sink, and no second place to wire.

// Go — the handler closes over the app it is registered on.
app.Post("/event-state/consume", func(ctx *apptheory.Context) (*apptheory.Response, error) {
	if cursorBehindSequence(ctx) {
		app.RecordRefusal("event_state_consume", "stale_seq")
		return apptheory.JSON(409, map[string]string{"error": "stale_sequence"})
	}
	return consumeEventState(ctx)
})
// TypeScript
app.post("/event-state/consume", async (ctx) => {
  if (cursorBehindSequence(ctx)) {
    app.recordRefusal("event_state_consume", "stale_seq");
    return text(409, "stale_sequence");
  }
  return consumeEventState(ctx);
});
# Python
def consume(ctx: Context) -> Response:
    if cursor_behind_sequence(ctx):
        app.record_refusal("event_state_consume", "stale_seq")
        return text(409, "stale_sequence")
    return consume_event_state(ctx)


app.post("/event-state/consume", consume)

The recorder is on the app in hand: App and SecureApp both carry RecordRefusal (Go), recordRefusal (TypeScript), and record_refusal (Python), and the secure facade delegates to the same core recording path, so a closed-by-default handler records a refusal without leaving the secure surface and without a second observability wire.

Both arguments are required, and there is no third. The record carries exactly two labels:

Label Meaning Example
operation The operation that refused event_state_consume
reason The low-cardinality reason code stale_seq

There is deliberately no parameter for a tenant, request ID, event ID, record key, path, or namespace value. A metric an attacker can influence must not be able to mint metric series, and a per-tenant or per-id label is exactly that. The absence of the parameter is the guarantee: the framework cannot forget to reject a label it never accepts.

What the metric looks like

RecordRefusal records one metric record with name = "apptheory.refusal" and value = 1. The first-party EMF sink encodes it as its own CloudWatch Embedded Metric Format line:

{
  "_aws": {
    "Timestamp": 1735689600000,
    "CloudWatchMetrics": [
      {
        "Namespace": "AppTheory",
        "Dimensions": [["service", "operation", "reason"]],
        "Metrics": [{ "Name": "RefusalCount", "Unit": "Count" }]
      }
    ]
  },
  "service": "theorymcp-events",
  "operation": "event_state_consume",
  "reason": "stale_seq",
  "RefusalCount": 1
}

RefusalCount in namespace AppTheory over service, operation, reason is the whole alarmable surface. It is separate from the RequestCount / RequestDuration / RequestErrors envelope, so a refusal never inflates the request error rate and a request never perturbs the refusal count.

The sink drops any metric name AppTheory does not own, so an application cannot introduce a fourth AppTheory dimension tuple by calling the sink directly.

Bounding the labels

The framework bounds the shape of a label, in every runtime, identically:

  • surrounding whitespace is trimmed and the value is lowercased, so Stale_Seq and stale_seq are one series;
  • an empty label becomes unspecified rather than an empty dimension value;
  • a label carrying any character outside [a-z0-9_.:-] becomes invalid;
  • a label longer than 64 characters becomes invalid.

The alphabet check runs before the length check so the outcome cannot depend on whether a runtime measures length in bytes, UTF-16 code units, or code points.

This bites exactly where it should. Passing an inbound path segment or a namespaced value through as a label lands on invalid:

app.RecordRefusal("events/produce/tenant-3f9a1c", "type_outside_prefix:corp.orders/v2")
// operation=invalid, reason=invalid

invalid is itself a dimension value, so a bounded label never hides a refusal from an alarm — it moves it to a series you can see.

What the framework does not do is guess whether an all-alphabet value is semantically low cardinality. stale-seq-0001 passes the bound. Declaring the reason set is the application’s job, and the place it converges is the alarm below.

Alarming on refusals

AppTheoryRefusalAlarm declares the alarm. Constructing it is what creates it, so a deployment that does not construct it has no refusal alarm. It is exported from @theory-cloud/apptheory-cdk alongside the rest of the deployment constructs.

new AppTheoryRefusalAlarm(stack, "EventStateRefusalAlarm", {
  serviceName: "theorymcp-events",
  operations: ["event_state_produce", "event_state_consume"],
  reasons: ["type_outside_prefix", "namespace_unknown", "stale_seq"],
  threshold: 1,
  period: Duration.minutes(5),
  evaluationPeriods: 1,
  alarmTopic: incidentTopic,
});

The construct evaluates CloudWatch Metrics Insights queries over the emitted tuple. The documented Metrics Insights WHERE grammar admits equality and inequality predicates joined by AND — there is no IN, no OR, and no parenthesised grouping — so “one of these reasons” is one query per value:

SELECT SUM("RefusalCount")
FROM SCHEMA("AppTheory", "service", "operation", "reason")
WHERE "service" = 'theorymcp-events' AND "reason" = 'type_outside_prefix'
SELECT SUM("RefusalCount")
FROM SCHEMA("AppTheory", "service", "operation", "reason")
WHERE "service" = 'theorymcp-events' AND "reason" = 'namespace_unknown'
SELECT SUM("RefusalCount")
FROM SCHEMA("AppTheory", "service", "operation", "reason")
WHERE "service" = 'theorymcp-events' AND "reason" = 'stale_seq'

and the alarm’s metric is their sum, refusal1 + refusal2 + refusal3. Summing is exact rather than approximate here: a refusal series carries exactly one operation and one reason, so each matching series is named by exactly one query and counted once. A single configured reason is a single query with the alarm evaluating it directly, with no sum.

Every identifier in those queries is double-quoted — the metric name, the namespace, and each label key, in SCHEMA(...) and in WHERE. CloudWatch publishes a long reserved keyword list and requires those words to be double-quoted wherever they appear as a namespace, metric name, or label key. operation is on that list, and so are path, type, state, source, error, result, and request; method on the request schema is on it too. The construct quotes all of them instead of the reserved ones, so a schema change or a new AWS release cannot turn a working alarm query into one the service rejects.

CloudWatch caps an alarm’s metric-math graph at ten metrics, and each query is one metric, so a configured operation set and reason set whose product exceeds ten queries fails at synthesis with the count and the limit instead of deploying an alarm CloudWatch rejects. Leave the sets unset for the default posture: with no filter the construct issues exactly one query over every operation and reason.

The operations and reasons values are bounded by the same rule the runtime applies to the labels, so the constant an application declares can be passed to RecordRefusal and to the alarm verbatim: Stale_Seq and stale_seq configure one series and one query, and a value that bounds to invalid configures the invalid series the runtime emits. A blank configured value names the unspecified series rather than being dropped, so a configuration mistake cannot silently widen the alarm to every value; only leaving the prop unset means “every value”.

Defaults are the “refusals are not expected” posture:

Prop Default Meaning
threshold 1 Any refusal in the period breaches
period 5 minutes Evaluation window
evaluationPeriods 1 Datapoints before alarm
operations every operation Not narrowed
reasons every reason Not narrowed
alarmTopic none Alarm exists without an action
missing data not breaching Absence of refusals is healthy

comparisonOperator is >= the threshold, and the alarm’s period is carried by the Metrics Insights expression rather than the alarm’s own Period property, which is what a Metrics Insights alarm looks like in a synthesized template.

Configured in code, never by an operator

The threshold, period, evaluation periods, operation set, and reason set are construct properties. They come from code or from stage configuration, and they are reviewed with the application they alarm on. Nothing in the construct reads an environment variable, so an operator cannot widen, silence, or retune the alarm at deploy time — a change to what pages has to land in the same change as the reason it pages about.

Routing is the one deployment-policy input: pass alarmTopic and the alarm publishes an SNS action, leave it unset and the alarm exists with no action, for a deployment that routes incidents from a central place.

Worked example: TheoryMCP event state

TheoryMCP’s agent event state is the case this primitive was grown for, and it is an instructive one because both of its refusals are correct behavior that must still page.

theory-mcp-server keeps a per-agent event log. A producer writes events under a type prefix inside a namespace, and a consumer reads forward from a cursor:

  • type_outside_prefix — a producer tried to write an event whose type does not sit under its own type prefix. The write is refused, so one producer cannot forge another’s event types. A spike means a producer was configured with the wrong prefix after a deploy.
  • namespace_unknown — a producer or consumer referenced a namespace with no registered event state. The operation is refused rather than creating state implicitly. A spike means an agent or a stage lost its namespace, or a namespace was deleted underneath a live producer.
  • stale_seq — a consumer presented a cursor that is behind the producer’s sequence. The read is refused so the consumer cannot silently skip events. A spike means a consumer lost its place — a restart with a stale checkpoint, or two consumers disagreeing about a shared cursor.

Each is recorded at the refusal site:

switch {
case !types.HasPrefix(eventType, producer.TypePrefix):
	app.RecordRefusal("event_state_produce", "type_outside_prefix")
	return ErrTypeOutsidePrefix
case !namespaces.Exists(namespace):
	app.RecordRefusal("event_state_produce", "namespace_unknown")
	return ErrNamespaceUnknown
}
if cursor.Seq < head.Seq {
	app.RecordRefusal("event_state_consume", "stale_seq")
	return ErrStaleSequence
}

The deployment then declares one alarm with the three reasons as its declared set:

new AppTheoryRefusalAlarm(stack, "EventStateRefusalAlarm", {
  serviceName: "theorymcp-events",
  operations: ["event_state_produce", "event_state_consume"],
  reasons: ["type_outside_prefix", "namespace_unknown", "stale_seq"],
  alarmTopic: incidentTopic,
});

Because the reasons are declared in one place, a new refusal reason added to the code without an alarm change still records and still appears on the EMF line, but it will not page until the alarm’s reason set grows in review. That is the intended direction: an alarming reason is a decision, not an accident.

Operational notes

  • Tier. Refusal recording rides the P2 observability hooks. Wire the P2 metric hook to the EMF sink as you would for request metrics; at a lower tier nothing is recorded and the alarm has no data.
  • Do not record refusals as request errors. Reporting a refusal through the error envelope or a 5xx turns a contractual “no” into an incident signal on the request error rate, and the two failure modes then look identical.
  • Do not build a second emitter. If the framework cannot express what you need to alarm on, grow the reason set or the construct. A one-off PutMetricData call in a route handler reintroduces exactly the drift this primitive removes.
  • Cardinality is a reviewed property. Adding a label means extending the framework surface, not passing a string. If you find yourself wanting reason=tenant-3f9…, the value belongs on the request log, not in a metric dimension.