mvcc-isolation-tests
БесплатноБез исполняемых скриптовНе проверенUse when two concurrent database transactions can touch the same rows (balance debits, seat bookings, stock counts), or before changing a default isolation…
от testland★ 18 звёзд на GitHubОб этом скилле
mvcc-isolation-tests
Overview
Two transactions on two connections, interleaved deterministically with thread events, prove which anomalies the chosen isolation level allows and that the application copes. All tests below ran 5/5 green on PostgreSQL 16 with psycopg 3.
When to use
- Two transactions can touch the same rows (balance debit, seat booking, stock decrement, on-call rota).
- Choosing or changing a service's isolation level.
- Auditing whether "at least one X" invariants survive concurrency.
Step 1 - Anomalies and the PostgreSQL matrix
| Anomaly | Shape |
|---|---|
| Dirty read | T2 reads T1's uncommitted write |
| Non-repeatable read | T1 reads a row twice; T2 commits an update in between |
| Phantom read | T1 re-runs a predicate query; T2 committed a new matching row |
| Serialization anomaly (write skew) | Both read the same set, each writes a different row on that basis; no serial order gives the result |
| PostgreSQL level | Dirty | Non-repeatable | Phantom | Serialization anomaly |
|---|---|---|---|---|
| Read Uncommitted (acts as Read Committed) | no | yes | yes | yes |
| Read Committed (default) | no | yes | yes | yes |
| Repeatable Read | no | no | no | yes |
| Serializable | no | no | no | no |
Source: [PostgreSQL transaction isolation][pg]. Other databases differ: references/per-database.md.
Step 2 - Harness, fixtures and tests
Each test rebuilds the tables and checks the starting row counts before running, so a failed or aborted test cannot leak state into the next one. Events and barriers pin the interleaving (no sleeps), every wait has a timeout, and a hung thread fails the test instead of the run.
# tests/db/test_isolation.py
import os, threading, time
import psycopg
import pytest
from psycopg import IsolationLevel
DSN = os.environ.get("TEST_DSN", "dbname=test")
WAIT = 5 # seconds; a wait that times out fails the test instead of hanging
SCHEMA = """
DROP TABLE IF EXISTS accounts, orders, doctors;
CREATE TABLE accounts (id text PRIMARY KEY, balance int NOT NULL);
CREATE TABLE orders (id serial PRIMARY KEY, status text NOT NULL);
CREATE TABLE doctors (name text PRIMARY KEY, status text NOT NULL);
INSERT INTO accounts VALUES ('acc1', 100);
INSERT INTO orders (status) VALUES ('pending'), ('pending'), ('pending');
INSERT INTO doctors VALUES ('alice', 'on_call'), ('bob', 'on_call');
"""
def scalar(sql, *args):
with psycopg.connect(DSN, autocommit=True) as c:
return c.execute(sql, args).fetchone()[0]
def on_call():
return scalar("SELECT count(*) FROM doctors WHERE status = 'on_call'")
@pytest.fixture(autouse=True)
def fresh_tables():
"""Rebuild the tables before every test and refuse to run on unexpected state."""
with psycopg.connect(DSN, autocommit=True) as c:
c.execute(SCHEMA)
assert scalar("SELECT balance FROM accounts WHERE id = 'acc1'") == 100
assert scalar("SELECT count(*) FROM orders") == 3
assert on_call() == 2
def run_pair(work_a, work_b, level):
"""Run two workloads on two connections at `level`; return (results, errors)."""
conns = [psycopg.connect(DSN) for _ in range(2)]
for c in conns:
c.isolation_level = level
results, errors = {}, {}
def run(key, conn, work):
try:
results[key] = work(conn)
except Exception as e: # recorded, asserted by the test
errors[key] = e
conn.rollback()
threads = [threading.Thread(target=run, args=("a", conns[0], work_a)),
threading.Thread(target=run, args=("b", conns[1], work_b))]
for t in threads:
t.start()
for t in threads:
t.join(timeout=3 * WAIT)
assert not any(t.is_alive() for t in threads), "workload hung (lock wait?)"
for c in conns:
c.close()
return results, errors
def test_non_repeatable_read_under_read_committed():
read1, wrote = threading.Event(), threading.Event()
def reader(conn):
first = conn.execute("SELECT balance FROM accounts WHERE id = 'acc1'").fetchone()[0]
read1.set()
assert wrote.wait(WAIT)
second = conn.execute("SELECT balance FROM accounts WHERE id = 'acc1'").fetchone()[0]
conn.commit()
return first, second
def writer(conn):
assert read1.wait(WAIT)
conn.execute("UPDATE accounts SET balance = 200 WHERE id = 'acc1'")
conn.commit()
wrote.set()
results, errors = run_pair(reader, writer, IsolationLevel.READ_COMMITTED)
assert not errors
assert results["a"] == (100, 200) # Read Committed allows it
def test_no_phantom_under_repeatable_read():
read1, wrote = threading.Event(), threading.Event()
def reader(conn):
q = "SELECT count(*) FROM orders WHERE status = 'pending'"
first = conn.execute(q).fetchone()[0]
read1.set()
assert wrote.wait(WAIT)
second = conn.execute(q).fetchone()[0]
conn.commit()
ret
Установить mvcc-isolation-tests в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл mvcc-isolation-tests?
Use when two concurrent database transactions can touch the same rows (balance debits, seat bookings, stock counts), or before changing a default isolation level. Tests which anomalies each level prevents (dirty, non-repeatable and phantom reads, write skew) in PostgreSQL, MySQL and SQL Server.
Как установить скилл mvcc-isolation-tests?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл mvcc-isolation-tests запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic