DataDrivenAlex commited on
Commit
c3209f9
·
verified ·
1 Parent(s): 9f5bbee

Publish Concurrency Control Lab

Browse files
README.md CHANGED
@@ -1,10 +1,28 @@
1
  ---
2
  title: Concurrency Control Lab
3
- emoji: 📉
4
- colorFrom: gray
5
  colorTo: indigo
6
  sdk: static
7
  pinned: false
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Concurrency Control Lab
3
+ emoji: 🔀
4
+ colorFrom: blue
5
  colorTo: indigo
6
  sdk: static
7
  pinned: false
8
  ---
9
 
10
+ # Concurrency Control Lab
11
+
12
+ A hands-on simulator for a classic backend bug: two requests read the same record version, then overwrite each other's updates. Compare last-write-wins with optimistic locking and see when a retry preserves the intended edits.
13
+
14
+ ## Try the demo
15
+
16
+ Open the Space and change the initial value, client edits, commit order, or conflict-retry setting. The demo shows the version checks, accepted writes, conflicts, retries, and final value. The example is deterministic so the same request schedule always produces the same trace.
17
+
18
+ ## Run the Python model
19
+
20
+ ```bash
21
+ python -m unittest -v
22
+ ```
23
+
24
+ `engine.py` models a set of edits that all read one initial snapshot. Last-write-wins commits each stale computed value, illustrating lost updates. Optimistic locking accepts a write only when its base version matches the current version; a stale write is rejected, and an optional retry re-reads and recomputes against the latest value.
25
+
26
+ ## Scope and limitations
27
+
28
+ This is an educational, in-memory simulation, not a database benchmark or production concurrency library. It assumes integer deltas, a single record, a deterministic commit order, and no network failures. Real systems must define transaction isolation, retry limits/backoff, idempotency, validation, and user-facing conflict behavior for their database and workload. The browser demo is static and does not call a backend or persist data.
__pycache__/engine.cpython-314.pyc ADDED
Binary file (5.76 kB). View file
 
__pycache__/test_engine.cpython-314.pyc ADDED
Binary file (4.02 kB). View file
 
engine.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small deterministic model for comparing stale-write policies."""
2
+ from dataclasses import dataclass
3
+ from typing import Iterable, Literal
4
+
5
+ Policy = Literal["last_write_wins", "optimistic_locking"]
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class Edit:
10
+ client: str
11
+ delta: int
12
+ base_version: int
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Event:
17
+ client: str
18
+ kind: str
19
+ before: int
20
+ after: int
21
+ version: int
22
+ note: str
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Result:
27
+ value: int
28
+ version: int
29
+ accepted: int
30
+ conflicts: int
31
+ retries: int
32
+ lost_updates: int
33
+ events: tuple[Event, ...]
34
+
35
+
36
+ def simulate(initial: int, edits: Iterable[Edit], policy: Policy, retry_conflicts: bool = True) -> Result:
37
+ """Apply edits that all read an initial snapshot, in submission order.
38
+
39
+ last_write_wins writes each client's stale computed value, so later commits can
40
+ overwrite earlier changes. optimistic_locking rejects stale versions; optional
41
+ retries recompute the edit against the latest value and version.
42
+ """
43
+ if policy not in ("last_write_wins", "optimistic_locking"):
44
+ raise ValueError("policy must be last_write_wins or optimistic_locking")
45
+ edits = tuple(edits)
46
+ value, version = initial, 0
47
+ accepted = conflicts = retries = lost_updates = 0
48
+ events: list[Event] = []
49
+ for edit in edits:
50
+ if edit.base_version < 0:
51
+ raise ValueError("base_version cannot be negative")
52
+ if policy == "last_write_wins":
53
+ before = value
54
+ stale_value = initial + edit.delta
55
+ if accepted:
56
+ lost_updates += 1
57
+ value = stale_value
58
+ version += 1
59
+ accepted += 1
60
+ events.append(Event(edit.client, "write", before, value, version,
61
+ f"stale snapshot v{edit.base_version}; overwrote current value"))
62
+ continue
63
+
64
+ if edit.base_version == version:
65
+ before = value
66
+ value += edit.delta
67
+ version += 1
68
+ accepted += 1
69
+ events.append(Event(edit.client, "commit", before, value, version,
70
+ f"version matched v{edit.base_version}"))
71
+ else:
72
+ conflicts += 1
73
+ events.append(Event(edit.client, "conflict", value, value, version,
74
+ f"expected v{edit.base_version}, found v{version}"))
75
+ if retry_conflicts:
76
+ before = value
77
+ value += edit.delta
78
+ version += 1
79
+ accepted += 1
80
+ retries += 1
81
+ events.append(Event(edit.client, "retry", before, value, version,
82
+ f"re-read v{version - 1}; recomputed edit"))
83
+ return Result(value, version, accepted, conflicts, retries, lost_updates, tuple(events))
84
+
85
+
86
+ def concurrent_edits(initial: int, deltas: Iterable[tuple[str, int]]) -> tuple[Edit, ...]:
87
+ """Build edits whose clients all read the same initial version."""
88
+ if initial < 0:
89
+ raise ValueError("initial value cannot be negative")
90
+ return tuple(Edit(client, delta, 0) for client, delta in deltas)
index.html CHANGED
@@ -1,19 +1,35 @@
1
  <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
19
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
5
+ <title>Concurrency Control Lab</title>
6
+ <style>
7
+ :root{color-scheme:dark;--bg:#0b1020;--panel:#141c31;--line:#273550;--ink:#eef4ff;--muted:#a8b5cb;--blue:#71a7ff;--mint:#61dfb5;--amber:#ffcb77;--red:#ff8d93}
8
+ *{box-sizing:border-box}body{margin:0;background:radial-gradient(ellipse at top,#1c2d4c 0,#0b1020 58%);color:var(--ink);font:16px/1.5 ui-sans-serif,system-ui,-apple-system,Segoe UI,sans-serif}
9
+ main{max-width:1080px;margin:auto;padding:34px 20px 56px}.eyebrow{color:var(--mint);font-size:.78rem;text-transform:uppercase;letter-spacing:.15em;font-weight:700}h1{font-size:clamp(2rem,5vw,3.6rem);line-height:1.02;margin:.55rem 0 1rem;letter-spacing:-.04em}.lead{max-width:720px;color:#c4d0e4;font-size:1.08rem}.grid{display:grid;grid-template-columns:340px 1fr;gap:18px;margin-top:26px}.card{background:linear-gradient(160deg,#17223b,#11192b);border:1px solid var(--line);border-radius:18px;padding:20px;box-shadow:0 18px 48px #0003}.card h2{font-size:1.05rem;margin:0 0 14px}.field{margin:14px 0}.field label{display:flex;justify-content:space-between;gap:10px;color:#dbe6f7;font-size:.9rem;margin-bottom:7px}.field input,.field select{width:100%;background:#0d1527;color:var(--ink);border:1px solid #354565;border-radius:10px;padding:10px 12px;font:inherit}.field input[type=range]{padding:0;accent-color:var(--blue)}.buttons{display:flex;gap:8px;flex-wrap:wrap}.btn{border:1px solid #48608a;background:#1d2d4b;color:white;border-radius:10px;padding:9px 12px;cursor:pointer;font-weight:650}.btn.active{background:#315c98;border-color:#80adfa}.toggle{display:flex;align-items:center;gap:9px;color:var(--muted);font-size:.9rem}.stats{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:18px}.stat{background:#0d1527;border:1px solid var(--line);border-radius:12px;padding:12px}.stat span{display:block;color:var(--muted);font-size:.76rem}.stat strong{font-size:1.45rem}.result{display:flex;justify-content:space-between;align-items:center;background:#0d1527;border:1px solid #354565;border-radius:14px;padding:14px 16px;margin-bottom:18px}.result strong{font-size:1.65rem;color:var(--mint)}.result .bad{color:var(--amber)}.trace{display:grid;gap:8px}.event{display:grid;grid-template-columns:82px 1fr auto;gap:12px;align-items:center;background:#10192a;border-left:3px solid var(--blue);border-radius:9px;padding:10px 12px;font-size:.88rem}.event.conflict{border-left-color:var(--amber)}.event.retry{border-left-color:var(--mint)}.event .client{font-weight:750}.event small{color:var(--muted)}.note{margin-top:16px;color:var(--muted);font-size:.86rem}.section{margin-top:22px}.legend{display:flex;gap:14px;flex-wrap:wrap;color:var(--muted);font-size:.82rem}.dot{display:inline-block;width:9px;height:9px;border-radius:50%;background:var(--blue);margin-right:5px}.dot.amber{background:var(--amber)}.dot.mint{background:var(--mint)}footer{margin-top:24px;color:#8090aa;font-size:.8rem}@media(max-width:800px){.grid{grid-template-columns:1fr}.stats{grid-template-columns:repeat(2,1fr)}main{padding:25px 14px 40px}.event{grid-template-columns:65px 1fr}.event small{grid-column:2}}
10
+ </style>
11
+ </head><body><main>
12
+ <div class="eyebrow">Backend systems · concurrency</div>
13
+ <h1>Concurrency<br>Control Lab</h1>
14
+ <p class="lead">Three requests read the same record, then write in sequence. Watch a last-write-wins policy lose updates—and see optimistic locking reject stale writes before retrying them safely.</p>
15
+ <div class="grid">
16
+ <section class="card"><h2>Shape the race</h2>
17
+ <div class="field"><label for="initial">Starting balance <b id="initialLabel">100</b></label><input id="initial" type="range" min="20" max="200" step="10" value="100"></div>
18
+ <div class="field"><label>Concurrent edits</label><div id="editFields"></div></div>
19
+ <div class="field"><label>Commit order</label><div class="buttons" id="order"></div></div>
20
+ <div class="field"><label>Write policy</label><div class="buttons" id="policies"></div></div>
21
+ <label class="toggle"><input type="checkbox" id="retry" checked> Retry stale writes after re-reading</label>
22
+ <p class="note">Each request computes its change from version 0. Change order to see which stale write wins.</p>
23
+ </section>
24
+ <section class="card"><h2>Run result</h2><div class="stats" id="stats"></div><div class="result"><div><span id="resultLabel">Final balance</span><div id="resultNote" class="note"></div></div><strong id="finalValue">—</strong></div><h2>Commit trace</h2><div class="trace" id="trace"></div><div class="legend"><span><i class="dot"></i>Commit</span><span><i class="dot amber"></i>Conflict / overwrite</span><span><i class="dot mint"></i>Recomputed retry</span></div></section>
25
+ </div>
26
+ <section class="card section"><h2>Why versions matter</h2><p class="lead" style="font-size:.98rem">A version check turns silent data loss into an explicit conflict. Retrying is safe only when the operation can be recomputed against fresh state; production APIs also need transaction boundaries, idempotency, bounded retries, and a clear conflict response.</p></section>
27
+ <footer>Deterministic teaching model · no database, external service, or data persistence</footer>
28
+ </main>
29
+ <script>
30
+ const clients=[{id:'A',delta:15},{id:'B',delta:-8},{id:'C',delta:20}];let order=['A','B','C'];let policy='last_write_wins';
31
+ const $=id=>document.getElementById(id);const fmt=n=>n<0?`−${Math.abs(n)}`:`+${n}`;
32
+ function renderControls(){ $('editFields').innerHTML=clients.map(c=>`<div class="field"><label for="d${c.id}">Client ${c.id}<b>${fmt(c.delta)}</b></label><input id="d${c.id}" type="range" min="-30" max="40" step="1" value="${c.delta}"></div>`).join('');for(const c of clients)$(`d${c.id}`).oninput=e=>{c.delta=+e.target.value;renderControls();run()};$('order').innerHTML=order.map((id,i)=>`<button class="btn" data-id="${id}">${i+1} · ${id}</button>`).join('');document.querySelectorAll('#order button').forEach(b=>b.onclick=()=>{const i=order.indexOf(b.dataset.id);[order[i],order[(i+1)%order.length]]=[order[(i+1)%order.length],order[i]];renderControls();run()});$('policies').innerHTML=[['last_write_wins','Last write wins'],['optimistic_locking','Optimistic locking']].map(([v,n])=>`<button class="btn ${policy===v?'active':''}" data-policy="${v}">${n}</button>`).join('');document.querySelectorAll('#policies button').forEach(b=>b.onclick=()=>{policy=b.dataset.policy;renderControls();run()})}
33
+ function run(){const initial=+$('initial').value;$('initialLabel').textContent=initial;let value=initial,version=0,accepted=0,conflicts=0,retries=0,lost=0,events=[];for(const id of order){const c=clients.find(x=>x.id===id);if(policy==='last_write_wins'){const before=value;value=initial+c.delta;if(accepted)lost++;version++;accepted++;events.push({client:id,kind:'write',before,after:value,version,note:`stale snapshot v0 overwrote current value`})}else if(version===0){const before=value;value+=c.delta;version++;accepted++;events.push({client:id,kind:'commit',before,after:value,version,note:'version matched v0'})}else{conflicts++;events.push({client:id,kind:'conflict',before:value,after:value,version,note:`expected v0, found v${version}`});if($('retry').checked){const before=value;value+=c.delta;version++;accepted++;retries++;events.push({client:id,kind:'retry',before,after:value,version,note:`re-read v${version-1}, recomputed edit`})}}}$('finalValue').textContent=value;$('resultLabel').textContent='Final balance';$('resultNote').innerHTML=policy==='last_write_wins'?`Intended total: <b>${initial+clients.reduce((s,c)=>s+c.delta,0)}</b> · <span class="bad">${lost} update(s) overwritten</span>`:`${conflicts} stale conflict(s) · ${retries} retried`;const stats=[['Version',version],['Accepted writes',accepted],['Conflicts',conflicts],['Retries',retries]];$('stats').innerHTML=stats.map(([n,v])=>`<div class="stat"><span>${n}</span><strong>${v}</strong></div>`).join('');$('trace').innerHTML=events.map(e=>`<div class="event ${e.kind}"><span class="client">Client ${e.client}</span><span>${e.kind==='conflict'?'Request rejected':e.kind==='retry'?'Recomputed and committed':e.kind==='write'?'Stale value committed':'Committed'}<br><small>${e.note}</small></span><b>${e.before} → ${e.after}</b></div>`).join('')||'<div class="note">No edits to apply.</div>'}
34
+ $('initial').oninput=run;$('retry').onchange=run;renderControls();run();
35
+ </script></body></html>
test_engine.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ from engine import concurrent_edits, simulate
3
+
4
+
5
+ class ConcurrencyControlTests(unittest.TestCase):
6
+ def setUp(self):
7
+ self.edits = concurrent_edits(100, [("A", 15), ("B", -8), ("C", 20)])
8
+
9
+ def test_last_write_wins_exposes_lost_updates(self):
10
+ result = simulate(100, self.edits, "last_write_wins")
11
+ self.assertEqual(result.value, 120)
12
+ self.assertEqual(result.lost_updates, 2)
13
+ self.assertEqual(result.accepted, 3)
14
+
15
+ def test_optimistic_locking_retries_preserve_all_edits(self):
16
+ result = simulate(100, self.edits, "optimistic_locking", retry_conflicts=True)
17
+ self.assertEqual(result.value, 127)
18
+ self.assertEqual(result.conflicts, 2)
19
+ self.assertEqual(result.retries, 2)
20
+ self.assertEqual(result.version, 3)
21
+
22
+ def test_optimistic_locking_without_retry_leaves_conflicts_unapplied(self):
23
+ result = simulate(100, self.edits, "optimistic_locking", retry_conflicts=False)
24
+ self.assertEqual(result.value, 115)
25
+ self.assertEqual(result.conflicts, 2)
26
+ self.assertEqual(result.retries, 0)
27
+
28
+ def test_single_edit_has_same_result_under_both_policies(self):
29
+ edits = concurrent_edits(9, [("A", 4)])
30
+ self.assertEqual(simulate(9, edits, "last_write_wins").value, 13)
31
+ self.assertEqual(simulate(9, edits, "optimistic_locking").value, 13)
32
+
33
+ def test_rejects_unknown_policy_and_negative_start(self):
34
+ with self.assertRaises(ValueError):
35
+ simulate(100, self.edits, "merge_magic")
36
+ with self.assertRaises(ValueError):
37
+ concurrent_edits(-1, [("A", 1)])
38
+
39
+
40
+ if __name__ == "__main__":
41
+ unittest.main(verbosity=2)