This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-modular-compilation-cycle-detection-standard

OpenFGA Modular Authorization Model Compilation and Cycle Detection Standard

Enforces strict static graph cycle detection and validation during the compilation phase of OpenFGA modular authorization models. Prevents unconstrained recursive relation expansion (such as nested group hierarchies or cross-module tuple-to-userset cycles) that trigger evaluation engine timeouts, Denial of Service (DoS), or runaway latency in production Check calls.

Prohibited Anti-Pattern: Unvalidated Cross-Module Tupleset Recursion Causing Infinite Check Evaluation and Engine Starvation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Modular Authorization Model Compilation and Cycle Detection Standard - Enforces strict static graph cycle detection and validation during the compilation phase of OpenFGA modular authorization models. Prevents unconstrained recursive relation expansion (such as nested group hierarchies or cross-module tuple-to-userset cycles) that trigger evaluation engine timeouts, Denial of Service (DoS), or runaway latency in production Check calls.
globs: **/fga/**/*.fga, **/fga/**/*.json, **/authz/**/*.ts, **/security/authorization/**/*.ts, **/models/**/*.fga.yaml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-modular-compilation-cycle-detection-standard"
---

# OpenFGA Modular Authorization Model Compilation and Cycle Detection Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unvalidated Cross-Module Tupleset Recursion Causing Infinite Check Evaluation and Engine Starvation

## System Constraints
You are a Principal Security Architect specializing in Fine-Grained Authorization (ReBAC) and OpenFGA compiler internals. Enforce strict compile-time cycle detection and depth validation for modular OpenFGA authorization models. Reject any modular schema integration that introduces circular relation dependencies across module boundaries or permits unconstrained indirect relation loops without an invariant acyclic compilation pass.

## Strict Guidelines
- Engineers MUST ALWAYS run a compile-time static dependency graph validation across all modular `.fga` files before deploying or publishing a new Authorization Model ID.
- Engineers MUST NOT introduce circular relation definitions across modular boundaries (e.g., Module A `folder#parent -> folder` referencing Module B `document#parent -> folder` which in turn loops back via `viewer` tuple-to-userset definitions).
- Services MUST invoke `@openfga/sdk` compilation utilities or the official OpenFGA CLI compile step with cycle verification within CI/CD pipelines to fail builds before migration execution.
- Code SHOULD build a Directed Acyclic Graph (DAG) representation of relation-to-relation projections using Tarjan's or Kosaraju's Strongly Connected Components (SCC) algorithm to detect non-trivial recursive cycles.
- Components NEVER evaluate dynamically constructed authorization tuples at runtime without guaranteeing that the corresponding schema relation graph was verified as finite and cycle-free during compile time.

## Bad vs Good Implementations
### Modular OpenFGA Compilation with Static Cycle Validation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Modular schemas from multiple teams are concatenated and deployed directly without compile-time graph validation. Circular relation paths (such as nested group memberships or cross-type tuple-to-userset links) pass JSON syntax validation but cause runtime evaluation deadlocks, thread pool exhaustion, and cascading service outages on OpenFGA Check calls.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import * as fs from 'fs';

// ANTI-PATTERN: Blindly reading modular manifests and deploying without cycle or SCC validation
export async function deployAuthorizationModel(client: OpenFgaClient, modelJsonPath: string) {
  const rawModel = fs.readFileSync(modelJsonPath, 'utf-8');
  const model = JSON.parse(rawModel);

  // Deploying directly to production OpenFGA store.
  // If modular relations have mutual dependency cycles (e.g. org -> team -> project -> org),
  // runtime 'client.check()' calls will spin into recursive depth exhaustion or 504 timeouts.
  const response = await client.writeAuthorizationModel(model);
  return response.authorization_model_id;
}
```

#### Production Standard (Correct)
> **Standard**: Implements an explicit graph cycle detection pass using DFS traversal on the authorization model's AST prior to store deployment. By inspecting computed usersets and tuple-to-userset rewrites, it guarantees that circular dependencies across modules are detected and rejected at compile time, eliminating runaway recursion and latency spikes in production.
```typescript
import { OpenFgaClient, TypeDefinition, RelationMetadata } from '@openfga/sdk';
import * as fs from 'fs';

interface DependencyGraph {
  [node: string]: Set<string>;
}

export class AuthorizationModelCompiler {
  private static buildNodeKey(type: string, relation: string): string {
    return `${type}#${relation}`;
  }

  public static detectCycles(typeDefinitions: TypeDefinition[]): void {
    const adjList: DependencyGraph = {};

    for (const typeDef of typeDefinitions) {
      const type = typeDef.type;
      if (!typeDef.relations) continue;

      for (const [relation, rewrite] of Object.entries(typeDef.relations)) {
        const sourceKey = this.buildNodeKey(type, relation);
        if (!adjList[sourceKey]) adjList[sourceKey] = new Set();

        // Traverse userset rewrites (this, computedUserset, tupleToUserset)
        const targetRelations = this.extractReferencedRelations(rewrite, typeDef.metadata?.relations?.[relation]);
        for (const target of targetRelations) {
          adjList[sourceKey].add(target);
        }
      }
    }

    // Execute Tarjan's / DFS cycle detection
    const visited = new Set<string>();
    const recStack = new Set<string>();

    for (const node of Object.keys(adjList)) {
      if (this.hasCycleDFS(node, adjList, visited, recStack)) {
        throw new Error(`OpenFGA Schema Compilation Error: Cyclic relation dependency detected involving '${node}'`);
      }
    }
  }

  private static extractReferencedRelations(rewrite: any, metadata?: RelationMetadata): string[] {
    const targets: string[] = [];
    if (!rewrite) return targets;

    if (rewrite.computedUserset) {
      targets.push(rewrite.computedUserset.relation);
    }
    if (rewrite.tupleToUserset) {
      targets.push(rewrite.tupleToUserset.computedUserset.relation);
    }
    if (rewrite.union) {
      rewrite.union.child?.forEach((c: any) => targets.push(...this.extractReferencedRelations(c, metadata)));
    }
    if (rewrite.intersection) {
      rewrite.intersection.child?.forEach((c: any) => targets.push(...this.extractReferencedRelations(c, metadata)));
    }
    return targets;
  }

  private static hasCycleDFS(node: string, graph: DependencyGraph, visited: Set<string>, recStack: Set<string>): boolean {
    if (!visited.has(node)) {
      visited.add(node);
      recStack.add(node);

      for (const neighbor of graph[node] || []) {
        if (!visited.has(neighbor) && this.hasCycleDFS(neighbor, graph, visited, recStack)) {
          return true;
        } else if (recStack.has(neighbor)) {
          return true;
        }
      }
    }
    recStack.delete(node);
    return false;
  }
}

export async function deployAuthorizationModel(client: OpenFgaClient, modelJsonPath: string): Promise<string> {
  const rawModel = JSON.parse(fs.readFileSync(modelJsonPath, 'utf-8'));
  
  // Guardrail: Static cycle detection pass across compiled modular type definitions
  AuthorizationModelCompiler.detectCycles(rawModel.type_definitions);

  const response = await client.writeAuthorizationModel(rawModel);
  return response.authorization_model_id;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Modular Authorization Model Compilation and Cycle Detection Standard

OpenFGA Modular Authorization Model Compilation and Cycle Detection Standard defines an industrial-grade behavioral standard for security engineering. Enforces strict static graph cycle detection and validation during the compilation phase of OpenFGA modular authorization models. Prevents unconstrained recursive relation expansion (such as nested group hierarchies or cross-module tuple-to-userset cycles) that trigger evaluation engine timeouts, Denial of Service (DoS), or runaway latency in production Check calls. 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: Unvalidated Cross-Module Tupleset Recursion Causing Infinite Check Evaluation and Engine Starvation 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 DriftUnvalidated Cross-Module Tupleset Recursion Causing Infinite Check Evaluation and Engine StarvationCritical
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 run a compile-time static dependency graph validation across all modular `.fga` files before deploying or publishing a new Authorization Model ID.

Engineers MUST ALWAYS run a compile-time static dependency graph validation across all modular `.fga` files before deploying or publishing a new Authorization Model ID.

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 introduce circular relation definitions across modular boundaries (e.g., Module A `folder#parent -> folder` referencing Module B `document#parent -> folder` which in turn loops back via `viewer` tuple-to-userset definitions).

Engineers MUST NOT introduce circular relation definitions across modular boundaries (e.g., Module A `folder#parent -> folder` referencing Module B `document#parent -> folder` which in turn loops back via `viewer` tuple-to-userset definitions).

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 invoke `@openfga/sdk` compilation utilities or the official OpenFGA CLI compile step with cycle verification within CI/CD pipelines to fail builds before migration execution.

Services MUST invoke `@openfga/sdk` compilation utilities or the official OpenFGA CLI compile step with cycle verification within CI/CD pipelines to fail builds before migration execution.

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

Code SHOULD build a Directed Acyclic Graph (DAG) representation of relation-to-relation projections using Tarjan's or Kosaraju's Strongly Connected Components (SCC) algorithm to detect non-trivial recursive cycles.

Code SHOULD build a Directed Acyclic Graph (DAG) representation of relation-to-relation projections using Tarjan's or Kosaraju's Strongly Connected Components (SCC) algorithm to detect non-trivial recursive cycles.

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 evaluate dynamically constructed authorization tuples at runtime without guaranteeing that the corresponding schema relation graph was verified as finite and cycle-free during compile time.

Components NEVER evaluate dynamically constructed authorization tuples at runtime without guaranteeing that the corresponding schema relation graph was verified as finite and cycle-free during compile time.

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 Authorization Model Compilation and Cycle Detection Standard critical for AI coding assistants?

Enforces strict static graph cycle detection and validation during the compilation phase of OpenFGA modular authorization models. Prevents unconstrained recursive relation expansion (such as nested group hierarchies or cross-module tuple-to-userset cycles) that trigger evaluation engine timeouts, Denial of Service (DoS), or runaway latency in production Check calls. 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 (Unvalidated Cross-Module Tupleset Recursion Causing Infinite Check Evaluation and Engine Starvation) 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