This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-lamport-clock-tuple-mutation-ordering-standard

Strict Monotonic Lamport Clock Ordering for OpenFGA Tuple Mutations and Cache Invalidation

Enforces strict monotonic Lamport timestamp validation and atomic compare-and-swap state transitions across distributed Zanzibar authorization caches and tuple change streams. Eliminates time-of-check to time-of-use (TOCTOU) authorization windows and stale permissions resulting from out-of-order tuple ingestion across horizontally scaled evaluators. Guarantees that late-arriving revoke mutations are never overwritten or masked by superseded grant events.

Prohibited Anti-Pattern: Unordered Asynchronous Tuple Streaming Causing Phantom Authorization Windows in Distributed Caches

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Strict Monotonic Lamport Clock Ordering for OpenFGA Tuple Mutations and Cache Invalidation - Enforces strict monotonic Lamport timestamp validation and atomic compare-and-swap state transitions across distributed Zanzibar authorization caches and tuple change streams. Eliminates time-of-check to time-of-use (TOCTOU) authorization windows and stale permissions resulting from out-of-order tuple ingestion across horizontally scaled evaluators. Guarantees that late-arriving revoke mutations are never overwritten or masked by superseded grant events.
globs: src/authz/**/*.{ts,js,go}, src/cache/**/*.{ts,js,go}, src/events/**/*.{ts,js,go}, src/services/fga/**/*.{ts,js,go}, lib/security/**/*.{ts,js,go}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-lamport-clock-tuple-mutation-ordering-standard"
---

# Strict Monotonic Lamport Clock Ordering for OpenFGA Tuple Mutations and Cache Invalidation

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unordered Asynchronous Tuple Streaming Causing Phantom Authorization Windows in Distributed Caches

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA Real-Time Tuple Mutation Lamport Clock Ordering Standard. You must mandate that every OpenFGA relation tuple mutation, change data capture (CDC) event, and local cache update carries a strictly monotonic Lamport timestamp (sequence + node epoch). Never permit non-deterministic wall-clock timestamps or unversioned cache writes. Ensure that any out-of-order or duplicate tuple mutation is rejected via transactional compare-and-swap invariants, preventing authorization drift and phantom permission windows across horizontally scaled Zanzibar authorization caches.

## Strict Guidelines
- Engineers MUST ALWAYS embed an incrementing Lamport timestamp and a node/stream epoch identifier in every authorization tuple mutation payload written to OpenFGA and CDC message brokers.
- Engineers MUST NOT apply tuple updates or cache invalidations using wall-clock time (e.g., Date.now() or system epoch timestamps), which are susceptible to clock skew and NTP drift across nodes.
- Services MUST execute atomic Compare-And-Swap (CAS) or Lua script evaluations against the distributed authorization cache, updating cached relations if and only if incoming Lamport timestamp > current cached Lamport timestamp.
- Engineers MUST configure Change Data Capture (CDC) stream consumers to reject or route out-of-sequence mutations (where incoming Lamport timestamp <= high-water mark) to a dead-letter quarantine queue.
- Components NEVER drop or bypass Lamport sequence checks during batch tuple synchronization or catastrophic recovery re-sync operations.
- Code SHOULD enforce idempotency by recording the highest-seen Lamport sequence per bounded context key (user:relation:object) in durable Redis/KV storage with strict TTL parity.

## Bad vs Good Implementations
### Out-of-Order Cache Invalidation vs. Atomic Monotonic Lamport Validation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The handler blindly writes or deletes cache keys based on wall-clock time and network delivery order. If a 'DELETE' mutation precedes an out-of-order 'WRITE' in delivery, the cache restores unauthorized access indefinitely.
```typescript
import { Redis } from 'ioredis';

interface TupleMutation {
  user: string;
  relation: string;
  object: string;
  action: 'WRITE' | 'DELETE';
  wallClockTimestamp: number;
}

export async function handleTupleEvent(redis: Redis, event: TupleMutation): Promise<void> {
  const cacheKey = `fga:${event.user}:${event.relation}:${event.object}`;
  
  // CRITICAL SECURITY FLAW: Uses wall-clock timestamp without monotonic validation.
  // Out-of-order network arrival will overwrite a newer DELETE with a stale WRITE,
  // leading to persistent unauthorized access.
  if (event.action === 'WRITE') {
    await redis.set(cacheKey, 'ALLOWED');
  } else {
    await redis.del(cacheKey);
  }
}
```

#### Production Standard (Correct)
> **Standard**: Atomic Redis Lua execution checks the incoming Lamport timestamp against the current state. Stale or out-of-sequence mutations are discarded, completely preventing race conditions and unauthorized caching windows.
```typescript
import { Redis } from 'ioredis';

export interface MonotonicTupleMutation {
  user: string;
  relation: string;
  object: string;
  action: 'WRITE' | 'DELETE';
  lamportClock: number;
  streamEpoch: number;
}

// Atomic CAS script using Redis EVAL to enforce strict monotonic progression
const MONOTONIC_CACHE_UPDATE_LUA = `
  local key = KEYS[1]
  local action = ARGV[1]
  local incomingLamport = tonumber(ARGV[2])
  local ttlSeconds = tonumber(ARGV[3])

  local currentLamport = tonumber(redis.call('HGET', key, 'lamport') or '-1')

  if incomingLamport <= currentLamport then
    -- Stale or duplicate tuple mutation; reject update to preserve safety
    return 0
  end

  redis.call('HSET', key, 'status', action, 'lamport', incomingLamport)
  redis.call('EXPIRE', key, ttlSeconds)
  return 1
`;

export async function applyMonotonicTupleMutation(
  redis: Redis,
  event: MonotonicTupleMutation,
  ttlSeconds = 300
): Promise<boolean> {
  const cacheKey = `fga:tuple:${event.user}#${event.relation}@${event.object}`;

  const result = await redis.eval(
    MONOTONIC_CACHE_UPDATE_LUA,
    1,
    cacheKey,
    event.action,
    event.lamportClock.toString(),
    ttlSeconds.toString()
  );

  return result === 1;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Strict Monotonic Lamport Clock Ordering for OpenFGA Tuple Mutations and Cache Invalidation

Strict Monotonic Lamport Clock Ordering for OpenFGA Tuple Mutations and Cache Invalidation defines an industrial-grade behavioral standard for security engineering. Enforces strict monotonic Lamport timestamp validation and atomic compare-and-swap state transitions across distributed Zanzibar authorization caches and tuple change streams. Eliminates time-of-check to time-of-use (TOCTOU) authorization windows and stale permissions resulting from out-of-order tuple ingestion across horizontally scaled evaluators. Guarantees that late-arriving revoke mutations are never overwritten or masked by superseded grant events. 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: Unordered Asynchronous Tuple Streaming Causing Phantom Authorization Windows in Distributed Caches 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 DriftUnordered Asynchronous Tuple Streaming Causing Phantom Authorization Windows in Distributed CachesCritical
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 embed an incrementing Lamport timestamp and a node/stream epoch identifier in every authorization tuple mutation payload written to OpenFGA and CDC message brokers.

Engineers MUST ALWAYS embed an incrementing Lamport timestamp and a node/stream epoch identifier in every authorization tuple mutation payload written to OpenFGA and CDC message brokers.

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 apply tuple updates or cache invalidations using wall-clock time (e.g., Date.now() or system epoch timestamps), which are susceptible to clock skew and NTP drift across nodes.

Engineers MUST NOT apply tuple updates or cache invalidations using wall-clock time (e.g., Date.now() or system epoch timestamps), which are susceptible to clock skew and NTP drift across nodes.

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

Services MUST execute atomic Compare-And-Swap (CAS) or Lua script evaluations against the distributed authorization cache, updating cached relations if and only if incoming Lamport timestamp > current cached Lamport timestamp.

Services MUST execute atomic Compare-And-Swap (CAS) or Lua script evaluations against the distributed authorization cache, updating cached relations if and only if incoming Lamport timestamp > current cached Lamport timestamp.

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

Engineers MUST configure Change Data Capture (CDC) stream consumers to reject or route out-of-sequence mutations (where incoming Lamport timestamp <= high-water mark) to a dead-letter quarantine queue.

Engineers MUST configure Change Data Capture (CDC) stream consumers to reject or route out-of-sequence mutations (where incoming Lamport timestamp <= high-water mark) to a dead-letter quarantine queue.

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 drop or bypass Lamport sequence checks during batch tuple synchronization or catastrophic recovery re-sync operations.

Components NEVER drop or bypass Lamport sequence checks during batch tuple synchronization or catastrophic recovery re-sync operations.

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.
6

Code SHOULD enforce idempotency by recording the highest-seen Lamport sequence per bounded context key (user

Code SHOULD enforce idempotency by recording the highest-seen Lamport sequence per bounded context key (user:relation:object) in durable Redis/KV storage with strict TTL parity.

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 Strict Monotonic Lamport Clock Ordering for OpenFGA Tuple Mutations and Cache Invalidation critical for AI coding assistants?

Enforces strict monotonic Lamport timestamp validation and atomic compare-and-swap state transitions across distributed Zanzibar authorization caches and tuple change streams. Eliminates time-of-check to time-of-use (TOCTOU) authorization windows and stale permissions resulting from out-of-order tuple ingestion across horizontally scaled evaluators. Guarantees that late-arriving revoke mutations are never overwritten or masked by superseded grant events. 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 (Unordered Asynchronous Tuple Streaming Causing Phantom Authorization Windows in Distributed Caches) 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

Strict