This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-background-runner-worker-fence

Capacitor 7 Background Runner Execution Fence and Budget Enforcement

Enforces isolated headless Web Worker execution boundaries and cooperative deadline budgets for Capacitor 7 Background Runner tasks. Prevents native watchdog terminations (SIGKILL/0x8badf00d on iOS, Foreground Service/WorkManager ANRs on Android) by isolating state, capping in-memory buffer allocations, and binding operations to non-negotiable runtime fences.

Prohibited Anti-Pattern: Unbounded Async Execution and State Leakage in Headless Background Runner Tasks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Background Runner Execution Fence and Budget Enforcement - Enforces isolated headless Web Worker execution boundaries and cooperative deadline budgets for Capacitor 7 Background Runner tasks. Prevents native watchdog terminations (SIGKILL/0x8badf00d on iOS, Foreground Service/WorkManager ANRs on Android) by isolating state, capping in-memory buffer allocations, and binding operations to non-negotiable runtime fences.
globs: src/workers/**/*.{js,ts}, src/background/**/*.{js,ts}, capacitor.config.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-background-runner-worker-fence"
---

# Capacitor 7 Background Runner Execution Fence and Budget Enforcement

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Async Execution and State Leakage in Headless Background Runner Tasks

## System Constraints
You are a Principal Mobile Architect enforcing strict execution fences for Capacitor 7 Background Runner tasks. Headless background runtimes operate under hostile OS conditions with strict memory ceilings (<15MB on iOS background tasks) and tight temporal budgets (under 25 seconds). You must enforce cooperative abortion using AbortController deadlines, chunked payload streaming to prevent heap spikes, complete avoidance of DOM/Window references, and persistent state serialization guards.

## Strict Guidelines
- Engineers MUST ALWAYS bound background runner tasks to a non-negotiable execution fence using `AbortSignal.timeout()` capped at 25,000ms maximum to preempt OS termination.
- Engineers MUST NOT reference DOM elements, `window`, `document`, or UI-bound Web APIs inside background runner entry points.
- Code SHOULD process large data synchronization payloads in bounded incremental chunks (maximum batch size of 50 records) to maintain worker heap usage below 10MB.
- Services MUST gracefully catch `AbortError` and persist deterministic checkpoint cursors before the worker context teardown.
- Components NEVER trigger background tasks with raw circular references or un-serializable parameters passed across the native-to-JS runner bridge.

## Bad vs Good Implementations
### Background Sync Execution Fence with Cooperative Abort and Chunking

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad example performs an unbounded fetch and serial async writes without monitoring execution time or memory. On iOS and Android, exceeding background time budgets (typically 25-30s) or triggering a thermal/memory pressure event leads to an abrupt native SIGKILL, corrupting in-flight sync states.
```typescript
import { BackgroundRunner } from '@capacitor/background-runner';

// ANTI-PATTERN: Unbounded fetch loop without timeout fences or heap isolation.
// Exceeding 30s or ~15MB will trigger an iOS 0x8badf00d kill without saving state.
export async function syncUserData(): Promise<void> {
  const response = await fetch('https://api.example.com/sync-all');
  const hugeDataset = await response.json(); // Uncapped memory allocation

  for (const item of hugeDataset) {
    await saveToLocalDatabase(item); // Slow serial execution without abort check
  }
}
```

#### Production Standard (Correct)
> **Standard**: The good example imposes a strict 22-second execution fence using an AbortController, safely below native OS watchdog limits. Data is synchronized in constrained 50-record batches to maintain a minimal memory footprint, and any abort event triggers an orderly exit that preserves cursor state for the next scheduling window.
```typescript
import { BackgroundRunner } from '@capacitor/background-runner';

const BACKGROUND_EXECUTION_TIMEOUT_MS = 22_000; // Leave 3s margin before OS 25s deadline
const BATCH_CHUNK_SIZE = 50;

interface SyncCheckpoint {
  lastProcessedId: string | null;
  completed: boolean;
}

export async function syncUserDataBounded(checkpoint: SyncCheckpoint): Promise<SyncCheckpoint> {
  const abortController = new AbortController();
  const timeoutId = setTimeout(() => abortController.abort(), BACKGROUND_EXECUTION_TIMEOUT_MS);

  try {
    let currentCursor = checkpoint.lastProcessedId;
    let hasMore = true;

    while (hasMore) {
      if (abortController.signal.aborted) {
        throw new DOMException('Background budget exceeded', 'AbortError');
      }

      const pageUrl = `https://api.example.com/sync-chunk?limit=${BATCH_CHUNK_SIZE}${currentCursor ? `&cursor=${currentCursor}` : ''}`;
      const response = await fetch(pageUrl, { signal: abortController.signal });
      const batch: Array<{ id: string; payload: unknown }> = await response.json();

      if (batch.length === 0) {
        hasMore = false;
        break;
      }

      await saveBatchToLocalDatabase(batch);
      currentCursor = batch[batch.length - 1].id;

      if (batch.length < BATCH_CHUNK_SIZE) {
        hasMore = false;
      }
    }

    return { lastProcessedId: currentCursor, completed: !hasMore };
  } catch (error: unknown) {
    if (error instanceof Error && error.name === 'AbortError') {
      // Graceful degraded exit: preserve checkpoint for subsequent run
      return { lastProcessedId: checkpoint.lastProcessedId, completed: false };
    }
    throw error;
  } finally {
    clearTimeout(timeoutId);
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Background Runner Execution Fence and Budget Enforcement

Capacitor 7 Background Runner Execution Fence and Budget Enforcement defines an industrial-grade behavioral standard for mobile engineering. Enforces isolated headless Web Worker execution boundaries and cooperative deadline budgets for Capacitor 7 Background Runner tasks. Prevents native watchdog terminations (SIGKILL/0x8badf00d on iOS, Foreground Service/WorkManager ANRs on Android) by isolating state, capping in-memory buffer allocations, and binding operations to non-negotiable runtime fences. 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: Unbounded Async Execution and State Leakage in Headless Background Runner Tasks 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 DriftUnbounded Async Execution and State Leakage in Headless Background Runner TasksCritical
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 bound background runner tasks to a non-negotiable execution fence using `AbortSignal.timeout()` capped at 25,000ms maximum to preempt OS termination.

Engineers MUST ALWAYS bound background runner tasks to a non-negotiable execution fence using `AbortSignal.timeout()` capped at 25,000ms maximum to preempt OS termination.

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 reference DOM elements, `window`, `document`, or UI-bound Web APIs inside background runner entry points.

Engineers MUST NOT reference DOM elements, `window`, `document`, or UI-bound Web APIs inside background runner entry points.

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 SHOULD process large data synchronization payloads in bounded incremental chunks (maximum batch size of 50 records) to maintain worker heap usage below 10MB.

Code SHOULD process large data synchronization payloads in bounded incremental chunks (maximum batch size of 50 records) to maintain worker heap usage below 10MB.

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 gracefully catch `AbortError` and persist deterministic checkpoint cursors before the worker context teardown.

Services MUST gracefully catch `AbortError` and persist deterministic checkpoint cursors before the worker context teardown.

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 trigger background tasks with raw circular references or un-serializable parameters passed across the native-to-JS runner bridge.

Components NEVER trigger background tasks with raw circular references or un-serializable parameters passed across the native-to-JS runner bridge.

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 Capacitor 7 Background Runner Execution Fence and Budget Enforcement critical for AI coding assistants?

Enforces isolated headless Web Worker execution boundaries and cooperative deadline budgets for Capacitor 7 Background Runner tasks. Prevents native watchdog terminations (SIGKILL/0x8badf00d on iOS, Foreground Service/WorkManager ANRs on Android) by isolating state, capping in-memory buffer allocations, and binding operations to non-negotiable runtime fences. 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 (Unbounded Async Execution and State Leakage in Headless Background Runner Tasks) 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 MOBILE Rules

View all rules →
1 Rule in Stack

Capacitor