Runtime

Intent Verification

@axiljs/runtime checks the promises decorators declare: tReadOnly, tPure, tSideEffect, tTenantIsolated, tIdempotent, tSlo, tDeprecated and tDeadline, with enforce, warn and off modes.

12 min readUpdated DocumentationEdit this page
On this page18

Some decorators state a promise about a method: tReadOnly says it never writes, tTenantIsolated says it never returns another tenant's data, tIdempotent says a repeated request has no second effect. @axiljs/runtime checks those promises while the code runs. A broken promise fails a test in development instead of becoming a data leak or a duplicate charge in production.

Note

New in 0.3.4: intent verification. New in 0.3.5: the AXIL_INTENT_MODE environment variable, runWithoutSideEffectReports() and runtimeReport().

TypeScript
TS
1import { tIdempotent, tReadOnly, tTenantIsolated } from '@axiljs/decorator'
2import { configureIntent, installSideEffectProbes, wire } from '@axiljs/runtime'
3
4class Orders {
5  @tReadOnly()
6  @tTenantIsolated()
7  async list() { return this.repo.findAll() }        // an INSERT here throws in development
8
9  @tIdempotent({ key: 'header:idempotency-key', ttl: 86_400_000 })
10  async pay(orderId: string) { return this.gateway.charge(orderId) }
11}
12wire(Orders)
13
14installSideEffectProbes()              // optional: also report fetch() and fs writes
15configureIntent({ mode: 'enforce' })   // 'enforce' | 'warn' | 'off'

Like every runtime decorator, these only take effect on classes passed to wire() (or reached by wireAll()). See Interceptors. The checks apply to decorated methods.

The decorators

DecoratorOrderWhat is checked
tDeprecated(options)50Warns once on use; a violation after the removeAfter date
tSlo({ latency, percentile, errorBudget })60Latency percentile and error rate over the last 1000 calls; emits breach and recovery events
tPure()70No side effect of any kind, reads included
tReadOnly()70No write inside the call tree
tSideEffect(kind)75Reports kind to the caller, so a pure or read-only caller fails when it calls this method
tTenantIsolated()80The call runs inside a tenant context, and the result contains no rows of another tenant
tIdempotent({ key, ttl })90One execution per key: concurrent duplicates share the running call, later duplicates get the stored result
tDeadline(at)120Rejects calls after an absolute timestamp with DeadlineExceededError (HTTP 410)

Lower orders run outside higher ones. The full order of all 26 runtime interceptors is in Resilience.

Modes

ModeBehaviourDefault
enforceRecords the violation, emits runtime.intent.violation and throws IntentViolationErrorWhen NODE_ENV is not production
warnRecords the violation, emits runtime.intent.violation and prints one process warning (IntentViolationWarning) per decorator, target and detailWhen NODE_ENV=production
offDisables the checks

Select the mode in code with configureIntent({ mode }), read it with getIntentMode(), or set it without code changes:

Terminal
AXIL_INTENT_MODE=enforce npm test # enforce | warn | off

AXIL_INTENT_MODE is read once when the runtime is loaded and takes precedence over the NODE_ENV default. axil verify uses it to run your tests in enforce mode. A later configureIntent() call still overrides it.

Note

off disables the checks, not the behaviour: tIdempotent still replays stored results, tSlo still measures and tDeadline still rejects late calls. Only the violations (a write in tReadOnly, a missing tenant, a missing idempotency key, a call after removeAfter) are no longer recorded or thrown.

IntentViolationError

Thrown in enforce mode. It extends axilError, so @axiljs/core answers with status 500 and code INTENT_VIOLATION if it reaches the error handler.

TypeScript
TS
1import { IntentViolationError } from '@axiljs/runtime'
2
3try {
4  await orders.list()
5} catch (err) {
6  if (err instanceof IntentViolationError) {
7    err.message     // 'Orders.list violates tReadOnly: performed side effect db.write (INSERT INTO orders ...)'
8    err.violation   // { decorator, target, detail, requestId?, tenantId?, timestamp }
9  }
10}

Recorded violations

Every violation (in enforce and warn mode) is kept in memory, most recent last, capped at 500:

TypeScript
TS
1import { clearIntentViolations, getIntentViolations } from '@axiljs/runtime'
2
3getIntentViolations()
4// [{ decorator: 'tReadOnly', target: 'Orders.list', detail: 'performed side effect db.write (...)',
5//    requestId: '8f9b6c1e-...', tenantId: 'acme', timestamp: '2026-11-17T10:15:00.000Z' }]
6
7clearIntentViolations()   // also resets the once-per-target warnings

requestId and tenantId come from the request context when there is one. You can record your own violation with violate(decorator, target, detail); it follows the current mode.

Side effects: tReadOnly, tPure and tSideEffect

tReadOnly and tPure open a side-effect scope for the whole call tree, including methods of other classes called from inside it. Code reports effects to the innermost and every enclosing scope:

  • Inside tPure, every reported kind is a violation.
  • Inside tReadOnly, every kind except db.read, network.read, fs.read and cache.read is a violation.

Effects are reported before they happen, so in enforce mode the write is prevented, not just detected.

Where reports come from

SourceKinds reported
@axiljs/ormdb.read or db.write for every statement, before it executes
tSideEffect(kind)kind, with the method name as detail
tCachecache.read (allowed in tReadOnly, a violation in tPure)
installSideEffectProbes()network.read / network.write for fetch(), fs.write for node:fs writes
reportSideEffect(kind, detail?)Anything you report from your own code

How @axiljs/orm classifies statements. After comments are stripped, SELECT, SHOW, EXPLAIN, DESCRIBE, PRAGMA, VALUES and transaction control (BEGIN, COMMIT, ROLLBACK, SAVEPOINT, SET, …) are reads, except SELECT ... FOR UPDATE, which is a write. A WITH query is a read unless one of its parts writes (WITH x AS (DELETE ... RETURNING *)). Everything else is a write. The ORM reports through a global hook, so it works without depending on @axiljs/runtime; classifyStatement(sql) is exported from @axiljs/orm if you want the same classification.

tSideEffect(kind)

Declares the effect of a method, so its callers are checked even when the effect itself is invisible to the runtime (a payment API call, an e-mail):

TypeScript
TS
1import { tReadOnly, tSideEffect } from '@axiljs/decorator'
2
3class Mailer {
4  @tSideEffect('email.send')
5  async send(to: string, body: string) { /* ... */ }
6}
7
8class Reports {
9  constructor(private mailer: Mailer) {}
10
11  @tReadOnly()
12  async monthly() {
13    await this.mailer.send('cfo@example.com', '...')   // IntentViolationError in enforce mode
14  }
15}
16
17wire(Mailer)
18wire(Reports)

The message is Reports.monthly violates tReadOnly: performed side effect email.send (Mailer.send). Kinds are free-form strings; only the four read kinds above are allowed inside tReadOnly.

reportSideEffect(kind, detail?)

Report an effect the runtime cannot see. Call it before performing the effect:

TypeScript
TS
1import { reportSideEffect } from '@axiljs/runtime'
2
3async function publishToKafka(topic: string, message: unknown) {
4  reportSideEffect('queue.publish', topic)
5  await producer.send({ topic, messages: [{ value: JSON.stringify(message) }] })
6}

Outside a tPure / tReadOnly scope the call does nothing. A package that must not depend on @axiljs/runtime can report through the global hook:

TypeScript
TS
globalThis[Symbol.for('axiljs.intent.report')]?.('queue.publish', topic)

currentIntentScope() returns the innermost scope as { decorator, target }, or undefined.

installSideEffectProbes(options?)

Patches the global fetch and node:fs so their effects are reported to the current scope. Outside a scope the patched functions behave exactly like the originals. Intended for development and tests.

TypeScript
TS
1import { installSideEffectProbes } from '@axiljs/runtime'
2
3const removeProbes = installSideEffectProbes()   // { fetch?: boolean, fs?: boolean }, both default true
4// ...
5removeProbes()                                   // restore the originals
OptionDefaultReports
fetchtrueGET / HEAD as network.read, every other method as network.write, with METHOD url as detail
fstruefs.write for writeFile, appendFile, rm, unlink, rename, mkdir, copyFile, truncate (sync, callback and fs.promises forms)

Infrastructure writes: runWithoutSideEffectReports(fn)

Writes the framework makes on behalf of a decorator (a cache entry or idempotency record stored in a database table, a lock row) are not the method's own side effects. Run such code inside runWithoutSideEffectReports() and nothing it does is reported:

TypeScript
TS
import { runWithoutSideEffectReports } from '@axiljs/runtime'

await runWithoutSideEffectReports(() => db.query('INSERT INTO cache_entries ...'))

The SQL stores in @axiljs/stores and the SQL queue backend in @axiljs/queue already do this, so a shared cache write inside a tReadOnly method is not a violation. The function is also published on globalThis[Symbol.for('axiljs.intent.unreported')].

tTenantIsolated()

Two checks per call:

  1. A tenant is required. Without a tenantId in the request context, the call is a violation (called without a tenant in the request context). In warn mode the method then runs normally.
  2. No foreign rows. After the method returns, the result is searched for a tenantId, tenant_id or tenant field (a string, a number, or an object with an id) that differs from the current tenant. The search walks arrays and the data, items, rows, results and metadata properties, up to four levels deep, which covers plain arrays, single rows and the AxilJS pagination envelope.
TypeScript
TS
1class Invoices {
2  @tTenantIsolated()
3  async list() {
4    return this.repo.findAll()   // forgot WHERE tenant_id = ?
5  }
6}
7wire(Invoices)
8
9await runWithContext({ tenantId: 'acme' }, () => invoices.list())
10// IntentViolationError: Invoices.list violates tTenantIsolated: returned data of tenant 'globex' to tenant 'acme'

The tenant comes from the request context: req.locals.tenant set by your tenancy middleware, or runWithContext({ tenantId }) in jobs and tests.

Warning

The second check runs after the method returned. In enforce mode the caller gets an error instead of the data; in warn mode the data is returned and the violation is only recorded. tTenantIsolated detects a leak, it does not add a tenant filter to your queries.

tIdempotent({ key, ttl })

One execution per key. The key is resolved per call from a key spec, typically a request header:

TypeScript
TS
1class Payments {
2  @tIdempotent({ key: 'header:idempotency-key', ttl: 86_400_000 })
3  async charge(orderId: string, amount: number) {
4    return this.gateway.charge(orderId, amount)
5  }
6}
OptionTypeDefaultDescription
keystringrequiredKey spec, for example 'header:idempotency-key' or 'order:{0}'
ttlnumber86400000 (24 h)How long a completed result is kept, ms
  • Concurrent duplicates (same key while the first call runs) join the running call and receive its result.
  • Later duplicates receive the stored result without calling the method.
  • Failures are not stored, so the client can retry with the same key.
  • No key (for example the header is missing) is a violation: no idempotency key (spec 'header:idempotency-key'). In warn or off mode the method then runs without idempotency.
  • Keys are scoped to the method (Class.method:key).
  • Both replay paths emit runtime.idempotent.replay with { target, key, inFlight }.

Results are kept in an in-memory MemoryIdempotencyStore by default. That is correct for one process only: with several instances, a duplicate that reaches a different instance runs again. Install a shared store with useStores() or setIdempotencyStore(). Stored results must be JSON-serializable for shared stores.

Note

Joining a running call is per process even with a shared store; a shared store makes completed results visible to every instance.

To test the promise end to end over HTTP, use expectIdempotent().

tSlo({ latency, percentile, errorBudget })

Measures every call and keeps the last 1000 durations and outcomes per method.

OptionTypeDefaultDescription
latencynumbernoneTarget latency in ms at the chosen percentile
percentilenumber99Percentile the latency is measured at
errorBudgetnumbernoneAllowed fraction of failed calls, e.g. 0.001 for 0.1%
TypeScript
TS
1class Search {
2  @tSlo({ latency: 200, percentile: 95, errorBudget: 0.01 })
3  async query(text: string) { /* ... */ }
4}

The status is evaluated every 50 calls. When an objective is first missed, runtime.slo.breach is emitted; when it is met again, runtime.slo.recovered. Both carry the method's SloReport. A failed call is any call that throws; the error is re-thrown unchanged.

getSloReport() returns the current status of every tSlo method that has been called, and resetSloReport() clears it:

TypeScript
TS
1import { getSloReport } from '@axiljs/runtime'
2
3getSloReport()
4// [{ target: 'Search.query', samples: 1000, percentile: 95, observedMs: 143.2, targetMs: 200,
5//    errorRate: 0.004, errorBudget: 0.01, meetsLatency: true, meetsErrorBudget: true }]

tSlo measures and reports; it never fails a call and is not affected by the intent mode.

tDeprecated(options)

OptionDescription
sinceVersion or date the method was deprecated
removeAfterDate after which any call is a violation (parsed with Date.parse)
replacementName of the method to use instead
messageExtra text for the warning

The first call prints one DeprecationWarning per method (Orders.find is deprecated; since 0.3.0; use Orders.findById instead). Every call emits runtime.deprecated with the target and the options. After removeAfter, every call is also an intent violation, so in enforce mode tests that still use the method fail.

tDeadline(at)

Rejects calls after an absolute time (Date or a string parsed with Date.parse) with DeadlineExceededError: status 410, code DEADLINE_EXCEEDED, message Promo.redeem is not available after 2026-12-31T23:59:59.000Z. Use it for time-limited features such as promotions or sunset endpoints. It does not depend on the intent mode.

TypeScript
TS
1class Promo {
2  @tDeadline('2026-12-31T23:59:59Z')
3  async redeem(code: string) { /* ... */ }
4}

Events

All events go to the global event bus of @axiljs/events. A subscriber that throws produces a process warning and never breaks the business call.

EventPayloadWhen
runtime.intent.violationIntentViolationEvery recorded violation (enforce and warn)
runtime.idempotent.replay{ target, key, inFlight }A duplicate received a running or stored result
runtime.slo.breachSloReportAn SLO is first missed
runtime.slo.recoveredSloReportA breached SLO is met again
runtime.deprecated{ target, since?, removeAfter?, replacement?, message? }Every call of a tDeprecated method
TypeScript
TS
1import { getGlobalEventBus } from '@axiljs/events'
2
3getGlobalEventBus().on('runtime.intent.violation', event => {
4  logger.error('intent violation', event.payload as Record<string, unknown>)
5})

runtimeReport()

A snapshot for tools and tests:

TypeScript
TS
1import { runtimeReport } from '@axiljs/runtime'
2
3runtimeReport()
4// {
5//   mode: 'enforce',
6//   enforced: [{ decorator: 'tDeprecated', order: 50 }, ...],   // outermost first
7//   violations: [...],                                         // getIntentViolations()
8//   slo: [...],                                                // getSloReport()
9//   circuits: { 'Payments.charge': 'CLOSED' },
10//   generatedAt: '2026-11-17T10:15:00.000Z'
11// }

The function is also published on globalThis[Symbol.for('axiljs.runtime.report')], so tools in the same process can read it without importing the runtime. expectNoIntentViolations() and the Studio Intent view use it.

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY