This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: android-15-short-service-deadline-quarantine-standard

Android 15 Short-Service Execution Budget & Quarantine Standard

Enforces deterministic state checkpointing and cooperative pre-emptive cancellation within Android 15's mandatory 3-minute (180s) shortService foreground execution ceiling. Guarantees atomic transaction flush and WorkManager fallback handoff prior to OS SIGKILL or ANR triggered on timeout.

Prohibited Anti-Pattern: Unbounded Short-Service Worker Without onTimeout Implementation and Checkpoint Quarantine

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Android 15 Short-Service Execution Budget & Quarantine Standard - Enforces deterministic state checkpointing and cooperative pre-emptive cancellation within Android 15's mandatory 3-minute (180s) shortService foreground execution ceiling. Guarantees atomic transaction flush and WorkManager fallback handoff prior to OS SIGKILL or ANR triggered on timeout.
globs: app/src/**/*.kt, **/AndroidManifest.xml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/android-15-short-service-deadline-quarantine-standard"
---

# Android 15 Short-Service Execution Budget & Quarantine Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Short-Service Worker Without onTimeout Implementation and Checkpoint Quarantine

## System Constraints
You are a Principal Android Architect enforcing the Android 15 Short-Service Background Execution Deadline Quarantine Standard. Under Android 15 (API level 35), foreground services with type 'shortService' are subjected to an uncompromising 3-minute (180-second) hard limit. Failure to stop the service before the deadline invokes onTimeout(), and failing to stop immediately results in OS-level ANR and process termination. You must enforce internal quarantine timeouts, cooperative cancellation token propagation, incremental state checkpointing, and graceful delegation to WorkManager for uncompleted work.

## Strict Guidelines
- Engineers MUST ALWAYS implement Service.onTimeout(startId: Int) whenever android:foregroundServiceType="shortService" is declared.
- Engineers MUST configure an application-level quarantine deadline (e.g., 150 seconds / 2.5 minutes) that triggers task pre-emption before the OS invokes onTimeout().
- Services MUST call stopSelf(startId) immediately upon completion or when the quarantine deadline / onTimeout is reached.
- Engineers MUST checkpoint batch work incrementally using room/atomic disk writes so that interrupted work can be resumed.
- Services MUST enqueue a targeted OneTimeWorkRequest via WorkManager to handle remaining payloads when reaching the quarantine boundary.
- Components NEVER start another short-service while the app remains in the background if the short-service budget is exhausted.

## Bad vs Good Implementations
### Android 15 Short-Service Lifecycle and Quarantine Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The service treats shortService as an unbounded background worker. It does not monitor execution duration, does not override onTimeout(startId), lacks incremental progress persistence, and does not yield unfinished work to WorkManager before Android 15 terminates the process.
```kotlin
class SyncService : Service() {
    private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        startForeground(NOTIFICATION_ID, createNotification())
        // ANTI-PATTERN: Indefinite execution without budget awareness or onTimeout handling.
        // Will trigger an unhandled OS SIGKILL / ANR at exactly 180 seconds on Android 15.
        scope.launch {
            val pendingItems = fetchPendingItemsFromDb()
            for (item in pendingItems) {
                uploadPayload(item)
            }
            stopSelf()
        }
        return START_NOT_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? = null
}
```

#### Production Standard (Correct)
> **Standard**: Implements an internal 150-second quarantine timeout via withTimeoutOrNull, checkpoints state transactionally per batch, overrides onTimeout(startId) to guarantee stopSelf() is called before the OS throws an ANR, and delegates incomplete work to WorkManager.
```kotlin
class SyncService : Service() {
    private val serviceJob = SupervisorJob()
    private val scope = CoroutineScope(Dispatchers.IO + serviceJob)
    private val QUARANTINE_BUDGET_MS = 150_000L // 2.5 mins safe quarantine (hard cap: 180s)

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        startForeground(NOTIFICATION_ID, createNotification(), ServiceInfo.FOREGROUND_SERVICE_TYPE_SHORT_SERVICE)
        scope.launch {
            val completedNormally = withTimeoutOrNull(QUARANTINE_BUDGET_MS) {
                processBatchWithCheckpointing()
            }
            if (completedNormally == null) {
                // Quarantine hit: persist cursor and delegate remaining work
                handoffToWorkManager()
            }
            stopSelf(startId)
        }
        return START_NOT_STICKY
    }

    override fun onTimeout(startId: Int) {
        // Mandatory OS callback on Android 15 (API 35+)
        serviceJob.cancel()
        handoffToWorkManager()
        stopSelf(startId)
    }

    private suspend fun processBatchWithCheckpointing() {
        var cursor = repository.getSyncCursor()
        while (coroutineContext.isActive) {
            val batch = repository.fetchBatch(cursor, limit = 25)
            if (batch.isEmpty()) break
            repository.uploadBatch(batch)
            cursor = batch.last().id
            repository.saveSyncCursor(cursor)
        }
    }

    private fun handoffToWorkManager() {
        val syncWork = OneTimeWorkRequestBuilder<SyncWorker>().build()
        WorkManager.getInstance(applicationContext).enqueueUniqueWork(
            "deferred_sync",
            ExistingWorkPolicy.APPEND_OR_REPLACE,
            syncWork
        )
    }

    override fun onDestroy() {
        serviceJob.cancel()
        super.onDestroy()
    }

    override fun onBind(intent: Intent?): IBinder? = 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: Android 15 Short-Service Execution Budget & Quarantine Standard

Android 15 Short-Service Execution Budget & Quarantine Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic state checkpointing and cooperative pre-emptive cancellation within Android 15's mandatory 3-minute (180s) shortService foreground execution ceiling. Guarantees atomic transaction flush and WorkManager fallback handoff prior to OS SIGKILL or ANR triggered on timeout. 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 Short-Service Worker Without onTimeout Implementation and Checkpoint Quarantine 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 Short-Service Worker Without onTimeout Implementation and Checkpoint QuarantineCritical
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 implement Service.onTimeout(startId

Engineers MUST ALWAYS implement Service.onTimeout(startId: Int) whenever android:foregroundServiceType="shortService" is declared.

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 configure an application-level quarantine deadline (e.g., 150 seconds / 2.5 minutes) that triggers task pre-emption before the OS invokes onTimeout().

Engineers MUST configure an application-level quarantine deadline (e.g., 150 seconds / 2.5 minutes) that triggers task pre-emption before the OS invokes onTimeout().

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

Services MUST call stopSelf(startId) immediately upon completion or when the quarantine deadline / onTimeout is reached.

Services MUST call stopSelf(startId) immediately upon completion or when the quarantine deadline / onTimeout is reached.

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

Engineers MUST checkpoint batch work incrementally using room/atomic disk writes so that interrupted work can be resumed.

Engineers MUST checkpoint batch work incrementally using room/atomic disk writes so that interrupted work can be resumed.

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

Services MUST enqueue a targeted OneTimeWorkRequest via WorkManager to handle remaining payloads when reaching the quarantine boundary.

Services MUST enqueue a targeted OneTimeWorkRequest via WorkManager to handle remaining payloads when reaching the quarantine boundary.

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

Components NEVER start another short-service while the app remains in the background if the short-service budget is exhausted.

Components NEVER start another short-service while the app remains in the background if the short-service budget is exhausted.

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 Android 15 Short-Service Execution Budget & Quarantine Standard critical for AI coding assistants?

Enforces deterministic state checkpointing and cooperative pre-emptive cancellation within Android 15's mandatory 3-minute (180s) shortService foreground execution ceiling. Guarantees atomic transaction flush and WorkManager fallback handoff prior to OS SIGKILL or ANR triggered on timeout. 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 Short-Service Worker Without onTimeout Implementation and Checkpoint Quarantine) 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

Android