TxTransactions Lab
GitHub
II · Implement isolation

Build the lock manager.

“Take a lock” becomes concrete when you implement the compatibility check, queue the blocked request, construct its dependencies and decide which transaction to abort.

You will: trace shared/exclusive compatibility and upgrades, build a wait-for graph, and implement cycle detection. Prerequisites: transaction lifetime and JavaScript sets; directed-graph traversal is introduced here. Runtime: an executable lock table and request queues.

Concept diagram · before the experiment

Deadlock is a cycle of dependencies

Transaction A holds an exclusive lock on x and requests y. Transaction B holds an exclusive lock on y and requests x. A waits for B and B waits for A. Neither can release by completing. A detector aborts a victim to release its locks; consistent acquisition order prevents this cycle.
Read the diagram: The wait-for graph removes the resources and keeps the reason each transaction cannot advance. Arrows point from waiter to blocker. One waiting edge is ordinary contention; the cycle is the deadlock. Locks must cover the complete operation they protect. Open full diagram

Predict

A and B both hold shared locks on bike. Each now requests an exclusive lock on the same key. Does owning a shared lock give either permission to upgrade immediately?

Compatibility before policy

A shared lock (S) permits another shared owner; an exclusive lock (X) conflicts with every other owner's S or X. A requester's existing ownership does not conflict with itself. Upgrading S to X still requires all other owners to stop holding conflicting locks.

Held by another transaction Request S Request X
S grant if queue policy permits wait
X wait wait

A lock-table entry contains holders and a FIFO request queue. A blocked transaction stops issuing operations. Releasing an owner's locks lets the manager reconsider the queue head and grant eligible requests. The engine retains all granted locks until commit or abort, a conservative rigorous two-phase locking discipline. Strict 2PL retains exclusive locks until transaction end while also following the two-phase acquisition rule; implementations vary in how long they retain shared locks.

Control the experiment

The page loads Baseline with two shared requests, two upgrades and a cycle check. Select Step through both upgrades. Compare Granted owners, Waiting requests and the arrows in the wait-for graph. Which request closes the cycle?

Actual S/X compatibility checks, FIFO queues, graph construction and DFS cycle detection. Two named clients and two keys; no lock escalation or SQL lock modes. Locking protects access, not durable storage.

Edit the experiment

Change the JSON settings and select Step or Run to end. Restore scenario reloads the selected preset.

Select Step to inspect the initial state.

    The wait-for drawing uses directed arrows from each waiting transaction to its blockers. Step through both upgrades and the detector: the cycle appears before the victim aborts, then disappears when its ownership and queued request are removed.

    Choose Repair and select Run to end. The detector chooses the younger transaction to abort. Check Granted owners and Waiting requests. Which transaction can now acquire X, and why?

    The detector algorithm

    Depth-first search keeps a recursion-stack set and a completed set. Encountering a node already on the current recursion stack proves a directed cycle. Encountering an already completed node does not: two branches can share the same downstream owner without deadlocking. Select Test implementation and inspect the diamond case. In Your JavaScript implementation, track the nodes on the current search path separately from completed nodes. Test again and compare the diamond with a real cycle.

    Read the engine code executed by this lab

    These functions come directly from the running engine. Shared helpers and every mechanism are in the complete downloadable module.

    function compatible(held, requested) { return held==='S'&&requested==='S'; }
    
    function hasCycle(graph) {
      const visiting=new Set(),finished=new Set();
      function visit(node) {
        if(visiting.has(node))return true;
        if(finished.has(node))return false;
        visiting.add(node);
        if((graph[node]||[]).some(visit))return true;
        visiting.delete(node);finished.add(node);return false;
      }
      return Object.keys(graph).some(visit);
    }
    
    function lockManager(config) {
      choose(config,'deadlock',['ignore','abort-youngest']);
      const s={transactions:{A:'active',B:'active'},locks:{},waitFor:{},victims:[],cycle:false};
      const t=recorder(s,s=>[check('the wait-for graph has no cycle',!s.cycle),check('incompatible locks never have different simultaneous owners',Object.values(s.locks).every(l=>Object.entries(l.holders).every(([a,m])=>Object.entries(l.holders).every(([b,n])=>a===b||compatible(m,n)))))]);
      const blockers=(lock,request)=>Object.entries(lock.holders).filter(([owner,mode])=>owner!==request.tx&&!compatible(mode,request.mode)).map(([owner])=>owner);
      function graph() {
        s.waitFor={};
        for(const lock of Object.values(s.locks))for(const [i,request] of lock.queue.entries()) {
          const ahead=lock.queue.slice(0,i).filter(r=>r.tx!==request.tx&&!compatible(r.mode,request.mode)).map(r=>r.tx);
          s.waitFor[request.tx]=[...new Set([...(s.waitFor[request.tx]||[]),...blockers(lock,request),...ahead])];
        }
        s.cycle=hasCycle(s.waitFor);
      }
      function wake() {
        for(const lock of Object.values(s.locks))while(lock.queue.length&&!blockers(lock,lock.queue[0]).length){const r=lock.queue.shift();lock.holders[r.tx]=r.mode;}
        graph();
      }
      function release(tx,terminal) {
        if(s.transactions[tx]!=='active')throw Error(`${tx} is not active.`);
        s.transactions[tx]=terminal;
        for(const lock of Object.values(s.locks)){delete lock.holders[tx];lock.queue=lock.queue.filter(r=>r.tx!==tx);}
        wake();
      }
      for(const op of program(config)) {
        if(op==='detect') {
          graph();
          if(s.cycle&&config.deadlock==='abort-youngest') {
            // Select a participant in a cycle, not an unrelated waiter downstream of it.
            const inCycle=Object.keys(s.waitFor).filter(tx=>{const reaches=(node,seen=new Set())=>node===tx||(!seen.has(node)&&(seen.add(node),(s.waitFor[node]||[]).some(n=>reaches(n,seen))));return(s.waitFor[tx]||[]).some(n=>reaches(n));});
            const victim=inCycle.sort().at(-1);s.victims.push(victim);release(victim,'aborted');t.emit(`Detector aborts ${victim}; release locks and grant the surviving upgrade`);
          }else t.emit(s.cycle?'Detector finds a cycle; policy leaves it blocked':'Detector finds no cycle');
          continue;
        }
        const [tx,mode,key]=op.split(':');
        if(!['A','B'].includes(tx)||s.transactions[tx]!=='active')throw Error('Use an active A or B transaction.');
        if(mode==='commit'&&Object.values(s.locks).some(l=>l.queue.some(r=>r.tx===tx)))throw Error('A waiting transaction must finish its blocked operation or abort before commit.');
        if(['commit','abort'].includes(mode)){release(tx,mode==='commit'?'committed':'aborted');t.emit(`${tx} ${mode}s and releases all locks`);continue;}
        if(!['S','X'].includes(mode)||!['bike','helmet'].includes(key))throw Error('Use A:S:bike, B:X:helmet, A:commit, or detect.');
        const lock=s.locks[key]??={holders:{},queue:[]};
        if(Object.values(s.locks).some(l=>l.queue.some(r=>r.tx===tx)))throw Error(`${tx} is waiting and cannot issue another operation.`);
        const request={tx,mode};
        if(lock.holders[tx]==='X'||(lock.holders[tx]===mode)){t.emit(`${tx} already owns ${mode} or stronger on ${key}`);continue;}
        if(!lock.queue.length&&!blockers(lock,request).length)lock.holders[tx]=mode;
        else lock.queue.push(request);
        graph();t.emit(`${tx} requests ${mode} on ${key}: ${lock.queue.some(r=>r.tx===tx)?'queued':'granted'}`);
      }
      return t.finish();
    }
    Implementation bench · write the algorithm

    Implement deadlock detection

    solve(graph) returns true exactly when the directed wait-for graph contains a cycle. Keys are transaction IDs; each array lists owners that transaction waits for. A shared dependency and a long acyclic chain are not cycles.

    The trace above uses the published algorithm. Test your own function here against the named cases.

    Test the starter to find the cases it misses.

      Compare the reference implementation

      Attempt the named cases before comparing your solution.

      function solve(graph) {
        const visiting=new Set(),finished=new Set();
        function visit(node) {
          if(visiting.has(node))return true;
          if(finished.has(node))return false;
          visiting.add(node);
          if((graph[node]||[]).some(visit))return true;
          visiting.delete(node);finished.add(node);return false;
        }
        return Object.keys(graph).some(visit);
      }
      Download your code

      Change one thing

      In Repair, open Edit the experiment and set schedule to ["A:X:bike", "B:S:bike", "A:commit", "B:commit"]. Select Run to end, then revisit B requests S on bike: queued and A commits. Compare the owners and queue before and after release. Run ["A:S:bike", "A:X:bike"] next. Why can one owner upgrade without waiting? Finally run ["A:X:bike", "B:S:bike", "B:X:bike"] and read the input error for an operation from a blocked transaction.

      Hint 1 · Build dependencies from actual blockers

      For each queued request, identify conflicting holders and earlier incompatible queued requests. A long wait alone is not a cycle.

      Hint 2 · Use two traversal sets

      The active DFS stack and the fully explored set have different meanings. Mark a node finished only after exploring its outgoing edges.

      Why this result occurs

      The upgrade cycle exists because each transaction holds a shared lock that prevents the other's exclusive request. Aborting B releases its S lock and removes its queued X request, allowing A to upgrade. A production abort must also undo B's data changes, cancel its waits and preserve recovery correctness. This lock-table engine models ownership and scheduling; the transaction manager and recovery engine explain the other responsibilities.

      Transfer the idea

      Design three transactions holding x, y and z respectively, each requesting the next resource in a cycle. Derive the graph and test your downloaded detector with it. Remove one request and explain why the remaining shared downstream dependency is not itself a cycle. The browser ownership engine has two clients; the detector function accepts a larger graph.

      Optional extension: propose intention locks for a table/row hierarchy, or a fairness rule preventing new readers from starving a queued writer. Specify the extra compatibility and queue dependencies before extending the engine.

      Success criteria: derive the upgrade cycle from conflicting holders and queued requests; show release and wakeup after victim abort; pass the detector bench including shared downstream nodes; distinguish cycle detection from timeout.

      Primary sources: PostgreSQL locking and deadlocks and SQLite locking protocol.

      Your design record

      Explain what happened and cite the run or SQL result that supports it.

      Write your design notes

      Download notes and evidence

      Downloads include current editor text. Run evidence stays on this page until you leave.