AGENT SKILL

shared-resource-per-owner-scoping

One screen's teardown kills a resource another screen is still using, or one path's failure permanently disables a feature for every other caller — a shared singleton (speech transcriber, camera session, model session, circuit breaker, token budget) is stopped/tripped by whoever finishes first, because the stop path checks a bare Bool like isListening instead of "am I still the owner". Symptoms: voice input returns nothing after the second use, a suggestion feature silently dies for the rest of the launch, a capture session tears down mid-handoff, cancelling one request cancels an unrelated one. Use whenever a stateful service is shared across screens or requests and any caller can stop, cancel, reset or trip it — before writing the stop/teardown path, not after the bug.

License 许可
MIT
最近更新
2026-11-07
Stars
★ 1
Forks
1

01 前言 Front Matter

name
shared-resource-per-owner-scoping
description
One screen's teardown kills a resource another screen is still using, or one path's failure permanently disables a feature for every other caller — a shared singleton (speech transcriber, camera session, model session, circuit breaker, token budget) is stopped/tripped by whoever finishes first, because the stop path checks a bare Bool like isListening instead of "am I still the owner". Symptoms: voice input returns nothing after the second use, a suggestion feature silently dies for the rest of the launch, a capture session tears down mid-handoff, cancelling one request cancels an unrelated one. Use whenever a stateful service is shared across screens or requests and any caller can stop, cancel, reset or trip it — before writing the stop/teardown path, not after the bug.

03 SKILL.md 正文

Shared Resources Need Per-Owner Scoping, Not a Boolean

Symptom

A stateful service is created once and shared: a speech transcriber, an AVCaptureSession, an on-device model session, a circuit breaker, a rate limiter. Two screens (or two requests) use it in overlapping windows. Then:

  • Screen B's stop() tears down the session Screen A is still using — A hangs or returns nothing, with no error anywhere.
  • One path trips a shared circuit breaker after a failure, and an unrelated read-only consumer of the same breaker is dead for the rest of the launch.
  • A cancel intended for request 1 lands on request 2, because by the time the cancel ran, the shared handle had been rebound.

The tell is that the first use always works and the failure needs two overlapping users, so it survives every single-screen test.

Root cause

The stop path asks "is it running?" when it must ask "am I still the one who started it?"

// WRONG — any caller can stop anyone's session
func stop() {
    guard isListening else { return }
    engine.stop()
    isListening = false
}

isListening is true regardless of who made it true. A bare Bool cannot express ownership, so every teardown is a global teardown.

The fix: record identity at start, compare it at every exit

private var currentOwner: ObjectIdentifier?   // or a monotonic generation token

func start(owner: AnyObject) {
    currentOwner = ObjectIdentifier(owner)
    engine.start()
}

func stop(owner: AnyObject) {
    // Not "is it running" — "is it still MINE"
    guard currentOwner == ObjectIdentifier(owner) else { return }
    engine.stop()
    currentOwner = nil
}

A monotonic generation token works equally well when only one owner is ever live, and survives object reuse:

private var generation = 0

func start() -> Int { generation += 1; engine.start(); return generation }
func stop(token: Int) { guard token == generation else { return }; engine.stop() }

Pick the shape by how many owners can be live at the same time — the three are not interchangeable:

Shape Use when Why
Monotonic generation token Exactly one owner is live at a time A stale token compares unequal, so a late stop no-ops
Per-owner registry (Set<ObjectIdentifier>) Several owners can be live concurrently Each stop releases only its own entry; the resource stays up while anyone holds it
A reference count Never A count records how many, never which, so any stop satisfies any claim — a stale stop from an owner that already went away drops the count to zero and releases the gate while the outgoing session is still draining

The count row is the trap, because a count looks like a generation token and compiles the same. "Is anyone using it?" is not the question; "is this caller the one I owe a teardown to?" is.

The three rules that make it actually hold

1. "At start" means before the first suspension point. This is the rule people get wrong after fixing everything else. If ownership is recorded after an await, there is a window where the resource is live and unowned:

// WRONG — the authorize() await is an ownership hole. A stop() arriving
// during it finds currentOwner == nil and no-ops, so the session it was
// meant to stop keeps running.
func start(owner: AnyObject) async throws {
    try await requestAuthorization()          // <-- suspension point
    currentOwner = ObjectIdentifier(owner)    // too late
    engine.start()
}

// RIGHT — claim first, release on failure.
func start(owner: AnyObject) async throws {
    currentOwner = ObjectIdentifier(owner)
    do { try await requestAuthorization() }
    catch { currentOwner = nil; throw error }
    engine.start()
}

2. Every teardown path compares identity — not just the obvious one. stop(), deinit, onDisappear, a backgrounding notification, a timeout handler, and an error path are all teardowns. One unguarded path reintroduces the whole bug.

3. Blast radius runs in the availability direction too. A shared circuit breaker is the same defect wearing different clothes: one path's failures trip it, and a read-only consumer that never failed inherits the trip. If the breaker is shared, its state must be keyed per consumer — or the consumers must not share it. A one-way trip with no reset is strictly worse: the feature is dead until the app relaunches, and nothing logs why.

Fixing the async-callback version reopens the race

A common "fix" moves ownership assignment into a completion callback so it reflects the real session. That reintroduces the hole from rule 1 — the callback runs after suspension. Claim synchronously; correct or release in the callback.

How to test it

The single-owner test always passes and proves nothing. The tests that catch it:

  • Interleaved owners: A starts, B starts, A stops → assert B's session is still live. This is the one that fails before the fix.
  • Stale stop: A starts, A stops, B starts, A's late timeout fires → assert B survives.
  • Suspension-window stop: stop arrives while start is awaiting authorization → assert the eventual session does not leak.
  • For a breaker: consumer X fails enough to trip → assert consumer Y still works.

Make the decision a pure function (shouldStop(current:requesting:) -> Bool) and these become plain unit tests with no hardware.

Checklist

  • [ ] Ownership is an identity (ObjectIdentifier / generation token), never a Bool
  • [ ] Recorded before the first await in the start path, released on failure
  • [ ] Every teardown path — including deinit, backgrounding and timeouts — compares it
  • [ ] Shared breakers/limiters are keyed per consumer, or not shared
  • [ ] A tripped breaker has a reset path and logs the trip
  • [ ] An interleaved-owner test exists and fails against the pre-fix code

Evidence

Cubby iOS, four reports of one defect across two sessions.

  • Session 0066 (2026-07-25), BUG-044 — a shared transcriber stopped by hosts that never started it; a coarse phase guard still allowed a kill during .preparing (rule 1).
  • Session 0066, BUG-045 — a stop counter could not attribute a stop; replaced by a live-session registry (the count row of the table).
  • Session 0068 (2026-07-26), findings #4/#5/#2 — rule 2 (a guard missing from stop(); an unkeyed camera-handoff Bool) and rule 3 (one breaker shared by two consumers). Ownership as a pure predicate made each a plain unit test.

Related skills

  • avfoundation-capture-delivery-watchdog — the sibling failures on the same hardware. Three root causes, one symptom: the delegate never came (its Fix 1), two sessions overlapped during a swap (its Fix 2), or someone else's stop() killed a session you own (here). Route to all three before concluding a capture bug is fixed.
  • shared-action-overload-callsite-audit — the same blast-radius error in the behavioural direction: widening one shared action to satisfy one caller silently changes every other call site that reuses it.
  • nonsendable-hardware-handle-inline-io — a sibling constraint on the same shared handles: the handle itself cannot cross an isolation boundary, so the ownership check has to live where the handle does.
  • field-log-duration-clustering-race-diagnosis — how to confirm this class from the field when the interleaving only happens on a real device.

04 同仓库更多 Skills

abhijitbansal
abhijitbansal/claude-skills

second-wind

Orchestrate long unattended Claude Code runs across multiple repos with the wind CLI. Use when the user wants to run Claude Code overnight, resume sessions after the 5-hour usage limit, run Claude in many repos at once via tmux, or says "set up second wind", "wind up", "overnight run", "resume after limit", "usage limit orchestrator".

★ 1
abhijitbansal
abhijitbansal/claude-skills

structured-output-adaptive-thinking-token-bloat

A Claude API call using output_config.format (json_schema structured outputs) with thinking:{type:"adaptive"} burns most of its output budget on thinking (observed ~21k of ~24k tokens) without improving JSON quality, making the run up to ~5x more expensive than the same call with thinking omitted — use when calling the Messages API with a json_schema output format for extraction, ranking, classification, or summarization tasks, or when a schema-constrained call's usage.output_tokens is far larger than the returned JSON.

★ 1
abhijitbansal
abhijitbansal/claude-skills

review

Apply a code-review lens to a diff, branch, or file — find correctness bugs, security issues, and quality problems, ranked by severity, with a concrete fix for each. Use when the user says "review this", "review my diff", "check this PR", "look this over before I commit", or "is this safe". Skip when the user wants the code written, not reviewed.

★ 1
abhijitbansal
abhijitbansal/claude-skills

refresh

Rebuild the prompt-craft command registry and usage profile, and print a summary of installed commands and your personalized recommendations. Use when you install or update plugins and want the advisor to pick them up immediately, or say "refresh prompt-craft", "rebuild the command registry".

★ 1
abhijitbansal
abhijitbansal/claude-skills

refactor

Apply a refactoring lens — restructure code without changing behavior, guarded by tests that pass before and after. Use when the user says "refactor", "clean this up", "extract this", "simplify this", "reduce duplication", or "make this readable" on existing working code. Skip when the change is meant to alter behavior (that's a feature or a fix).

★ 1
abhijitbansal
abhijitbansal/claude-skills

plan

Decompose a non-trivial task into an explicit, tracked plan with goals and per-step acceptance criteria before writing code. Use when the user says "plan this", "break this down", "what's the plan", or asks for a multi-step feature/refactor that touches more than one file. Pairs with plan mode. Skip for single-edit changes that need no decomposition.

★ 1