This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-modular-schema-migration-invariant

OpenFGA Modular Schema Migration and Staged Dual-Model Deployment Invariant

Enforces backward-compatible Relationship-Based Access Control (ReBAC) evaluations across distributed OpenFGA topologies during modular schema evolution. Prohibits in-place relation deprecation and immediate default authorization model re-pointing without dual-writing tuples and executing staged shadow-evaluation phases. Eliminates transient authorization denial-of-service, split-brain graph resolution, and privilege escalation during asynchronous multi-region cutovers.

Prohibited Anti-Pattern: Direct Model Cutover and Immediate Tuple Re-Typing Without Dual-Model Ingestion Staging

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Modular Schema Migration and Staged Dual-Model Deployment Invariant - Enforces backward-compatible Relationship-Based Access Control (ReBAC) evaluations across distributed OpenFGA topologies during modular schema evolution. Prohibits in-place relation deprecation and immediate default authorization model re-pointing without dual-writing tuples and executing staged shadow-evaluation phases. Eliminates transient authorization denial-of-service, split-brain graph resolution, and privilege escalation during asynchronous multi-region cutovers.
globs: fga/**/*.fga, fga/**/fga.mod, src/**/authz/**/*.{ts,tsx}, src/**/authorization/**/*.{ts,tsx}, migrations/**/authz/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-modular-schema-migration-invariant"
---

# OpenFGA Modular Schema Migration and Staged Dual-Model Deployment Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Direct Model Cutover and Immediate Tuple Re-Typing Without Dual-Model Ingestion Staging

## System Constraints
You are a Principal Security Architect specializing in OpenFGA and Relationship-Based Access Control (ReBAC). You must enforce the staged dual-model migration pipeline for all OpenFGA schema revisions and tuple alterations. Never allow destructive or breaking relation mutations within existing modular boundaries without strict schema compilation, dual-write tuple lifecycle management, and explicit version-pinned evaluations across distributed stores.

## Strict Guidelines
- Engineers MUST ALWAYS enforce the 4-phase migration pattern: Phase 1 (Deploy compiled model without activating as store default), Phase 2 (Dual-write tuples compatible with both old and new relation schemas), Phase 3 (Canary/shadow read evaluations pinned by explicit authorization_model_id), Phase 4 (Promote new authorization_model_id and deprecate legacy tuples).
- Engineers MUST NOT delete relations, rename relations, or contract type restrictions in OpenFGA modular schemas without introducing an interim aliased relation that retains identical graph expansions during the migration window.
- Engineers MUST NOT execute check/batchCheck queries omitting an explicit 'authorization_model_id' during an active migration window; queries MUST pin the model ID to ensure deterministic graph evaluation across distributed edge caches.
- Services MUST implement idempotent tuple synchronization where tuples are written with transactional guarantees or dual-written across both legacy and prospective relation definitions before read cutover.
- Code MUST validate OpenFGA modular schemas using `fga model test` and compiler AST analysis prior to CI/CD artifact publication to guarantee no cycles or orphaned relation targets are introduced.

## Bad vs Good Implementations
### OpenFGA Model Migration & Tuple Ingestion Pipeline

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly replacing the 'viewer' tuple with 'reader' breaks in-flight and cached read queries on any service instance still relying on the prior authorization model schema. Omitting an explicit authorization_model_id invites transient denial of access or incorrect authorization responses during progressive regional rollouts.
```typescript
// BAD: Direct model update with immediate tuple mutation and unpinned checks
import { OpenFgaClient } from '@openfga/sdk';

const fgaClient = new OpenFgaClient({
  apiUrl: process.env.FGA_API_URL!,
  storeId: process.env.FGA_STORE_ID!,
});

export async function updateDocumentAccess(docId: string, userId: string) {
  // Anti-pattern: Renaming 'viewer' to 'reader' directly without staged fallback
  // Deleting 'viewer' and writing only 'reader' breaks clients on the older model
  await fgaClient.write({
    deletes: [{ user: `user:${userId}`, relation: 'viewer', object: `doc:${docId}` }],
    writes: [{ user: `user:${userId}`, relation: 'reader', object: `doc:${docId}` }],
  });

  // Anti-pattern: Omission of authorization_model_id defaults to store latest,
  // causing non-deterministic checks across distributed nodes during rollout.
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'reader',
    object: `doc:${docId}`,
  });

  return response.allowed;
}
```

#### Production Standard (Correct)
> **Standard**: The good example encapsulates authorization changes within a phased lifecycle. During the migration window, dual-writes ensure that both legacy ('viewer') and modern ('reader') relations coexist in the tuple store. Access checks strictly specify the target authorizationModelId, avoiding non-deterministic store-default lookups.
```typescript
// GOOD: Staged dual-write with explicit model pinning and phase-aware resolution
import { OpenFgaClient } from '@openfga/sdk';

interface MigrationContext {
  activeModelId: string;
  targetModelId: string;
  isDualWritePhase: boolean;
}

export class ResilientAuthorizationService {
  constructor(
    private readonly fgaClient: OpenFgaClient,
    private readonly context: MigrationContext
  ) {}

  public async grantDocumentAccess(docId: string, userId: string): Promise<void> {
    const userTuple = `user:${userId}`;
    const objectTuple = `doc:${docId}`;

    if (this.context.isDualWritePhase) {
      // Phase 2: Dual-write to both legacy and prospective relations atomically
      await this.fgaClient.write({
        writes: [
          { user: userTuple, relation: 'viewer', object: objectTuple },
          { user: userTuple, relation: 'reader', object: objectTuple }
        ]
      });
      return;
    }

    await this.fgaClient.write({
      writes: [{ user: userTuple, relation: 'reader', object: objectTuple }]
    });
  }

  public async checkDocumentAccess(docId: string, userId: string): Promise<boolean> {
    // Pin explicitly to target model ID to prevent split-brain edge evaluation
    const response = await this.fgaClient.check(
      {
        user: `user:${userId}`,
        relation: 'reader',
        object: `doc:${docId}`,
      },
      {
        authorizationModelId: this.context.targetModelId
      }
    );

    return response.allowed ?? false;
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Modular Schema Migration and Staged Dual-Model Deployment Invariant

OpenFGA Modular Schema Migration and Staged Dual-Model Deployment Invariant defines an industrial-grade behavioral standard for security engineering. Enforces backward-compatible Relationship-Based Access Control (ReBAC) evaluations across distributed OpenFGA topologies during modular schema evolution. Prohibits in-place relation deprecation and immediate default authorization model re-pointing without dual-writing tuples and executing staged shadow-evaluation phases. Eliminates transient authorization denial-of-service, split-brain graph resolution, and privilege escalation during asynchronous multi-region cutovers. 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: Direct Model Cutover and Immediate Tuple Re-Typing Without Dual-Model Ingestion Staging 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 DriftDirect Model Cutover and Immediate Tuple Re-Typing Without Dual-Model Ingestion StagingCritical
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 enforce the 4-phase migration pattern

Engineers MUST ALWAYS enforce the 4-phase migration pattern: Phase 1 (Deploy compiled model without activating as store default), Phase 2 (Dual-write tuples compatible with both old and new relation schemas), Phase 3 (Canary/shadow read evaluations pinned by explicit authorization_model_id), Phase 4 (Promote new authorization_model_id and deprecate legacy tuples).

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 delete relations, rename relations, or contract type restrictions in OpenFGA modular schemas without introducing an interim aliased relation that retains identical graph expansions during the migration window.

Engineers MUST NOT delete relations, rename relations, or contract type restrictions in OpenFGA modular schemas without introducing an interim aliased relation that retains identical graph expansions during the migration window.

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

Engineers MUST NOT execute check/batchCheck queries omitting an explicit 'authorization_model_id' during an active migration window

Engineers MUST NOT execute check/batchCheck queries omitting an explicit 'authorization_model_id' during an active migration window; queries MUST pin the model ID to ensure deterministic graph evaluation across distributed edge caches.

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 implement idempotent tuple synchronization where tuples are written with transactional guarantees or dual-written across both legacy and prospective relation definitions before read cutover.

Services MUST implement idempotent tuple synchronization where tuples are written with transactional guarantees or dual-written across both legacy and prospective relation definitions before read cutover.

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

Code MUST validate OpenFGA modular schemas using `fga model test` and compiler AST analysis prior to CI/CD artifact publication to guarantee no cycles or orphaned relation targets are introduced.

Code MUST validate OpenFGA modular schemas using `fga model test` and compiler AST analysis prior to CI/CD artifact publication to guarantee no cycles or orphaned relation targets are introduced.

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 Modular Schema Migration and Staged Dual-Model Deployment Invariant critical for AI coding assistants?

Enforces backward-compatible Relationship-Based Access Control (ReBAC) evaluations across distributed OpenFGA topologies during modular schema evolution. Prohibits in-place relation deprecation and immediate default authorization model re-pointing without dual-writing tuples and executing staged shadow-evaluation phases. Eliminates transient authorization denial-of-service, split-brain graph resolution, and privilege escalation during asynchronous multi-region cutovers. 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 (Direct Model Cutover and Immediate Tuple Re-Typing Without Dual-Model Ingestion Staging) 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