This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-sqlite-wal-sigterm-barrier-guardrail

Bun 1.2 Embedded SQLite WAL Checkpoint SIGTERM Barrier

Enforces deterministic PRAGMA wal_checkpoint(TRUNCATE) execution and explicit shared-memory (.shm) unmapping prior to process termination in containerized Bun runtimes. Failure to complete checkpoint barriers during SIGTERM/SIGINT teardowns leaves SQLite database files in an unrecovered recovery-journal state, causing lock collisions or index corruption upon rapid container restarts. This guardrail mandates an idempotent teardown lifecycle with strict synchronous execution timeouts.

Prohibited Anti-Pattern: Uncoordinated process termination leaving uncheckpointed SQLite WAL rings and unclosed file descriptors

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Embedded SQLite WAL Checkpoint SIGTERM Barrier - Enforces deterministic PRAGMA wal_checkpoint(TRUNCATE) execution and explicit shared-memory (.shm) unmapping prior to process termination in containerized Bun runtimes. Failure to complete checkpoint barriers during SIGTERM/SIGINT teardowns leaves SQLite database files in an unrecovered recovery-journal state, causing lock collisions or index corruption upon rapid container restarts. This guardrail mandates an idempotent teardown lifecycle with strict synchronous execution timeouts.
globs: src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-sqlite-wal-sigterm-barrier-guardrail"
---

# Bun 1.2 Embedded SQLite WAL Checkpoint SIGTERM Barrier

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Uncoordinated process termination leaving uncheckpointed SQLite WAL rings and unclosed file descriptors

## System Constraints
You are a Principal Engineer enforcing Bun 1.2 Embedded SQLite WAL Checkpoint SIGTERM Failsafe. Mandate synchronous write-ahead log (WAL) flushing and safe SQLite connection destruction upon receiving OS lifecycle termination signals (SIGTERM, SIGINT). Ensure no asynchronous I/O leaves SQLite shared-memory mappings orphaned during container shutdowns.

## Strict Guidelines
- Engineers MUST ALWAYS register atomic SIGTERM and SIGINT listeners that execute 'PRAGMA wal_checkpoint(TRUNCATE);' before closing the SQLite database handle.
- Engineers MUST NOT rely on implicit process exit or asynchronous Garbage Collection to release SQLite shared-memory (.shm) and write-ahead log (.wal) file descriptors.
- Code SHOULD enforce an idempotent termination coordinator to ensure the shutdown handler runs exactly once even if multiple signals are received.
- Services MUST explicitly call 'db.close()' only after all active read/write transactions have settled or aborted.
- Components NEVER execute raw 'process.exit()' inside request or lifecycle pathways without invoking the registered graceful drain and checkpoint pipeline.

## Bad vs Good Implementations
### Abrupt Process Exit vs Deterministic WAL Flush and Handle Teardown

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Exiting immediately on SIGTERM without checkpointing leaves uncommitted pages in .wal and an active .shm mapping. In rapid container restarts, the new container may encounter lock contention or fail WAL index recovery if volume sync was mid-flight.
```typescript
import { Database } from "bun:sqlite";

const db = new Database("/data/app.db");
db.exec("PRAGMA journal_mode = WAL;");

// ANTI-PATTERN: Container orchestrator sends SIGTERM, runtime exits without checkpointing WAL.
process.on("SIGTERM", () => {
  console.log("Received SIGTERM, exiting...");
  process.exit(0);
});
```

#### Production Standard (Correct)
> **Standard**: Guarantees idempotent teardown, synchronously flushes WAL frames to the main database file with TRUNCATE mode, and invokes db.close() to detach shared-memory regions before container eviction.
```typescript
import { Database } from "bun:sqlite";

const db = new Database("/data/app.db");
db.exec("PRAGMA journal_mode = WAL;");
db.exec("PRAGMA synchronous = NORMAL;");

let isShuttingDown = false;

function handleTermination(signal: string): void {
  if (isShuttingDown) return;
  isShuttingDown = true;

  try {
    // Flush WAL pages into base DB and truncate WAL file
    db.exec("PRAGMA wal_checkpoint(TRUNCATE);");
    db.close(false); // Cleanly closes handle and unmaps .shm
  } catch (err) {
    console.error(`Failed during ${signal} SQLite WAL checkpoint barrier:`, err);
    process.exit(1);
  }
  process.exit(0);
}

process.once("SIGTERM", () => handleTermination("SIGTERM"));
process.once("SIGINT", () => handleTermination("SIGINT"));
```

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: Bun 1.2 Embedded SQLite WAL Checkpoint SIGTERM Barrier

Bun 1.2 Embedded SQLite WAL Checkpoint SIGTERM Barrier defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic PRAGMA wal_checkpoint(TRUNCATE) execution and explicit shared-memory (.shm) unmapping prior to process termination in containerized Bun runtimes. Failure to complete checkpoint barriers during SIGTERM/SIGINT teardowns leaves SQLite database files in an unrecovered recovery-journal state, causing lock collisions or index corruption upon rapid container restarts. This guardrail mandates an idempotent teardown lifecycle with strict synchronous execution timeouts. 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: Uncoordinated process termination leaving uncheckpointed SQLite WAL rings and unclosed file descriptors 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 DriftUncoordinated process termination leaving uncheckpointed SQLite WAL rings and unclosed file descriptorsCritical
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 register atomic SIGTERM and SIGINT listeners that execute 'PRAGMA wal_checkpoint(TRUNCATE)

Engineers MUST ALWAYS register atomic SIGTERM and SIGINT listeners that execute 'PRAGMA wal_checkpoint(TRUNCATE);' before closing the SQLite database handle.

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 rely on implicit process exit or asynchronous Garbage Collection to release SQLite shared-memory (.shm) and write-ahead log (.wal) file descriptors.

Engineers MUST NOT rely on implicit process exit or asynchronous Garbage Collection to release SQLite shared-memory (.shm) and write-ahead log (.wal) file descriptors.

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 enforce an idempotent termination coordinator to ensure the shutdown handler runs exactly once even if multiple signals are received.

Code SHOULD enforce an idempotent termination coordinator to ensure the shutdown handler runs exactly once even if multiple signals are received.

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 explicitly call 'db.close()' only after all active read/write transactions have settled or aborted.

Services MUST explicitly call 'db.close()' only after all active read/write transactions have settled or aborted.

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 'process.exit()' inside request or lifecycle pathways without invoking the registered graceful drain and checkpoint pipeline.

Components NEVER execute raw 'process.exit()' inside request or lifecycle pathways without invoking the registered graceful drain and checkpoint pipeline.

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 Bun 1.2 Embedded SQLite WAL Checkpoint SIGTERM Barrier critical for AI coding assistants?

Enforces deterministic PRAGMA wal_checkpoint(TRUNCATE) execution and explicit shared-memory (.shm) unmapping prior to process termination in containerized Bun runtimes. Failure to complete checkpoint barriers during SIGTERM/SIGINT teardowns leaves SQLite database files in an unrecovered recovery-journal state, causing lock collisions or index corruption upon rapid container restarts. This guardrail mandates an idempotent teardown lifecycle with strict synchronous execution timeouts. 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 (Uncoordinated process termination leaving uncheckpointed SQLite WAL rings and unclosed file descriptors) 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

Bun