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

Capacitor 7 Background Task Execution State Reconciliation & SQLite Ledger Atomicity

Enforces deterministic state reconciliation and atomic SQLite ledger transactions during Capacitor 7 background execution cycles. Mandates a defensive 25-second abort boundary to prevent OS-level SIGKILLs (enforcing iOS/Android 30-second execution caps) and guarantees zero-dangling write-ahead logs (WAL).

Prohibited Anti-Pattern: Unbounded async reconciliation inside background workers leading to mid-transaction OS SIGKILL and SQLite WAL ledger corruption.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Background Task Execution State Reconciliation & SQLite Ledger Atomicity - Enforces deterministic state reconciliation and atomic SQLite ledger transactions during Capacitor 7 background execution cycles. Mandates a defensive 25-second abort boundary to prevent OS-level SIGKILLs (enforcing iOS/Android 30-second execution caps) and guarantees zero-dangling write-ahead logs (WAL).
globs: src/**/*.{ts,tsx}, src/services/**/*.{ts,js}, src/workers/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-background-task-sqlite-reconciliation"
---

# Capacitor 7 Background Task Execution State Reconciliation & SQLite Ledger Atomicity

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded async reconciliation inside background workers leading to mid-transaction OS SIGKILL and SQLite WAL ledger corruption.

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 Background Task invariants. Background execution on iOS (UIApplication beginBackgroundTaskWithName) and Android (WorkManager/JobScheduler) terminates abruptly after 30 seconds with SIGKILL. You must mandate atomic SQLite transactions, bounded time budgets using AbortController with a 25-second ceiling, defensive WAL commits/rollbacks, and guaranteed task termination signaling via BackgroundTask.finish().

## Strict Guidelines
- Engineers MUST ALWAYS bound background execution routines to a strict 25,000ms deadline using AbortController to reserve a 5,000ms emergency cleanup window before the OS 30-second budget expires.
- Engineers MUST wrap all local ledger mutations in an explicit SQLite transaction ('BEGIN IMMEDIATE TRANSACTION' ... 'COMMIT') and execute 'ROLLBACK' immediately upon any aborted or unhandled operation.
- Code MUST ALWAYS call BackgroundTask.finish({ taskId }) within a finally block to avoid leaking background execution assertions and incurring OS energy penalties.
- Services MUST NOT execute unbounded iterative network or ledger loops during background tasks; mutations must be chunked into deterministic, bounded batches.
- Engineers MUST verify the database connection state and SQLite WAL lock status before initiating background reconciliation routines.

## Bad vs Good Implementations
### Capacitor 7 Background State Ledger Reconciliation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Lacks an AbortController deadline; if network requests stall, iOS/Android enforces a hard SIGKILL at the 30-second mark. Furthermore, mutating records sequentially without a transaction causes partial writes and risks unrecoverable WAL locks.
```typescript
import { BackgroundTask } from '@capacitor/background-task';
import { SQLiteDBConnection } from '@capacitor-community/sqlite';

export async function reconcileLedger(db: SQLiteDBConnection, pendingPayloads: any[]) {
  // Anti-pattern: No timeout budget, unbounded iteration, non-atomic individual updates
  const taskId = await BackgroundTask.beforeExit(async () => {
    for (const item of pendingPayloads) {
      const response = await fetch('https://api.example.com/sync', {
        method: 'POST',
        body: JSON.stringify(item),
      });
      const result = await response.json();
      // Dangerous: If 30s OS budget hits mid-loop, SQLite remains un-checkpointed or partially written
      await db.run('UPDATE ledger SET status = ? WHERE id = ?', [result.status, item.id]);
    }
    // If fetch hangs or takes >30s, this is never reached; app is killed via SIGKILL
    BackgroundTask.finish({ taskId });
  });
}
```

#### Production Standard (Correct)
> **Standard**: Implements an AbortController with a 25-second limit, leaving 5 seconds for rollback and cleanup before the 30-second OS limit. Explicitly wraps mutations in an atomic transaction ('BEGIN IMMEDIATE TRANSACTION'/'COMMIT') with a fail-safe 'ROLLBACK', and always invokes BackgroundTask.finish in a finally block.
```typescript
import { BackgroundTask } from '@capacitor/background-task';
import { SQLiteDBConnection } from '@capacitor-community/sqlite';

const BACKGROUND_BUDGET_MS = 25_000;

export async function reconcileLedger(
  db: SQLiteDBConnection,
  pendingPayloads: Array<{ id: string; delta: number }>
): Promise<void> {
  const taskId = await BackgroundTask.beforeExit(async () => {
    const abortController = new AbortController();
    const timeoutId = setTimeout(() => abortController.abort(), BACKGROUND_BUDGET_MS);
    let inTransaction = false;

    try {
      await db.execute('BEGIN IMMEDIATE TRANSACTION;');
      inTransaction = true;

      for (const item of pendingPayloads) {
        if (abortController.signal.aborted) {
          throw new Error('Background execution budget exhausted. Aborting reconciliation.');
        }

        const response = await fetch('https://api.example.com/sync', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(item),
          signal: abortController.signal,
        });

        if (!response.ok) {
          throw new Error(`Sync failed with HTTP status ${response.status}`);
        }

        const result = await response.json();
        await db.run(
          'UPDATE ledger SET status = ?, synced_at = ? WHERE id = ?;',
          [result.status, Date.now(), item.id]
        );
      }

      await db.execute('COMMIT;');
      inTransaction = false;
    } catch (err: unknown) {
      if (inTransaction) {
        await db.execute('ROLLBACK;').catch((rollbackErr) => {
          console.error('Fatal: SQLite rollback failed during reconciliation cleanup', rollbackErr);
        });
      }
      console.warn('Reconciliation aborted or encountered an error:', err);
    } finally {
      clearTimeout(timeoutId);
      BackgroundTask.finish({ taskId });
    }
  });
}
```

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: Capacitor 7 Background Task Execution State Reconciliation & SQLite Ledger Atomicity

Capacitor 7 Background Task Execution State Reconciliation & SQLite Ledger Atomicity defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic state reconciliation and atomic SQLite ledger transactions during Capacitor 7 background execution cycles. Mandates a defensive 25-second abort boundary to prevent OS-level SIGKILLs (enforcing iOS/Android 30-second execution caps) and guarantees zero-dangling write-ahead logs (WAL). 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 reconciliation inside background workers leading to mid-transaction OS SIGKILL and SQLite WAL ledger corruption. 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 reconciliation inside background workers leading to mid-transaction OS SIGKILL and SQLite WAL ledger corruption.Critical
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 execution routines to a strict 25,000ms deadline using AbortController to reserve a 5,000ms emergency cleanup window before the OS 30-second budget expires.

Engineers MUST ALWAYS bound background execution routines to a strict 25,000ms deadline using AbortController to reserve a 5,000ms emergency cleanup window before the OS 30-second budget expires.

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 wrap all local ledger mutations in an explicit SQLite transaction ('BEGIN IMMEDIATE TRANSACTION' ... 'COMMIT') and execute 'ROLLBACK' immediately upon any aborted or unhandled operation.

Engineers MUST wrap all local ledger mutations in an explicit SQLite transaction ('BEGIN IMMEDIATE TRANSACTION' ... 'COMMIT') and execute 'ROLLBACK' immediately upon any aborted or unhandled operation.

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 ALWAYS call BackgroundTask.finish({ taskId }) within a finally block to avoid leaking background execution assertions and incurring OS energy penalties.

Code MUST ALWAYS call BackgroundTask.finish({ taskId }) within a finally block to avoid leaking background execution assertions and incurring OS energy penalties.

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 NOT execute unbounded iterative network or ledger loops during background tasks

Services MUST NOT execute unbounded iterative network or ledger loops during background tasks; mutations must be chunked into deterministic, bounded batches.

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

Engineers MUST verify the database connection state and SQLite WAL lock status before initiating background reconciliation routines.

Engineers MUST verify the database connection state and SQLite WAL lock status before initiating background reconciliation routines.

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 Task Execution State Reconciliation & SQLite Ledger Atomicity critical for AI coding assistants?

Enforces deterministic state reconciliation and atomic SQLite ledger transactions during Capacitor 7 background execution cycles. Mandates a defensive 25-second abort boundary to prevent OS-level SIGKILLs (enforcing iOS/Android 30-second execution caps) and guarantees zero-dangling write-ahead logs (WAL). 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 reconciliation inside background workers leading to mid-transaction OS SIGKILL and SQLite WAL ledger corruption.) 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