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

OpenFGA 1.6 Modular Model Schema Static Acyclic & Cycle-Detection Standard

Mandates compile-time static acyclic graph verification across federated OpenFGA 1.6 modular authorization models prior to runtime registration. Circular relation expansions across distributed module files induce unbounded tuple resolution and severe Denial-of-Service (DoS) during Check and ListObjects queries. Strict automated cycle analysis guarantees provable termination bounds for recursive graph traversals.

Prohibited Anti-Pattern: Unvalidated Cross-Module Cyclic Relation References Inducing Recursive Expansion Denial of Service

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA 1.6 Modular Model Schema Static Acyclic & Cycle-Detection Standard - Mandates compile-time static acyclic graph verification across federated OpenFGA 1.6 modular authorization models prior to runtime registration. Circular relation expansions across distributed module files induce unbounded tuple resolution and severe Denial-of-Service (DoS) during Check and ListObjects queries. Strict automated cycle analysis guarantees provable termination bounds for recursive graph traversals.
globs: fga.mod, **/*.fga, src/authz/**/*.ts, src/authorization/**/*.json
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-modular-schema-acyclic-validation"
---

# OpenFGA 1.6 Modular Model Schema Static Acyclic & Cycle-Detection Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unvalidated Cross-Module Cyclic Relation References Inducing Recursive Expansion Denial of Service

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA 1.6 Modular Model Schema Cycle-Detection Standard. You must ensure that all fine-grained authorization schemas defined across modular OpenFGA files (fga.mod) are statically validated for acyclic dependencies. Reject any modular schema that introduces unconstrained mutual recursion across types and relations or bypasses static topological sorting during CI/CD pre-flight checks.

## Strict Guidelines
- Engineers MUST ALWAYS run static acyclic graph analysis across all modular schema files (`.fga`) defined in `fga.mod` during build time before publishing models to an OpenFGA store.
- Engineers MUST NOT define mutual transitive relations across modular boundaries (e.g., `folder#parent` referencing `workspace#folder` which references `folder#parent`) without strict directional hierarchy or terminal non-recursive base conditions.
- Code MUST integrate `@openfga/cli` validation (`fga model validate --type fga.mod`) into automated pre-commit and deployment pipelines.
- Services MUST enforce bounded query resolution depths on client check invocations (`client.check({ ... }, { max_depth: 25 })`) as an in-depth defensive runtime barrier against unexpected cycle traversals.
- Components NEVER execute raw dynamic authorization model updates directly against production clusters without cryptographic artifact digest hashing and static validation verification.

## Bad vs Good Implementations
### Modular Schema Ingestion and Static Cycle Validation in CI/CD Pre-flight

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly writing unvalidated modular authorization schemas allows circular dependencies between distinct modules to be deployed. During Check or ListObjects evaluation, cyclic relations cause exponential recursion, thread pool exhaustion, and catastrophic denial of service.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import * as fs from 'fs';

// ANTI-PATTERN: Blindly writing unverified modular schemas to the store
export async function deployAuthorizationModel(client: OpenFgaClient, schemaPath: string): Promise<string> {
  const rawSchema = JSON.parse(fs.readFileSync(schemaPath, 'utf8'));

  // Deploying without cycle detection allows cross-module recursive loops
  // (e.g., type group: relation member: [user, team#member]; type team: relation member: [group#member])
  // This causes infinite expansion and worker exhaustion during fga.check()
  const response = await client.writeAuthorizationModel(rawSchema);
  return response.authorization_model_id;
}
```

#### Production Standard (Correct)
> **Standard**: Validates the modular schemas deterministically using `fga model validate --type fga.mod` before compiling. If any circular relationships or unbounded recursive cross-module relations exist, deployment aborts prior to persisting to the store.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { execFileSync } from 'node:child_process';
import * as fs from 'fs';
import * as path from 'path';

// PRODUCTION FIX: Enforce deterministic acyclic validation before model compilation
export async function deployAuthorizationModelSecurely(
  client: OpenFgaClient,
  modRootDirectory: string
): Promise<string> {
  const modManifest = path.join(modRootDirectory, 'fga.mod');
  if (!fs.existsSync(modManifest)) {
    throw new Error('Security Error: Missing fga.mod manifest for modular validation');
  }

  // 1. Static cycle & dependency validation via OpenFGA Engine CLI
  try {
    execFileSync('fga',
      ['model', 'validate', '--type', 'fga.mod', '--file', modManifest],
      { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }
    );
  } catch (error) {
    throw new Error(`Model validation failed: Schema contains cyclic references or invalid types: ${String(error)}`);
  }

  // 2. Compile validated modular schemas into a single immutable artifact
  const compiledJson = execFileSync('fga',
    ['model', 'transform', '--type', 'fga.mod', '--file', modManifest, '--output-format', 'json'],
    { encoding: 'utf-8' }
  );

  const modelPayload = JSON.parse(compiledJson);

  // 3. Write model with verified acyclic guarantee
  const response = await client.writeAuthorizationModel(modelPayload);
  return response.authorization_model_id;
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA 1.6 Modular Model Schema Static Acyclic & Cycle-Detection Standard

OpenFGA 1.6 Modular Model Schema Static Acyclic & Cycle-Detection Standard defines an industrial-grade behavioral standard for security engineering. Mandates compile-time static acyclic graph verification across federated OpenFGA 1.6 modular authorization models prior to runtime registration. Circular relation expansions across distributed module files induce unbounded tuple resolution and severe Denial-of-Service (DoS) during Check and ListObjects queries. Strict automated cycle analysis guarantees provable termination bounds for recursive graph traversals. 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 Cyclic Relation References Inducing Recursive Expansion Denial of Service 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 Cyclic Relation References Inducing Recursive Expansion Denial of ServiceCritical
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 static acyclic graph analysis across all modular schema files (`.fga`) defined in `fga.mod` during build time before publishing models to an OpenFGA store.

Engineers MUST ALWAYS run static acyclic graph analysis across all modular schema files (`.fga`) defined in `fga.mod` during build time before publishing models to an OpenFGA store.

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 define mutual transitive relations across modular boundaries (e.g., `folder#parent` referencing `workspace#folder` which references `folder#parent`) without strict directional hierarchy or terminal non-recursive base conditions.

Engineers MUST NOT define mutual transitive relations across modular boundaries (e.g., `folder#parent` referencing `workspace#folder` which references `folder#parent`) without strict directional hierarchy or terminal non-recursive base conditions.

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 integrate `@openfga/cli` validation (`fga model validate --type fga.mod`) into automated pre-commit and deployment pipelines.

Code MUST integrate `@openfga/cli` validation (`fga model validate --type fga.mod`) into automated pre-commit and deployment pipelines.

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 bounded query resolution depths on client check invocations (`client.check({ ... }, { max_depth

Services MUST enforce bounded query resolution depths on client check invocations (`client.check({ ... }, { max_depth: 25 })`) as an in-depth defensive runtime barrier against unexpected cycle traversals.

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 execute raw dynamic authorization model updates directly against production clusters without cryptographic artifact digest hashing and static validation verification.

Components NEVER execute raw dynamic authorization model updates directly against production clusters without cryptographic artifact digest hashing and static validation verification.

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 Modular Model Schema Static Acyclic & Cycle-Detection Standard critical for AI coding assistants?

Mandates compile-time static acyclic graph verification across federated OpenFGA 1.6 modular authorization models prior to runtime registration. Circular relation expansions across distributed module files induce unbounded tuple resolution and severe Denial-of-Service (DoS) during Check and ListObjects queries. Strict automated cycle analysis guarantees provable termination bounds for recursive graph traversals. 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 Cyclic Relation References Inducing Recursive Expansion Denial of Service) 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