본문으로 건너뛰기
cccskills
무료GitHub에 공개

race-condition-test-author

Build deterministic race-condition tests - identify shared mutable state, drive interleavings via barriers / latches / manual scheduling; use ThreadSanitizer (clang `-fsanitize=thread`) for C/C++ data race detection; run the Go race detector end-to-end (`go test -race`, GORACE tuning, `-count`/`-cpu` stress, goroutine-leak gating with go.uber.org/goleak - references/go.md); use jcstress (`@JCStressTest` + `@Actor` + `@Outcome`) for JVM stress; use Loom virtual-thread interleavings for parallel testing. Use when a defect only reproduces under load on shared in-process state (cache, counter, connection pool, lazy-init singleton), when writing the regression test for a race-condition incident before the fix lands, or when adding `-race` to a Go CI matrix.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

testland/qa스타 13(GitHub 13 + cccskills 0)

실행 점수 미검증

설치 방법 보기

포함된 파일(14)

  • SKILL.md8.3 KB
  • .tessl-plugin/plugin.json905 B
  • evals/config-singleton-closed-as-not-reproducible/criteria.json6.1 KB
  • evals/config-singleton-closed-as-not-reproducible/task.md11.3 KB
  • evals/double-charge-that-ci-was-green-through/criteria.json7.0 KB
  • evals/double-charge-that-ci-was-green-through/task.md7.0 KB
  • evals/ingest-pods-oomkilled-while-the-detector-is-clean/criteria.json5.3 KB
  • evals/ingest-pods-oomkilled-while-the-detector-is-clean/task.md7.1 KB
  • evals/nightly-ledger-total-comes-up-short/criteria.json6.5 KB
  • evals/nightly-ledger-total-comes-up-short/task.md6.3 KB
  • evals/three-findings-before-the-friday-release-cut/criteria.json6.7 KB
  • evals/three-findings-before-the-friday-release-cut/task.md7.3 KB
  • references/go.md5.3 KB
  • references/goleak-filter-options.md1.6 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

race-condition-test-author

Race conditions are the canonical "works on my machine, breaks under load" bug. Tests must drive shared-state access deterministically (barriers, latches) AND non-deterministically (sanitizers, stress) to expose them.

When to use

  • Service handles concurrent requests on shared in-process state (caches, counters, connection pools).
  • Race-condition incident retro: build a regression test before fixing.
  • Pre-release smoke: TSan-instrumented binary catches data races that compile clean.

Step 1 - Identify shared mutable state

Code-review checklist:

  • Static / global / module-level mutable variables
  • Singleton instances with mutable fields
  • Cache structures with read-and-modify ("get-then-set" without CAS)
  • Per-request state stored on shared objects (mutable request context)
  • Connection pools / object pools without internal lock
  • Lazy-init patterns ("if not initialized, initialize")

For each: ask "what if two threads / goroutines / async tasks hit this concurrently?"

Step 2 - Deterministic interleaving via barriers

import threading

def test_lazy_init_thread_safe():
    target = LazyService()  # has private _instance + lazy_get()
    barrier = threading.Barrier(parties=2)
    results = [None, None]

    def worker(idx):
        barrier.wait()  # both threads stop here, then race
        results[idx] = target.lazy_get()

    t1 = threading.Thread(target=worker, args=(0,))
    t2 = threading.Thread(target=worker, args=(1,))
    t1.start(); t2.start()
    t1.join(); t2.join()

    assert results[0] is results[1], "Lazy init created two instances under race"

Barrier ensures both threads start the contended section at the same time - much higher probability of triggering the race than naive threading.Thread().

Step 3 - ThreadSanitizer for C/C++/Go

Per the ThreadSanitizer docs, TSan detects data races at runtime with ~5-15× overhead. For C/C++:

clang -fsanitize=thread -g -O1 program.c -o program
./program

For Go, the native data race detector:

go test -race ./...
go run -race main.go

The full Go workflow - GORACE options (log_path, halt_on_error, history_size), stress amplification via -count/-cpu, go vet loop-capture checks, goroutine-leak gating with goleak, and the CI matrix - is in references/go.md.

Output for a detected race:

WARNING: DATA RACE
Read at 0x... by goroutine 7:
  main.read+0x...
    main.go:42

Previous write at 0x... by goroutine 6:
  main.write+0x...
    main.go:38

Per the ThreadSanitizer docs, adaptive delay injection (TSAN_OPTIONS=enable_adaptive_delay=1) helps surface races at synchronization points.

Step 4 - jcstress for JVM

Per the jcstress docs, jcstress is "the experimental harness ... for the correctness of concurrency support in the JVM."

@JCStressTest
@Outcome(id = "0, 0", expect = ACCEPTABLE, desc = "Initial values")
@Outcome(id = "1, 1", expect = ACCEPTABLE, desc = "Both writes seen")
@Outcome(id = "0, 1", expect = ACCEPTABLE, desc = "Saw partial")
@Outcome(id = "1, 0", expect = FORBIDDEN, desc = "Reordered - bug")
@State
public class CounterTest {
    int x, y;

    @Actor
    public void writer() { x = 1; y = 1; }

    @Actor
    public void reader(II_Result r) {
        r.r1 = y;
        r.r2 = x;
    }
}

@Actor methods run concurrently on different threads; @Outcome classifies observed (r1, r2) pairs. FORBIDDEN outcomes indicate a memory-model violation (in this case, reordering allowed under JMM unless volatile or final).

Run:

java -jar jcstress.jar -m quick CounterTest

Per the jcstress docs: tests are probabilistic; longer runs find more reorderings.

Step 5 - Loom virtual-thread interleavings (Java 21+)

Java 21+ Project Loom enables cheap virtual threads. Use to test many-concurrent-task interleavings without OS thread cost:

@Test
void test_handles_10000_concurrent_orders() throws Exception {
    var orderService = new OrderService();
    try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
        var futures = IntStream.range(0, 10_000)
            .mapToObj(i -> executor.submit(() -> orderService.place(i)))
            .toList();
        for (var f : futures) f.get();
    }
    assertEquals(10_000, orderService.totalProcessed());
}

Virtual threads run M:N on OS threads - the JVM scheduler interleaves them aggressively, exposing schedule-dependent races.

Step 6 - Property-based + concurrency

Combine Hypothesis (Python) / fast-check (JS) with concurrency:

from hypothesis import given, strategies as st
import threading

@given(operations=st.lists(st.tuples(st.sampled_from(["read", "write"]), st.integers()), min_size=10, max_size=100))
def test_counter_property_under_concurrency(operations):
    counter = ThreadSafeCounter()
    threads = []
    for op, val in operations:
        if op == "write":
            threads.append(threading.Thread(target=lambda v=val: counter.set(v)))
        else:
            threads.append(threading.Thread(target=counter.get))

    for t in threads: t.start()
    for t in threads: t.join()

    # Property: final value is one of the written values
    assert counter.get() in [v for op, v in operations if op == "write"]

Cross-ref qa-property-based plugin for property-based test authoring patterns.

Step 7 - CI integration

# Go
- name: Run race detector
  run: go test -race ./...

# C/C++
- name: TSan build + test
  run: |
    cmake -B build -DCMAKE_C_FLAGS="-fsanitize=thread -g -O1"
    cmake --build build
    ./build/test_runner

# Java
- name: jcstress quick run
  run: java -jar jcstress.jar -m quick -r results/

Note the latency cost: go test -race ~3× slower; jcstress quick mode ~minutes per test class.

Anti-patterns

Anti-patternWhy it failsFix
time.sleep(0.001) to "force" interleavingNon-deterministic; flakeUse barriers (Step 2)
Run race tests once and assume greenProbabilistic; some races take hoursMultiple runs OR longer runs OR sanitizers
Skip TSan in CI for "release" buildsRace in release; CI passed without -raceTSan in CI for at least one matrix dimension (Step 7)
Depend on assertion in worker threadThread death silent; main thread sees passUse futures + assert from main
Test only the bug-causing race, not similarOther shared state has same pattern; bugs shipCode-review checklist (Step 1)

Limitations

  • TSan finds only data races (unsynchronized concurrent access), not higher-level race conditions (correct-but-non-atomic multi-step operations).
  • jcstress is JVM-only; no equivalent for non-JVM stacks.
  • Go's -race overhead is real (~5-10× memory); CI matrix budget required.
  • Loom virtual threads (Java 21+) require recent JDK; older versions need OS threads.

References

  • ThreadSanitizer docs - clang -fsanitize=thread, runtime options, adaptive delay
  • jcstress docs - @JCStressTest, @Actor, @Outcome outcomes
  • ThreadSanitizer C++ Manual - github.com/google/sanitizers/wiki/ThreadSanitizerCppManual
  • references/go.md - Go race detector + goleak workflow (GORACE, stress, CI matrix)
  • deadlock-detection-harness - sister skill for deadlock-specific patterns
  • async-ordering-tests - sister skill for async/await ordering

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Builds a CI gate that fails the build on **new** WCAG / a11y violations introduced by a PR while grandfathering pre-existing violations on a per-rule / per-page baseline. Aggregates verdicts from axe-core / pa11y / Lighthouse a11y / WAVE / IBM Equal Access scans. Use when a project has accumulated a11y debt and a strict "zero violations" gate would block every PR - the ratchet pattern lets the team ship while preventing regressions.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

testland/qa132026년 10월 20일 업데이트

Workflow skill that builds an A/B-test validity checklist from an experiment proposal, walking the canonical design-correctness gates - pre-registered OEC/power/guardrails, randomization unit + SRM check, assignment integrity, telemetry, peeking discipline, novelty/primacy, post-experiment SRM re-check - into a per-experiment checklist + sign-off form. Use when launching, auditing, or governing an experiment. For pitfall mechanics (guardrails, peeking) see experiment-results-interpreter's references; to read an already-valid result use experiment-results-interpreter; for per-SDK harness tests use experiment-sdk-testing - this gates DESIGN, not SDK code.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

testland/qa132026년 10월 20일 업데이트

The single install-flow skill: the reference contract for the PWA install flow (installability gate fields, `beforeinstallprompt` handshake, per-platform paths - Android WebAPK / iOS Share menu / Firefox no-op - and the `display-mode` post-install signal, in references/install-flow-reference.md) plus the build-an-X workflow that emits the Add-to-Home-Screen suite. Walks the four-stage timeline, emitting one test per gate cell per [web.dev/articles/install-criteria][install-criteria], the deferred-prompt → `prompt()` → `userChoice` chain per [web.dev/articles/customize-install][customize-install], the iOS Safari manual-metadata branch (`apple-touch-icon`) per [web.dev/learn/pwa/installation][learn-pwa], and the post-install `(display-mode: standalone)` MQ assertion. Output: a Playwright spec with per-stage cells plus a coverage matrix. Use when a PWA's manifest, icons, or install handler change, when install conversion drops at an unknown stage, or when triaging a flaky install assertion.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

testland/qa132026년 10월 20일 업데이트

Build-an-X workflow that uses an LLM to map existing tests to spec sections - given a spec doc + the test suite, the LLM identifies which tests cover which sections, surfaces uncovered sections (gap), and recommends specific tests to add. Output is a coverage matrix per spec ID. Scope is mapping tests that already exist and naming the gaps, not authoring tests for new acceptance criteria. Use when a spec doc and a test suite both exist but nobody can say which requirements are actually covered - before a release sign-off, an audit, or a decision about where to spend the next round of test effort.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

testland/qa132026년 10월 20일 업데이트

Generates tests from natural-language specs (acceptance criteria, user stories, requirements) using an LLM, with confidence scoring per test case (LLM self-assessment plus heuristics: assertion quality, naming, completeness), batching uncertain cases for human review, and integration with the team's existing test framework. Use when the user asks to generate unit tests from acceptance criteria, convert user stories to test cases, automate test creation from requirements, or augment a spec-driven test suite with AI-generated stubs that are then curated before merge.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

testland/qa132026년 10월 20일 업데이트

Configures Allure Report (test-runner adapter install, `allure-results` directory wiring, `categories.json` for failure classification, `history-trend.json` retention via the copy-history-between-runs pattern), runs the Allure CLI to convert `allure-results` to a static HTML site, and uploads the report as a CI artifact. Use when the team needs richer test reporting than JUnit XML - step-level attachments, per-test history, retry tracking, and severity / epic / feature labeling across framework-agnostic adapters (pytest, Jest, JUnit, TestNG, NUnit, Mocha). As a rich static HTML report generator, it is the open-source alternative to the sunset ExtentReports (JVM/.NET per-test HTML narrative); for hosted cross-run flakiness analytics rather than a static per-run report use currents-integration.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

testland/qa132026년 10월 20일 업데이트

testland의 스킬 모두 보기

이 스킬의 문제 신고