MVCC Snapshot Isolation Simulator

Simulate multi-version concurrency control so a transaction reads a consistent snapshot while others commit new versions.

TypescriptData Integrity

Code

typescriptsnippet
33 lines
interface VersionedRow {
  readonly key: string;
  readonly value: string;
  readonly startTs: number;
  readonly endTs: number;
}

export class MvccStore {
  private versions: VersionedRow[] = [];
  private clock = 0;

  beginTransaction(): number {
    return ++this.clock;
  }

  write(key: string, value: string, ts: number): void {
    for (const row of this.versions) {
      if (row.key === key && row.endTs === Number.POSITIVE_INFINITY) row.endTs = ts;
    }
    this.versions.push({ key, value, startTs: ts, endTs: Number.POSITIVE_INFINITY });
  }

  read(key: string, snapshotTs: number): string | undefined {
    let found: VersionedRow | undefined;
    for (const row of this.versions) {
      if (row.key !== key) continue;
      if (row.startTs <= snapshotTs && snapshotTs < row.endTs) {
        if (!found || row.startTs > found.startTs) found = row;
      }
    }
    return found?.value;
  }
}

How the snippet works

Count the class MvccStore as the entire surface area of MVCC Snapshot Isolation Simulator.

Points of care

  • The guard row.key !== key short-circuits the flow with an early continue when its condition holds.

Using it

The surface worth importing is MvccStore; the helpers around it are private to the snippet.

Key statements

return found?.value;
return ++this.clock;

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring.