TxTransactions Lab
GitHub
III · Implement durability

Build log recovery.

A buffer pool can write an uncommitted page before commit and leave a committed page unwritten after commit. Recovery needs enough durable history to handle both.

You will: trace before/after log records, dirty-page recLSNs, pageLSNs, a checkpoint and analysis/redo/undo. Prerequisites: WAL ordering and commit. Runtime: an executable single-writer log and page engine, not a production storage manager.

A winner has a durable COMMIT. A loser has unfinished work that recovery must undo. A checkpoint records metadata about active transactions and modified pages so restart can recover its work list.

Concept diagram · before the experiment

Why recovery needs both redo and undo

No-force allows a committed update to remain only in a lost buffer, so redo restores its durable logged value. Steal allows an uncommitted update to have reached disk, so undo removes the loser’s effect. A pageLSN guard prevents a redo record from being applied twice.
Read the diagram: The two policies create different recovery jobs. “Redo” does not mean blindly adding a change again: inspect the durable page’s pageLSN and the log record’s LSN before applying it. The foundation model uses before/after images; the optional ARIES lab adds compensation records. Open full diagram

Predict

Choose the loser scenario on paper: Alice’s logged debit reaches disk, then a checkpoint records T1 as active, with no COMMIT. Is T1 a winner after restart? Predict whether its pre-checkpoint UPDATE remains necessary and which value undo restores. Contrast a durable COMMIT whose Bob page is still old.

Why both redo and undo exist

The buffer pool caches data pages. A dirty page contains changes not fully installed in its disk image. Steal permits flushing a page containing an uncommitted change, making undo necessary. No-force permits acknowledging a committed transaction without forcing all its data pages, making redo necessary. A no-steal design can avoid this kind of loser-page undo; a force design pays more data-page writes at commit.

The model exposes these structures:

Structure What it records
UPDATE log record LSN, transaction ID, previous transaction LSN, page, before-image, after-image
Buffered page value, latest pageLSN, first still-dirty recLSN
Disk page persisted value and pageLSN
flushedLSN end of the durable log prefix
Transaction descriptor active/committed status and lastLSN
Checkpoint snapshot transaction metadata and dirty-page table; data pages need not all be forced

A log sequence number (LSN) orders log records. WAL requires flushedLSN >= page.pageLSN before that dirty page reaches disk. Durable COMMIT requires flushing its record and the preceding records. It does not require forcing all data pages. Here checkpoint metadata is captured atomically between operations; it does not implement a production fuzzy-checkpoint merge while transactions continue.

Control the experiment

The page loads Baseline with two balances of 100 and write-ahead ordering disabled. Select Run to end to reveal the schedule, then select Flush alice without enforcing write-ahead ordering and Crash & recover here. Compare Alice’s disk value with the durable log. Which evidence is missing for undo?

A one-writer steal/no-force buffer and log engine with LSNs, an atomic metadata checkpoint, redo and before-image undo. No torn pages, log truncation, concurrent writers or ARIES compensation records. A model crash discards volatile frames and log suffixes.

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 log strip distinguishes durable records from buffered records. Below it, buffer and disk pages display their actual pageLSNs. An unsafe disk page is marked when it gets ahead of the durable log. These are logical record positions, not measured I/O time or byte widths.

    Choose Repair and select Run to end. Revisit Flush alice only after flushing its WAL dependency, then select Crash & recover here. Find T1 under Losers and Alice’s restored value under Undo decisions. Select the final Flush COMMIT step and crash again. Which transaction is now a winner, and which page needed redo?

    Restart in three phases

    1. Analysis: inspect the durable checkpoint and subsequent log to reconstruct committed winners, unfinished losers and a conservative dirty-page table.
    2. Redo: start at the earliest required dirty-page recLSN. For each UPDATE, apply it only if the disk pageLSN is below the record's LSN. Equal means already applied.
    3. Undo: for this one-writer engine, traverse a loser's UPDATE records backward and restore before-images. Commit winners must not be undone.

    This implementation retains the whole log and uses a simple undo pass. It is not ARIES: there are no compensation log records (CLRs), undoNextLSNs, concurrent writers or interrupted-undo protocol. ARIES logs undo progress so recovery itself can be interrupted safely without simply redoing arbitrary work. Do not infer full ARIES correctness from this smaller engine.

    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 needsRedo(pageLSN, recordLSN) { return pageLSN < recordLSN; }
    
    function recoveryEngine(config) {
      choose(config,'wal',['disabled','enforced']);
      const s={disk:{alice:{value:100,pageLSN:0},bob:{value:100,pageLSN:0}},buffer:{alice:{value:100,pageLSN:0,recLSN:null},bob:{value:100,pageLSN:0,recLSN:null}},log:[],flushedLSN:0,transaction:{status:'active',lastLSN:0},checkpoint:null,acknowledged:false};
      const t=recorder(s,()=>[check('recovered transfer is atomic and acknowledged commits survive',null)]);
      const append=record=>{const lsn=s.log.length+1;s.log.push({lsn,...(record.tx?{prevLSN:s.transaction.lastLSN}:{}),...record});if(record.tx)s.transaction.lastLSN=lsn;return lsn;};
      append({type:'BEGIN',tx:'T1'});t.emit('Append BEGIN; the log buffer is not durable yet');
      for(const op of program(config)) {
        const [action,page,text]=op.split(':');
        if(action==='update') {
          if(s.transaction.status!=='active'||!s.buffer[page])throw Error('Update an active transaction on alice or bob.');
          const delta=Number(text);if(!Number.isSafeInteger(delta)||Math.abs(delta)>1000)throw Error('Use a bounded integer delta.');
          const frame=s.buffer[page],lsn=append({type:'UPDATE',tx:'T1',page,before:frame.value,beforePageLSN:frame.pageLSN,after:frame.value+delta});
          frame.value+=delta;frame.pageLSN=lsn;frame.recLSN??=lsn;t.emit(`Dirty ${page} in the buffer pool at LSN ${lsn}`);
        }else if(action==='flush') {
          const frame=s.buffer[page];if(!frame)throw Error('Flush alice or bob.');
          if(config.wal==='enforced')s.flushedLSN=Math.max(s.flushedLSN,frame.pageLSN);
          s.disk[page]={value:frame.value,pageLSN:frame.pageLSN};frame.recLSN=null;
          t.emit(`Flush ${page}${config.wal==='enforced'?' only after flushing its WAL dependency':' without enforcing write-ahead ordering'}`);
        }else if(action==='flush-log') {
          s.flushedLSN=s.log.length;t.emit('Flush all buffered log records');
        }else if(action==='checkpoint') {
          const dirty=Object.fromEntries(Object.entries(s.buffer).filter(([,f])=>f.recLSN!==null).map(([p,f])=>[p,f.recLSN]));
          const lsn=append({type:'CHECKPOINT',dirty,transaction:copy(s.transaction)});s.flushedLSN=lsn;
          s.checkpoint={lsn,dirty,transaction:copy(s.log.at(-1).transaction)};t.emit('Persist checkpoint metadata atomically, without forcing data pages');
        }else if(action==='commit') {
          if(s.transaction.status!=='active')throw Error('Transaction has already finished.');
          s.flushedLSN=append({type:'COMMIT',tx:'T1'});s.transaction.status='committed';s.acknowledged=true;
          t.emit('Flush COMMIT and earlier log records; acknowledge without forcing data pages');
        }else throw Error(`Unknown buffer/log operation ${op}`);
      }
      return t.finish();
    }
    
    function recoverEngine(original) {
      const s=copy(original),durable=s.log.filter(r=>r.lsn<=s.flushedLSN);
      s.discardedLogLSNs=s.log.filter(r=>r.lsn>s.flushedLSN).map(r=>r.lsn);s.log=durable;
      const cp=[...durable].reverse().find(r=>r.type==='CHECKPOINT');
      const dirty={...(cp?.dirty||{})};
      let phase=cp?.transaction.status??'absent',lastLSN=cp?.transaction.lastLSN??0;
      const scanned=durable.filter(r=>r.lsn>(cp?.lsn||0));
      for(const r of scanned) {
        if(r.tx==='T1'){phase=r.type==='COMMIT'?'committed':'active';lastLSN=r.lsn;}
        if(r.type==='UPDATE')dirty[r.page]=Math.min(dirty[r.page]??r.lsn,r.lsn);
      }
      const committed=phase==='committed';
      const redoStart=Math.min(...Object.values(dirty));
      s.analysis={checkpointLSN:cp?.lsn||0,winners:committed?['T1']:[],losers:phase==='active'?['T1']:[],analysisScannedLSNs:scanned.map(r=>r.lsn),undoStartLSN:phase==='active'?lastLSN:null,dirtyPageTable:dirty,redoStartLSN:Number.isFinite(redoStart)?redoStart:null};
      s.redo=[];s.undo=[];
      for(const r of durable)if(r.type==='UPDATE'&&r.lsn>=redoStart) {
        const applied=needsRedo(s.disk[r.page].pageLSN,r.lsn);
        s.redo.push({lsn:r.lsn,page:r.page,applied});
        if(applied)s.disk[r.page]={value:r.after,pageLSN:r.lsn};
      }
      // One transaction, no interleaved writers: before-image undo in reverse LSN order.
      // This intentionally does not implement ARIES compensation log records.
      const byLSN=new Map(durable.map(r=>[r.lsn,r]));
      if(phase==='active')for(let next=lastLSN;next;) {
        const r=byLSN.get(next);if(!r)throw Error('Undo depends on a log record that was not retained.');
        if(r.type==='UPDATE'){s.disk[r.page]={value:r.before,pageLSN:r.beforePageLSN};s.undo.push({lsn:r.lsn,page:r.page,restored:r.before});}
        next=r.prevLSN;
      }
      s.buffer=copy(s.disk);s.transaction={status:committed?'committed':phase==='active'?'aborted':'absent',lastLSN};
      const expected=committed?{alice:70,bob:130}:{alice:100,bob:100};
      return {label:'Restart: analyze durable log, redo by pageLSN, then undo the loser',state:s,checks:[check('recovery yields the complete committed transfer or the complete old state',Object.entries(expected).every(([p,v])=>s.disk[p].value===v)),check('acknowledged COMMIT is present in the durable log',s.acknowledged?committed:null)]};
    }

    Implement the redo guard

    Select Test implementation and inspect the equality case. In Your JavaScript implementation, return true only when pageLSN < recordLSN. Test again. Compare that rule with the Redo decisions from a repair where a page has already been installed.

    Implementation bench · write the algorithm

    Implement the page redo guard

    solve(pageLSN, recordLSN) returns true only when the data page has not incorporated this log record. LSNs are monotonic nonnegative integers. Equal means already applied.

    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(pageLSN, recordLSN) { return pageLSN < recordLSN; }
      Download your code

      Change one thing

      Choose loser, select Run to end, then Crash & recover here. In Recovery analysis and Undo decisions, check whether the checkpoint committed T1 or retained an earlier UPDATE needed for undo.

      Choose Repair and open Edit the experiment. Delete "checkpoint" from schedule, select Run to end, then Crash & recover here. Compare Redo start with a repaired run that keeps the checkpoint. Restore the scenario, append "flush:bob" after "commit", run and crash again. Is Bob’s UPDATE applied or skipped under Redo decisions?

      Restore the scenario again. Replace "update:alice:-30" with "update:alice:-15", "update:alice:-15". Run to end to reveal the steps and inspect the prevLSN chain in Log records. Crash at the Alice flush before COMMIT, then at the final COMMIT. Compare the order of restored values and the final Disk value for each page.

      Hint 1 · Separate durable facts from buffered intentions

      Crash discards the log suffix after flushedLSN and every volatile frame. Recovery can use only the retained log and disk images, plus acknowledged outcomes held by the outside observer.

      Hint 2 · A checkpoint is not a commit or automatic log truncation

      An active transaction can have records before the checkpoint that undo still needs. A dirty page can have an older recLSN that redo still needs. The checkpoint records those dependencies rather than erasing them.

      Why this result occurs

      Enforcing WAL makes an uncommitted page flush recoverable because its before-image survives first. No-force commit is recoverable because after-images and COMMIT survive even when a data page does not. The pageLSN guard skips durable work already installed. A checkpoint can shorten reconstruction without making all earlier log records disposable. The transfer verifier is independent of the engine's completion status.

      Optional advanced continuation

      A1 · ARIES recovery implements redo-only compensation log records and undoNextLSN chains across repeated crashes, with multiple interleaved transactions. Take it after this foundation when you want to extend the recovery machinery.

      Transfer the idea

      Design a log-retention decision with a dirty Bob page and an active T1 whose earlier Alice update may need undo. Identify the oldest records each dependency still needs, then explain why neither a checkpoint nor flushing one page alone makes the whole earlier prefix disposable. State when both dependencies would be discharged. This is a design task; the browser engine retains its whole log.

      Optional advanced extension: continue to A1 to add compensation log records and restartable undo. CLR design is outside the core completion criteria.

      Success criteria: classify a checkpointed active transaction as a loser; cite an actual applied/skipped LSN and an undo before-image; pass the redo guard bench; justify retaining pre-checkpoint log records without requiring the optional ARIES protocol.

      Primary sources: PostgreSQL WAL, checkpoints and Mohan et al., ARIES.

      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.