This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-contextual-tuple-temporal-partitioning

OpenFGA 1.6 Contextual Tuple Temporal Invariant and Evaluation Partitioning

Mandates absolute segregation between persistent graph authorization tuples and ephemeral, request-scoped contextual tuples within OpenFGA 1.6+ evaluation paths. Enforces strictly bounded contextual tuple payloads and temporal condition partitioning to guarantee sub-millisecond evaluation without store cache degradation or unbounded cycle traversal.

Prohibited Anti-Pattern: Persisting ephemeral session states to the authorization datastore or passing unbounded contextual tuples across transitive traversal boundaries.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA 1.6 Contextual Tuple Temporal Invariant and Evaluation Partitioning - Mandates absolute segregation between persistent graph authorization tuples and ephemeral, request-scoped contextual tuples within OpenFGA 1.6+ evaluation paths. Enforces strictly bounded contextual tuple payloads and temporal condition partitioning to guarantee sub-millisecond evaluation without store cache degradation or unbounded cycle traversal.
globs: src/**/auth*/**/*.ts, src/**/authorization/**/*.ts, src/**/permissions/**/*.ts, src/**/fga/**/*.ts, src/**/guards/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-temporal-partitioning"
---

# OpenFGA 1.6 Contextual Tuple Temporal Invariant and Evaluation Partitioning

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Persisting ephemeral session states to the authorization datastore or passing unbounded contextual tuples across transitive traversal boundaries.

## System Constraints
You are a Principal Security Architect enforcing OpenFGA 1.6 Contextual Tuple Temporal Invariant & Evaluation Partitioning. Mandate that ephemeral, high-churn, or request-scoped states (e.g., temporal step-up authentication, geo-location boundaries, IP claims, temporary emergency access) MUST NEVER be written to the persistent OpenFGA storage engine. Instead, these assertions MUST be partitioned into request-scoped contextual tuples or evaluated using OpenFGA 1.6 CEL conditions. Enforce strict limits on contextual tuple cardinality to preserve the sub-millisecond sub-graph evaluation invariants.

## Strict Guidelines
- Engineers MUST ALWAYS supply ephemeral attributes (such as active MFA session, ephemeral break-glass access, or dynamic environmental context) exclusively via `contextualTuples` or OpenFGA 1.6+ CEL `context` on evaluation calls (`check`, `listObjects`).
- Engineers MUST NOT write ephemeral, short-lived (< 24 hours), or high-velocity state changes into persistent OpenFGA storage via `write` or `writeTuples` to avoid storage write amplification, database locks, and cache thrashing.
- Code MUST partition contextual tuples so they only bridge direct relationship boundaries and NEVER introduce cycles or unbounded transitive user sets into the evaluation graph.
- Services MUST enforce a strict upper bound (maximum 10 tuples per request) on contextual tuple injection to maintain sub-millisecond P99 resolution latencies.
- Components NEVER pass untrusted, unvalidated client claims directly into contextual tuples without cryptographically verifying upstream token signatures and timestamp freshness.

## Bad vs Good Implementations
### Ephemeral Step-Up Authorization Evaluation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Writing ephemeral MFA state to the persistent datastore introduces significant disk I/O, cache invalidation across the OpenFGA cluster, replication lag races, and necessitates brittle distributed cleanup workers. It violates temporal isolation invariants.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export async function verifyTransferAccess(
  fgaClient: OpenFgaClient,
  userId: string,
  transactionId: string,
  mfaValidated: boolean,
  mfaExpiresAt: Date
): Promise<boolean> {
  // ANTI-PATTERN: Persisting ephemeral/temporal state into persistent store.
  // Causes storage bloat, race conditions, cache thrashing, and requires cleanup jobs.
  if (mfaValidated && mfaExpiresAt > new Date()) {
    await fgaClient.write({
      writes: [
        {
          user: `user:${userId}`,
          relation: 'mfa_authenticated_actor',
          object: `transaction:${transactionId}`
        }
      ]
    });
  }

  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'can_execute',
    object: `transaction:${transactionId}`
  });

  return allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: Ephemeral MFA authentication is partitioned into a memory-only contextual tuple attached directly to the single evaluation request. Persistent storage remains immutable, caches remain warm, and access resolution occurs sub-millisecond.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

interface EphemeralTransferContext {
  userId: string;
  transactionId: string;
  mfaVerifiedAt: Date;
  ttlSeconds: number;
}

export async function verifyTransferAccess(
  fgaClient: OpenFgaClient,
  context: EphemeralTransferContext
): Promise<boolean> {
  const now = Date.now();
  const mfaValidUntil = context.mfaVerifiedAt.getTime() + context.ttlSeconds * 1000;

  // INVARIANT: Isolate ephemeral session claims to request-scoped contextual tuples
  // Evaluated entirely in-memory by OpenFGA without persistent storage mutations.
  const checkPayload: ClientCheckRequest = {
    user: `user:${context.userId}`,
    relation: 'can_execute',
    object: `transaction:${context.transactionId}`,
    contextualTuples: mfaValidUntil > now
      ? [
          {
            user: `user:${context.userId}`,
            relation: 'mfa_authenticated_actor',
            object: `transaction:${context.transactionId}`
          }
        ]
      : [],
    context: {
      current_time: new Date(now).toISOString()
    }
  };

  const response = await fgaClient.check(checkPayload);
  return response.allowed ?? false;
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA 1.6 Contextual Tuple Temporal Invariant and Evaluation Partitioning

OpenFGA 1.6 Contextual Tuple Temporal Invariant and Evaluation Partitioning defines an industrial-grade behavioral standard for security engineering. Mandates absolute segregation between persistent graph authorization tuples and ephemeral, request-scoped contextual tuples within OpenFGA 1.6+ evaluation paths. Enforces strictly bounded contextual tuple payloads and temporal condition partitioning to guarantee sub-millisecond evaluation without store cache degradation or unbounded cycle traversal. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Persisting ephemeral session states to the authorization datastore or passing unbounded contextual tuples across transitive traversal boundaries. Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftPersisting ephemeral session states to the authorization datastore or passing unbounded contextual tuples across transitive traversal boundaries.Critical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS supply ephemeral attributes (such as active MFA session, ephemeral break-glass access, or dynamic environmental context) exclusively via `contextualTuples` or OpenFGA 1.6+ CEL `context` on evaluation calls (`check`, `listObjects`).

Engineers MUST ALWAYS supply ephemeral attributes (such as active MFA session, ephemeral break-glass access, or dynamic environmental context) exclusively via `contextualTuples` or OpenFGA 1.6+ CEL `context` on evaluation calls (`check`, `listObjects`).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT write ephemeral, short-lived (< 24 hours), or high-velocity state changes into persistent OpenFGA storage via `write` or `writeTuples` to avoid storage write amplification, database locks, and cache thrashing.

Engineers MUST NOT write ephemeral, short-lived (< 24 hours), or high-velocity state changes into persistent OpenFGA storage via `write` or `writeTuples` to avoid storage write amplification, database locks, and cache thrashing.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Code MUST partition contextual tuples so they only bridge direct relationship boundaries and NEVER introduce cycles or unbounded transitive user sets into the evaluation graph.

Code MUST partition contextual tuples so they only bridge direct relationship boundaries and NEVER introduce cycles or unbounded transitive user sets into the evaluation graph.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST enforce a strict upper bound (maximum 10 tuples per request) on contextual tuple injection to maintain sub-millisecond P99 resolution latencies.

Services MUST enforce a strict upper bound (maximum 10 tuples per request) on contextual tuple injection to maintain sub-millisecond P99 resolution latencies.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER pass untrusted, unvalidated client claims directly into contextual tuples without cryptographically verifying upstream token signatures and timestamp freshness.

Components NEVER pass untrusted, unvalidated client claims directly into contextual tuples without cryptographically verifying upstream token signatures and timestamp freshness.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is OpenFGA 1.6 Contextual Tuple Temporal Invariant and Evaluation Partitioning critical for AI coding assistants?

Mandates absolute segregation between persistent graph authorization tuples and ephemeral, request-scoped contextual tuples within OpenFGA 1.6+ evaluation paths. Enforces strictly bounded contextual tuple payloads and temporal condition partitioning to guarantee sub-millisecond evaluation without store cache degradation or unbounded cycle traversal. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Persisting ephemeral session states to the authorization datastore or passing unbounded contextual tuples across transitive traversal boundaries.) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

OpenFGA