Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

race-condition-test-author

БесплатноБез исполняемых скриптовНе проверен

Use when a bug only appears under load on shared in-process state (cache, counter, pool, lazy singleton), or a race needs a regression test before the fix…

testlandот testland★ 18 звёзд на GitHub

Об этом скилле

race-condition-test-author

Overview

Two complementary tools: a deterministic test that forces the bad interleaving with a start gate (or a hook inside the critical window), and a detector or stress harness (TSan, go test -race, jcstress) that explores interleavings you did not think of. A race fix is done when a test that failed before the fix passes after it, repeatedly.

When to use

  • A defect reproduces only under load on shared in-process state (cache, counter, pool, lazy singleton).
  • A race incident needs a regression test before the fix lands.
  • Adding a race detector to CI, or finding out why the existing one never fails.

Step 1 - Find the shared mutable state

Check each of: module-level / static mutable variables; singletons with mutable fields; get-then-set on caches or maps without a lock or CAS; per-request data stored on shared objects; pools; lazy initialisation ("if not initialised, initialise"). For each, write down the two operations that must not interleave.

Step 2 - Force the interleaving

A start gate makes both threads enter together; a hook inside the window makes the collision certain instead of likely:

import threading

def test_lazy_init_creates_one_instance(monkeypatch):
    in_window = threading.Barrier(2, timeout=0.5)
    real_build = LazyService._build

    def slow_build(self):
        try:
            in_window.wait()      # unfixed: both threads meet here, inside the window
        except threading.BrokenBarrierError:
            pass                  # fixed: only one thread gets here; carry on
        return real_build(self)

    monkeypatch.setattr(LazyService, "_build", slow_build)
    target = LazyService()
    results, errors = [None, None], []

    def worker(i):
        try:
            results[i] = target.lazy_get()
        except Exception as e:    # surface worker failures to the test thread
            errors.append(e)

    threads = [threading.Thread(target=worker, args=(i,)) for i in (0, 1)]
    for t in threads: t.start()
    for t in threads: t.join(timeout=10)
    assert not errors
    assert results[0] is results[1], "lazy init built two instances"

Verified with a check-then-build LazyService: the unfixed code fails 3/3 runs (both threads meet inside the window and build twice); with a lock around check-and-build it passes 3/3, because only one thread reaches _build and its barrier wait times out after 0.5 s. The same test serves before and after the fix.

Assertions belong on the test thread. An assertion or t.Fatal inside a worker thread, goroutine or executor task can fail silently; collect results and errors and assert after join().

When the shared state is not in process memory

A database row. Read-then-write in application code (SELECT the balance, check it, UPDATE with the computed value) races across connections, processes and pods, so a Python or Java lock cannot fix it.

  • Test on the engine production uses, with two separate connections. SQLite "implements serializable transactions by actually serializing the writes. There can only be a single writer at a time" ([sqlite-iso]), and a test that shares one connection (for example SQLAlchemy StaticPool) serializes the calls anyway. Either setup passes a test that Postgres or MySQL fails.
  • Force the interleaving the same way as above: a barrier or hook between the read and the write, so both connections read before either writes.
  • Fix it in the database: one conditional statement (UPDATE coupons SET uses_left = uses_left - 1 WHERE code = :c AND uses_left > 0, then check the row count), or SELECT ... FOR UPDATE before the check. In Postgres Read Committed, a blocked UPDATE re-evaluates its WHERE clause on the committed row version ([pg-iso]). Under Repeatable Read the loser gets "could not serialize access due to concurrent update" and must retry the whole transaction ([pg-iso]). Isolation-level testing in depth: mvcc-isolation-tests.

asyncio coroutines. One event loop thread still races: a coroutine can only be interrupted at an await, so if cache is None: cache = await load() lets every caller that arrives during load() start its own load.

  • A fake that returns without awaiting never suspends, so no other coroutine ever runs inside the window and the test cannot fail. Make the fake wait on an asyncio.Event that the test sets once all callers are waiting, rather than asyncio.sleep(0.01), which is the timing bet from the anti-patterns table in coroutine form.
  • Fix with an asyncio.Lock and re-check the state inside it (asyncio primitives "are not thread-safe" and threading locks block the loop ([asyncio-sync])), or share one in-flight asyncio.Task between callers.
  • If you share an in-flight task, clear it in finally. Otherwise a failed load stays cached and every later caller gets the same exception until a restart. Add a test where the first load raises and the
Полный SKILL.md на GitHub

Установить race-condition-test-author в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

.tessl-plugin/plugin.jsonevals/config-singleton-closed-as-not-reproducible/criteria.jsonevals/config-singleton-closed-as-not-reproducible/task.mdevals/double-charge-that-ci-was-green-through/criteria.jsonevals/double-charge-that-ci-was-green-through/task.mdevals/ingest-pods-oomkilled-while-the-detector-is-clean/criteria.jsonevals/ingest-pods-oomkilled-while-the-detector-is-clean/task.mdevals/nightly-ledger-total-comes-up-short/criteria.jsonevals/nightly-ledger-total-comes-up-short/task.mdevals/race-async-refresh/criteria.jsonevals/race-async-refresh/task.mdevals/race-check-then-act/criteria.jsonevals/race-check-then-act/task.mdevals/race-db-oversell/criteria.jsonevals/race-db-oversell/task.mdevals/three-findings-before-the-friday-release-cut/criteria.jsonevals/three-findings-before-the-friday-release-cut/task.mdreferences/go.mdreferences/goleak-filter-options.md

FAQ

Что делает скилл race-condition-test-author?

Use when a bug only appears under load on shared in-process state (cache, counter, pool, lazy singleton), or a race needs a regression test before the fix. Forces interleavings with barriers and latches, and runs ThreadSanitizer, go test -race with goleak, or jcstress for the JVM.

Как установить скилл race-condition-test-author?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл race-condition-test-author запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить race-condition-test-author с