TxTransactions Lab
GitHub
II · Implement isolation

Validate a transaction.

Optimistic concurrency lets a transaction do tentative work before deciding whether its observations are still usable. Implement that decision from recorded versions.

You will: build read/write sets, compare observed and current versions, and explain why write-conflict checking alone permits write skew. Prerequisites: write-skew dependencies and JavaScript maps. Runtime: an executable optimistic concurrency control (OCC) engine over two keys.

Concept diagram · before the experiment

Optimistic concurrency validates the read dependencies

A transaction reads key x at version 7 and stages a private write. Before publishing, it compares observed version 7 with the current version. A match permits this version check; current version 8 requires abort and a fresh attempt. Validation and publication must be protected together.
Read the diagram: The compared numbers are versions, not values. A changed version means the decision used stale information. In this model, validating the read set and publishing the write set form one protected step. More general serializability also needs correct handling of predicates and concurrent validators. Open full diagram

Predict

T1 reads A and B and writes A. T2 reads A and B and writes B. If validation checks only the rows each transaction writes, which invalidated observations are missed?

Read, validate, publish

The store keeps {value, version} per key. At begin, a transaction obtains a snapshot. Reads record observed versions; writes remain in a private map. Commit performs validation and publication in one ordered engine event:

read phase:      remember key → observed version; stage key → new value
validation:     compare dependencies with the current committed store
publication:    if valid, assign a commit version and install the write set
abort:          if invalid, discard the private write set

Atomic validate-and-publish matters. Two threads that both validate, then publish later without synchronization can both validate against the same old state. A real implementation needs a critical section, compare-and-swap protocol or equivalent serialization of this boundary.

Write-set validation checks whether another transaction overwrote a row this attempt plans to change. Read-set validation also checks observations that influenced its decision, including rows it did not change. This small engine conservatively validates every recorded read and every write base version.

Control the experiment

The page loads Baseline with A and B available and two decisions made from the same version. Select Run to end and inspect both statuses in Recorded dependencies and both values in Committed version store. Choose Repair and run again. Which tested version differs from the current version when T2 tries to commit?

An executable optimistic transaction engine with versioned key reads and atomic validate/publish. Finite key reads only; range predicates need additional tracking. This is OCC, not PostgreSQL SSI.

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 diagram separates recorded read versions and private writes, then shows the exact tested-versus-current comparison from the most recent validation event. It does not judge an already committed read against unrelated future changes.

    Read and implement the validator

    The surrounding engine supplies the versions and makes checking and publication one event. In the bench, select Test implementation. Compare the result for a stale read of a key the transaction does not write. In Your JavaScript implementation, return true only when every entry in readVersions matches currentVersions. A missing current key conflicts. Test again. The engine checks write base versions separately.

    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 validate(readVersions, currentVersions) {
      return Object.entries(readVersions).every(([key,version])=>currentVersions[key]===version);
    }
    
    function validation(config) {
      choose(config,'validation',['write-set','read-set']);
      const s={rows:{A:{value:true,version:0},B:{value:true,version:0}},clock:0,transactions:{},validationChecks:[]};
      const t=recorder(s,s=>[check('the committed roster retains at least one doctor',Object.values(s.rows).some(r=>r.value))]);
      for(const op of program(config)) {
        const [tx,action,key,text]=op.split(':');
        if(!['T1','T2'].includes(tx))throw Error('Use T1 or T2.');
        if(action==='begin') {
          if(s.transactions[tx])throw Error('Transaction already began.');
          s.transactions[tx]={snapshot:copy(s.rows),reads:{},writes:{},status:'active'};t.emit(`${tx} captures a snapshot and opens read/write sets`);continue;
        }
        const local=s.transactions[tx];if(!local||local.status!=='active')throw Error(`${tx} needs an active transaction.`);
        if(action==='read') {
          if(!s.rows[key])throw Error('Read A or B.');local.reads[key]=local.snapshot[key].version;t.emit(`${tx} records ${key}@version${local.reads[key]}`);
        }else if(action==='write') {
          if(!s.rows[key]||!['true','false'].includes(text))throw Error('Use T1:write:A:false.');
          local.writes[key]=text==='true';t.emit(`${tx} stages ${key} = ${text}`);
        }else if(action==='commit') {
          const versions=Object.fromEntries(Object.entries(s.rows).map(([k,row])=>[k,row.version]));
          const writes=Object.fromEntries(Object.keys(local.writes).map(k=>[k,local.snapshot[k].version]));
          const tested=config.validation==='read-set'?{...local.reads,...writes}:writes;
          const valid=validate(tested,versions);s.validationChecks.push({tx,tested,current:versions,valid});
          if(valid){s.clock++;for(const [k,value] of Object.entries(local.writes))s.rows[k]={value,version:s.clock};local.status='committed';}
          else local.status='aborted';
          t.emit(`${tx} validates ${config.validation} and ${local.status}`);
        }else throw Error('Use begin, read, write or commit.');
      }
      return t.finish();
    }
    Implementation bench · write the algorithm

    Implement optimistic validation

    solve(readVersions, currentVersions) returns true only when every recorded read version still equals the current version. Missing current keys conflict too. Empty read sets are valid.

    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(readVersions, currentVersions) {
        return Object.entries(readVersions).every(([key,version])=>currentVersions[key]===version);
      }
      Download your code

      Change one thing

      In Repair, open Edit the experiment. Replace schedule with ["T1:begin","T1:read:A","T1:read:B","T1:write:A:false","T1:commit","T2:begin","T2:read:A","T2:read:B","T2:commit"]. Select Run to end. Find T2’s read version of A and its final status.

      Insert "T2:write:B:false" before "T2:commit" and run again. Does T2 validate against fresh versions while still breaking the roster rule? Explain which decision belongs to the application.

      Hint 1 · Compare the actual version maps

      After T1 commits, A has a new version. T2's write-set-only test includes B but omits the stale observation of A.

      Hint 2 · Missing keys conflict too

      If a previously read key disappeared, its current version cannot equal the recorded version. An empty read set is valid, but that does not prove the transaction recorded everything it depended on.

      Why this result occurs

      The baseline validates B@0 while A has changed, so the two decisions can both commit. The repair compares A@0 with A@1 and aborts T2 before publishing its private write. This is an OCC implementation with sequential commit validation. PostgreSQL Serializable Snapshot Isolation uses a different mechanism: nonblocking predicate-read tracking and read/write dependency detection. Both must reason about observations, but they are not the same algorithm.

      Transfer the idea

      A request reads “all bookings overlapping this time interval.” Another transaction inserts a new overlapping row whose key was never read. Explain why validating only existing key versions misses this phantom. Add a range/predicate generation number to your proposed read set, and specify every insertion/deletion that must change it. Compare that design with predicate locking and PostgreSQL's SIREAD dependency tracking.

      Success criteria: show T2’s observed A version and the current A version at validation; abort before publishing stale private writes; pass the validator bench; identify a phantom that finite key versions cannot detect.

      Primary sources: Kung and Robinson, On Optimistic Methods for Concurrency Control and PostgreSQL Serializable isolation.

      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.