# runtime.tenant facet (/docs/tenant-facet)



The `runtime.tenant` facet is the substrate's single read site for the
active tenant scope. Construction takes `tenantId` and an optional
`subTenantId`; every downstream write site — event log, cost events,
OTel spans, outbound HTTP — derives its scoping from the facet rather
than from a re-threaded parameter.

This page is the primitive reference. For operations (RLS templates,
cost rollups, deployment checklist), see
[Multi-tenant deployments](/docs/multi-tenant). For the SaaS
use-case shape, see
[Multi-tenant SaaS agent](/docs/multi-tenant-saas-agent).

**Subpath:** `@pleach/core/tenant`

## `SessionRuntimeConfig.tenantId` + `subTenantId` [#sessionruntimeconfigtenantid--subtenantid]

Pass both at construction. `tenantId` is the primary partition key;
`subTenantId` is the optional second scope for nested isolation
(org → team, or tenant → sub-account). Both flow to every downstream
write site without further wiring.

```typescript
import { SessionRuntime } from "@pleach/core";

const runtime = new SessionRuntime({
  storage:     pgAdapter,
  tenantId:    "tenant_abc",
  subTenantId: "team_42",
  // ...
});
```

`tenantId` rejects the empty string at construction with
`TenantIdEmptyError`. The silent-isolation case — an unset env var
interpolated as `""` — becomes a load-bearing throw at init, not a
months-later billing incident. `subTenantId` is optional; when
omitted, the writer stamps `NULL` and the second-scope columns stay
empty.

## `runtime.tenant` facet shape [#runtimetenant-facet-shape]

Read the active scope through the facet rather than the constructor
config. The facet is the stable accessor; constructor fields are
implementation detail that can move.

```typescript
interface RuntimeTenantFacet {
  readonly id: string;
  readonly subId: string | undefined;
}
```

`id` and `subId` are properties, not methods. The facet is built
once in the `SessionRuntime` constructor and `Object.freeze`d for
identity stability — `runtime.tenant === runtime.tenant` always
holds, so consumers can put it in `useMemo` deps without
triggering re-renders.

Plugins, tool handlers, and gateway adapters that need the tenant
scope should reach through `runtime.tenant` — not through their own
config and not through a parallel context object. See
[Facets](/docs/facets) for the broader facet model and why a typed
accessor surface is the contract a plugin should code against.

```typescript
const tenantId = runtime.tenant.id;
const subTenantId = runtime.tenant.subId;
```

`id` is always a non-empty string — the constructor defaults it to
`"default"` when omitted and throws `TenantIdEmptyError` on
explicit `""`. `subId` is `undefined` when not configured.

## Automatic row stamping at `EventLogWriter` [#automatic-row-stamping-at-eventlogwriter]

Every row persisted to the event log carries a tenant and
a sub-tenant, both derived from the facet at write time.
Consumers don't pass these through call sites; the writer fills them
in from the runtime it was constructed against.

Audit and operator queries can read tenant scope without joining the
auditable-call table:

Ask the event log for the count of events by type for one tenant over
the last 24 hours.

The stamping is structural. There is no application-layer code path
that writes an event log row without the tenant scope attached.

## RLS policy shape [#rls-policy-shape]

Core's base schema ships owner and service-role policies. The tenant
policies come with `@pleach/compliance`: its
[tenant RLS schema tier](/docs/compliance#the-tenant-rls-schema-tier) fences each tenant table on the current tenant, and
`auditRlsPolicies()` verifies the result on your database.

A hand-written tenant policy compares each row's tenant to a per-connection setting.
The application server sets that setting on session start,
typically from the JWT claim or the request context. Read it so that an
unset value returns `NULL` instead of erroring: the policy then refuses every row, which is the
correct failure mode for an unauthenticated connection.

`auditRlsPolicies()` reports a table as `compliant` only with the tier's
restrictive tenant-fence and no-anon policies on each table, so a
hand-written policy alone won't pass.

Service-role clients bypass RLS; the substrate's structural stamping
is what keeps those writes correctly scoped. Anon clients rely on
the policy.

## `withTenantHeader` adapter [#withtenantheader-adapter]

The adapter wraps a `fetch` client (or any outbound HTTP layer) and
stamps a tenant header onto every request. Useful for hosts running
behind an upstream gateway that routes by tenant header — the previous
pattern was manual header-threading per call site, which the adapter
replaces.

```typescript
import { withTenantHeader } from "@pleach/core/tenant";

const tenantFetch = withTenantHeader(fetch, {
  header:   "x-tenant-id",
  tenantId: runtime.tenant.id,
});

await tenantFetch("https://gateway.internal/v1/chat", {
  method: "POST",
  body:   JSON.stringify(payload),
});
```

The adapter captures the `tenantId` string at wrap time — pass
`runtime.tenant.id` in when you construct it. The binding is to that
captured value, not to the runtime. The `header` name is required
(there is no default); set it to whatever key the upstream gateway
expects.

The wrapper covers your own outbound HTTP, not the model provider's
requests. `AiSdkProvider`, `AnthropicSdkProvider` and
`OpenAINativeProvider` stamp those themselves, on by default, under
`x-tenant-id`. Pass `tenantHeader: "<name>"` to rename the header, or
`tenantHeader: false` to turn it off. Placeholder tenants such as
`"default"` are never sent. A real tenant id reaches the provider and
any gateway in between. See
[Providers → tenant header](/docs/providers#tenant-header).

## `CostEvent.tenantId` propagation [#costeventtenantid-propagation]

Cost events emitted by the runtime carry `tenantId` automatically once
the facet is configured. Per-tenant cost rollups work without
consumer-side annotation — every emitter inside the substrate reads
the facet and stamps the field on the way out.

```typescript
runtime.on("cost.event", (event) => {
  // event.tenantId === runtime.tenant.id
  metrics.increment("llm_cost_usd", event.usdCost, {
    tenant: event.tenantId,
  });
});
```

See [Observability](/docs/observability) for the full `CostEvent`
shape and the dashboard patterns that consume it.

## OTel `pleach.tenant_id` attribute [#otel-pleachtenant_id-attribute]

When OTel is wired, every emitted span carries `pleach.tenant_id`
automatically. No opt-in needed once the facet is configured — the
attribute is set by the substrate's span factory, not by the call
sites that open spans.

Spans whose runtime had a `subTenantId` configured also carry
`pleach.sub_tenant_id`; the attribute is absent (not empty) when
the second scope wasn't set.

```
WHERE pleach.tenant_id = "tenant_abc"
VISUALIZE P95(duration_ms), COUNT
GROUP BY name
```

See [OTel observability](/docs/otel-observability) for the full
attribute catalog and the collector wiring.

## Migration SQL [#migration-sql]

Consumers upgrading from a single-tenant or org-scoped schema run a
three-step migration on every table the substrate writes (event log,
cost events, audit ledger). Add the columns nullable, backfill, then
tighten.

Add the tenant and sub-tenant columns as nullable. Backfill the tenant from
the previous tenant column, or `default` for pre-multi-tenant rows that have
no source value. Then make the tenant column required.

Run the tighten step only after a verification query confirms zero
unscoped rows.

Count rows with no tenant; the expected result is zero.

## What's checked on scoping [#whats-checked-on-scoping]

Pleach's CI checks three rules alongside the runtime contract.

* **Core's event-log write paths carry the tenant.** Each
  one sets it on the row or goes through the writer that stamps it.
* **Every `EventLogInput` member has an entry in the redaction field list.**
  The empty array (`[]`) is a valid entry: it records that no fields
  need redaction.
* **Every `EventLogInput` member has a producer.** The union stays free
  of members nothing writes.

Apply the [tenant RLS schema tier](/docs/compliance#the-tenant-rls-schema-tier) and run `auditRlsPolicies()` on your own
database.

Together they close the loop: the runtime stamps the partition at the
row, the tenant policies enforce it at read time, and the redaction
list covers every event type core writes.

## What this facet is NOT [#what-this-facet-is-not]

* **Not auth.** The facet records *who* the active tenant is; auth
  decides *whether* the caller may act as that tenant. Wire your
  auth layer in front of construction; the facet trusts what it's
  given.
* **Not RLS itself.** The facet provides the value RLS checks
  against; RLS provides the enforcement. A correctly-stamped row
  with no RLS policy still leaks across tenants on a service-role
  query.
* **Not a billing meter.** For per-tenant billing, join
  the event log to your billing table on the tenant — see
  [Observability § billing join](/docs/observability) for the
  pattern. The facet stamps the partition key; the meter is a
  consumer surface.

## Where to go next [#where-to-go-next]

<Cards>
  <Card title="Multi-tenant deployments" href="/docs/multi-tenant" description="The operations guide — RLS templates, per-tenant cost rollups, deployment checklist." />

  <Card title="Multi-tenant SaaS agent" href="/docs/multi-tenant-saas-agent" description="The use-case shape — per-tenant agents in a SaaS, the recurring product pattern this primitive serves." />

  <Card title="Facets" href="/docs/facets" description="The facet model and why typed accessors are the stable surface plugins should target." />

  <Card title="OTel observability" href="/docs/otel-observability" description="`pleach.tenant_id`, `pleach.sub_tenant_id`, and the rest of the substrate's OTel attribute catalog." />

  <Card title="SessionRuntime" href="/docs/session-runtime" description="The constructor that takes `tenantId` and `subTenantId` and threads them into the facet." />
</Cards>
