This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: svelte5-runes-reactive-graph-cycle-push-pull-leak-guardrail

Svelte 5 Runes Reactive Graph Cycle Prevention and Push-Pull Leak Guardrail

Enforces strict structural constraints on Svelte 5 rune topologies ($state, $derived, $effect) to eliminate infinite evaluation loops and subscription leaks. Protects against memory bloat and microtask exhaustion under high-throughput telemetry updates by mandating untracked reads, bounded buffers, and decoupled frame rendering.

Prohibited Anti-Pattern: Dynamic Graph Dependency Churn and Cyclic Invalidation Under High-Frequency Stream Mutation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Svelte 5 Runes Reactive Graph Cycle Prevention and Push-Pull Leak Guardrail - Enforces strict structural constraints on Svelte 5 rune topologies ($state, $derived, $effect) to eliminate infinite evaluation loops and subscription leaks. Protects against memory bloat and microtask exhaustion under high-throughput telemetry updates by mandating untracked reads, bounded buffers, and decoupled frame rendering.
globs: src/**/*.{svelte,svelte.ts,svelte.js,ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/svelte5-runes-reactive-graph-cycle-push-pull-leak-guardrail"
---

# Svelte 5 Runes Reactive Graph Cycle Prevention and Push-Pull Leak Guardrail

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Dynamic Graph Dependency Churn and Cyclic Invalidation Under High-Frequency Stream Mutation

## System Constraints
You are a Principal Software Architect enforcing production-grade Svelte 5 reactive graph integrity. You must guarantee that high-frequency state updates (telemetry, WebSockets, real-time charts) never cause push-pull invalidation cascades, cyclic dependencies, or retained reference leaks across $derived and $effect rune graphs.

## Strict Guidelines
- Engineers MUST ALWAYS isolate incidental state reads using `untrack(() => ...)` within `$effect` and `$derived.by` to prevent accidental dependency registration.
- Engineers MUST NOT mutate any `$state` signal directly or transitively inside a `$derived` or `$derived.by` computation; derivations MUST remain pure projection functions.
- Engineers MUST NOT mutate state signals inside an `$effect` that read that same state synchronously without an explicit termination condition or `untrack()` boundary, preventing microtask cycles (`ERR_SVELTE_TOO_MANY_UPDATES`).
- Code MUST bound high-frequency telemetry ingestion using fixed-capacity circular ring buffers or batching arrays, avoiding unbounded append mutations on `$state` collections.
- Components NEVER instantiate nested `$effect.root()` or dynamic `$derived` signals inside loops or continuous event callbacks without retaining and executing explicit cleanup disposers.
- Services MUST decouple high-throughput stream ingestion from visual rune reactivity by aggregating raw telemetry off-graph and flushing snapshots to `$state` at display refresh intervals (e.g., via `requestAnimationFrame`).

## Bad vs Good Implementations
### High-Frequency Telemetry Ingestion and Derived Metric Topology

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Mutating `this.totalSum` inside `$derived.by` introduces an illegal side effect in Svelte 5's push-pull execution model, triggering cascading invalidation cycles. Additionally, continuously mutating an unbounded array inside `$state` without ring-buffering creates retained memory leaks and escalates dirty-flag checking cost.
```typescript
// telemetry-store.svelte.ts
import { untrack } from 'svelte';

export class TelemetryMonitor {
  rawPackets = $state<number[]>([]);
  totalSum = $state(0);
  
  // ANTI-PATTERN: Mutating state inside derived, creating downstream evaluation cycle
  movingAverage = $derived.by(() => {
    const sum = this.rawPackets.reduce((acc, curr) => acc + curr, 0);
    // Side effect inside derived: Mutates state, poisoning push-pull scheduler
    this.totalSum = sum;
    return this.rawPackets.length > 0 ? sum / this.rawPackets.length : 0;
  });

  constructor(socket: WebSocket) {
    // ANTI-PATTERN: Unbounded reactive array growth triggers exponential push-pull dirty checks
    socket.onmessage = (event) => {
      const payload = JSON.parse(event.data);
      this.rawPackets.push(payload.metric); // Continuously expands graph memory footprint
    };
  }
}
```

#### Production Standard (Correct)
> **Standard**: The revised implementation buffers telemetry updates off-graph and synchronizes them to `$state` once per animation frame. The `$derived.by` computation remains strictly pure with zero external mutations, preventing graph evaluation cycles, bounding heap memory, and protecting scheduler microtasks.
```typescript
// telemetry-store.svelte.ts
import { untrack } from 'svelte';

export class TelemetryMonitor {
  private readonly maxCapacity: number;
  // Fixed-size window to guarantee memory boundedness
  private buffer: number[] = [];
  private animationFrameId: number | null = null;

  // Public rune state exposed as read-only snapshot
  samples = $state<readonly number[]>([]);

  // PURE projection: strictly pull-driven with zero state mutations
  movingAverage = $derived.by(() => {
    const current = this.samples;
    if (current.length === 0) return 0;
    const sum = current.reduce((acc, val) => acc + val, 0);
    return sum / current.length;
  });

  constructor(socket: WebSocket, capacity = 100) {
    this.maxCapacity = capacity;

    // Ingestion off-graph: avoid dirtying the reactive graph at network wire speed
    socket.onmessage = (event) => {
      const payload = JSON.parse(event.data);
      this.buffer.push(payload.metric);
      if (this.buffer.length > this.maxCapacity) {
        this.buffer.shift();
      }
      this.scheduleFlush();
    };
  }

  private scheduleFlush(): void {
    if (this.animationFrameId !== null) return;

    // Decouple ingestion from reactive graph updates using display frame throttling
    this.animationFrameId = requestAnimationFrame(() => {
      this.animationFrameId = null;
      // Update rune state in a single bounded atomic transaction
      this.samples = [...this.buffer];
    });
  }

  destroy(): void {
    if (this.animationFrameId !== null) {
      cancelAnimationFrame(this.animationFrameId);
      this.animationFrameId = null;
    }
  }
}
```

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: Svelte 5 Runes Reactive Graph Cycle Prevention and Push-Pull Leak Guardrail

Svelte 5 Runes Reactive Graph Cycle Prevention and Push-Pull Leak Guardrail defines an industrial-grade behavioral standard for frontend engineering. Enforces strict structural constraints on Svelte 5 rune topologies ($state, $derived, $effect) to eliminate infinite evaluation loops and subscription leaks. Protects against memory bloat and microtask exhaustion under high-throughput telemetry updates by mandating untracked reads, bounded buffers, and decoupled frame rendering. 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: Dynamic Graph Dependency Churn and Cyclic Invalidation Under High-Frequency Stream Mutation 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 DriftDynamic Graph Dependency Churn and Cyclic Invalidation Under High-Frequency Stream MutationCritical
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 isolate incidental state reads using `untrack(() => ...)` within `$effect` and `$derived.by` to prevent accidental dependency registration.

Engineers MUST ALWAYS isolate incidental state reads using `untrack(() => ...)` within `$effect` and `$derived.by` to prevent accidental dependency registration.

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 mutate any `$state` signal directly or transitively inside a `$derived` or `$derived.by` computation

Engineers MUST NOT mutate any `$state` signal directly or transitively inside a `$derived` or `$derived.by` computation; derivations MUST remain pure projection functions.

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 mutate state signals inside an `$effect` that read that same state synchronously without an explicit termination condition or `untrack()` boundary, preventing microtask cycles (`ERR_SVELTE_TOO_MANY_UPDATES`).

Engineers MUST NOT mutate state signals inside an `$effect` that read that same state synchronously without an explicit termination condition or `untrack()` boundary, preventing microtask cycles (`ERR_SVELTE_TOO_MANY_UPDATES`).

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 MUST bound high-frequency telemetry ingestion using fixed-capacity circular ring buffers or batching arrays, avoiding unbounded append mutations on `$state` collections.

Code MUST bound high-frequency telemetry ingestion using fixed-capacity circular ring buffers or batching arrays, avoiding unbounded append mutations on `$state` collections.

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 instantiate nested `$effect.root()` or dynamic `$derived` signals inside loops or continuous event callbacks without retaining and executing explicit cleanup disposers.

Components NEVER instantiate nested `$effect.root()` or dynamic `$derived` signals inside loops or continuous event callbacks without retaining and executing explicit cleanup disposers.

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

Services MUST decouple high-throughput stream ingestion from visual rune reactivity by aggregating raw telemetry off-graph and flushing snapshots to `$state` at display refresh intervals (e.g., via `requestAnimationFrame`).

Services MUST decouple high-throughput stream ingestion from visual rune reactivity by aggregating raw telemetry off-graph and flushing snapshots to `$state` at display refresh intervals (e.g., via `requestAnimationFrame`).

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 Svelte 5 Runes Reactive Graph Cycle Prevention and Push-Pull Leak Guardrail critical for AI coding assistants?

Enforces strict structural constraints on Svelte 5 rune topologies ($state, $derived, $effect) to eliminate infinite evaluation loops and subscription leaks. Protects against memory bloat and microtask exhaustion under high-throughput telemetry updates by mandating untracked reads, bounded buffers, and decoupled frame rendering. 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 (Dynamic Graph Dependency Churn and Cyclic Invalidation Under High-Frequency Stream Mutation) 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.

Related FRONTEND Rules

View all rules →
frontend
119

SolidStart 1.0 Server Functions & Async Boundaries Production Standard

SolidStart 1.0 relies on the Vinxi bundler to split `server$` closures into independent HTTP POST RPC endpoints. Direct lexical closure over client signals within `server$` scopes or failure to demarcate async boundaries with `<Suspense>` causes silent serialization failures, client-bundle secret leaks, and SSR hydration mismatches. Enforcing strict parameter passing, runtime input validation, and Solid async primitives maintains security and fine-grained reactivity across network boundaries.

frontend
119

Astro 5 Actions & Content Layer Production Standard

Enforces strict type safety and architectural correctness for Astro 5 Server Actions and the zero-waterfall Content Layer API. Prevents runtime contract mismatches, hydration mismatches, and unhandled mutation exceptions across dynamic and prerendered boundaries. Failure to follow these patterns leads to silent data fetching waterfalls, build-time cache corruptions, and unhandled server action exceptions.

frontend
51

Nuxt 4 Nitro Server Engine & Shared Directory Production Standard

Nuxt 4 enforces strict boundary segregation between client UI in the app/ directory, backend endpoints in server/, and universal contracts in shared/. Violating cross-boundary isolation or maintaining module-scoped state in Nitro server handlers causes catastrophic cross-request data corruption and hydration mismatches under concurrent production traffic. Architects must enforce request-isolated H3 event contexts, universal serialization schemas, and strict path-alias boundaries.

1 Rule in Stack

Svelte