Persistent SQL Storage Layer for Catalogs and Row Operations
Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Build the persistent disk-backed execution layer (StorageEngine) that sits at the bottom of a relational database engine. Upstream components have already handled SQL lexing, query planning, and syntax checks; your responsibility is maintaining on-disk catalog metadata and durable table storage under a filesystem directory root.
Data is organized into a three-tier hierarchy: a database holds named schemas, and each schema holds named tables. Every completed catalog change and row mutation must survive process restarts (modeled by instantiating a fresh StorageEngine(root) against the same directory) and must be all-or-nothing if the process crashes or encounters an I/O failure mid-operation.
Implement StorageEngine with the starter contract:
Row = Dict[str, Any]
Where = Optional[Callable[[Row], bool]]
TYPES = {
"INT": (int,),
"REAL": (int, float),
"TEXT": (str,),
"BOOL": (bool,),
}
Catalog Operations
create_database(database: str) -> None: Register a new top-level database.create_schema(database: str, schema: str) -> None: Register a new schema inside an existingdatabase.create_table(database: str, schema: str, table: str, columns: List[Tuple[str, str]]) -> None: Register a new table insidedatabase.schemawith ordered(column_name, column_type)pairs drawn fromTYPES.- Commit every catalog update atomically by writing the updated catalog to a temporary file and swapping it into place with
os.replaceso a crash or failedos.replaceleaves neither memory nor disk partially updated.
Row Storage and CRUD Operations
data_file(database: str, schema: str, table: str) -> str: Return the filesystem path of the table's append-only log file.insert(database: str, schema: str, table: str, row: Row) -> int: Append one row to the table's log file and return its assigned integer row ID (1, 2, 3, ...). Any table column omitted fromrowdefaults toNone(NULL). Row IDs strictly increase starting at1and are never reused, even after deletions and across restarts.select(database: str, schema: str, table: str, where: Where = None) -> List[Row]: Scan the table in original insertion order and return fresh dictionary copies of every row wherewhere(row)is truthy (or all live rows whenwhereisNone). Caller edits to returned dictionaries must not mutate stored state.update(database: str, schema: str, table: str, changes: Row, where: Where = None) -> int: Overwrite the specifiedchangescolumns on every row matchingwhereas one atomic append-only batch (preserving each row's original insertion position) and return the number of matched rows.delete(database: str, schema: str, table: str, where: Where = None) -> int: Remove every row matchingwhereas one atomic append-only batch and return the number of deleted rows.
Type Validation & Error Handling
Raise StorageError whenever an operation violates stored catalog or schema rules (leaving memory and disk completely unchanged):
- Creating an already-existing database, schema, or table within the same parent namespace (distinct parent namespaces may reuse names).
- Referencing a missing database, schema, or table in any method.
- Declaring duplicate column names or a column type outside TYPES.
- Supplying an unknown column name or an incompatible runtime type in insert or update:
- None is valid for every column type.
- Because bool subclasses int in Python, True and False are valid only for "BOOL" and must be rejected for "INT" and "REAL".
- "REAL" accepts both int and float inputs and normalizes int values to float (for example, 24 is stored and read back as 24.0).
Examples
Example 1
engine = StorageEngine(root)
engine.create_database("store")
engine.create_schema("store", "sales")
engine.create_table(
"store", "sales", "products",
[("sku", "INT"), ("title", "TEXT"), ("price", "REAL"), ("available", "BOOL")],
)
id1 = engine.insert("store", "sales", "products", {"sku": 101, "title": "lamp", "price": 24, "available": True})
id2 = engine.insert("store", "sales", "products", {"sku": 102, "title": "desk"})
restarted = StorageEngine(root)
cheap = restarted.select("store", "sales", "products", lambda r: r["sku"] == 101)
all_rows = restarted.select("store", "sales", "products")
Output:
id1 -> 1
id2 -> 2
cheap -> [{"sku": 101, "title": "lamp", "price": 24.0, "available": True}]
all_rows -> [
{"sku": 101, "title": "lamp", "price": 24.0, "available": True},
{"sku": 102, "title": "desk", "price": None, "available": None},
]
Explanation: Row 1 coerces integer 24 to 24.0 for the "REAL" column price. Row 2 fills omitted columns price and available with None. Opening a new StorageEngine(root) replays the committed log from disk and returns rows in insertion order.
Example 2
# Continuing on the same `root` directory from Example 1:
engine = StorageEngine(root)
updated = engine.update(
"store", "sales", "products",
{"price": 19.5, "available": False},
lambda r: r["sku"] >= 101,
)
deleted = engine.delete("store", "sales", "products", lambda r: r["sku"] == 102)
restarted = StorageEngine(root)
id3 = restarted.insert(
"store", "sales", "products",
{"sku": 103, "title": "chair", "price": 45.0, "available": True},
)
final_rows = restarted.select("store", "sales", "products")
Output:
updated -> 2
deleted -> 1
id3 -> 3
final_rows -> [
{"sku": 101, "title": "lamp", "price": 19.5, "available": False},
{"sku": 103, "title": "chair", "price": 45.0, "available": True},
]
Explanation: update modifies both existing rows in one atomic log append (updated == 2), and delete removes row 2 (sku == 102). After restarting, the next insert receives row ID 3 rather than reusing deleted ID 2. Attempting restarted.insert("store", "sales", "products", {"sku": True}) would raise StorageError without altering final_rows.
Constraints
- Single-writer execution per
rootdirectory; secondary indexes are not required (full scans forselect,update, anddeleteare expected). insert,update, anddeletemust only append todata_file(database, schema, table)during normal operation.- If the process terminates at any byte offset while appending a single-row or multi-row statement (or leaves a truncated/corrupted tail), opening
StorageEngine(root)must expose either the exact table state before that statement or the exact state after it—never a half-applied batch—and must clean up any uncommitted tail so subsequent appends succeed. - Only Python standard library modules may be used.
Step-by-step walkthrough
Pin down the contract and clarifying assumptions
Before writing code, we answer the open design questions from the prompt so every requirement is unambiguous:
- Row filters: Callers pass
whereas eitherNone(match every row) or a Python predicate functionCallable[[Row], bool]that takes a row dictionary and returnsTrueorFalse. This keeps our storage engine completely decoupled from SQL query parsing. - Supported column types:
INT,REAL,TEXT, andBOOL, plusNULL(represented as PythonNone) allowed in every column. - Durability: Once a method returns without error, its changes must survive an immediate process crash or power loss. Every disk write therefore flushes Python's buffer and calls
os.fsyncso the operating system pushes the bytes to storage. - Atomicity: Every create, insert, multi-row update, and multi-row delete is all-or-nothing — a crash mid-way leaves the database cleanly in its state before the call.
- Concurrency and indexes: A single writer per root directory, and full table scans for reads (concurrent writers and secondary indexes are covered in the follow-ups).
Any failure caused by stored state — such as creating a duplicate table, referencing a missing schema, or inserting a string into an
INTcolumn — raisesStorageError.from typing import Any, Callable, Dict, List, Optional, Tuple Row = Dict[str, Any] Where = Optional[Callable[[Row], bool]] class StorageError(Exception): """Raised when an operation fails due to stored state (duplicates, missing objects, bad types)."""- Row filters: Callers pass
Store the namespace in one catalog file with an atomic rename
A catalog is the metadata dictionary that records which databases, schemas, tables, and columns exist, along with where each table's rows live on disk. Because catalog updates (
CREATE DATABASE,CREATE SCHEMA,CREATE TABLE) happen rarely and the metadata is small, we store the entire three-level hierarchy in a single JSON filecatalog.json:root/ catalog.json {"next_file": 2, "databases": { "store": { "sales": { "products": { "columns": [["sku", "INT"], ["title", "TEXT"]], "file": "t1.log" } } } }} t1.log append-only row log for store.sales.productsNotice two important design choices: 1. Numbered data files (
t1.log,t2.log, ...): Naming files with a monotonic counternext_fileinstead of user-chosen table names avoids tricky filename characters, case-insensitive filesystem collisions, or path-traversal bugs. 2. Write-temp-then-rename commit point: If we overwrotecatalog.jsondirectly in place and crashed halfway through, the file would hold half-written JSON and wipe out the entire database. Instead, we write the full JSON tocatalog.json.tmp,fsyncthat file, atomically swap it overcatalog.jsonwithos.replace, andfsyncthe parent directory so the rename itself is durable.def _sync_file(file_obj) -> None: """Flush Python's buffer to the OS and force the OS to write bytes to disk.""" file_obj.flush() os.fsync(file_obj.fileno()) def _sync_dir(dir_path: str) -> None: """Flush a directory entry so an atomic file rename (os.replace) survives power loss.""" try: dir_fd = os.open(dir_path, os.O_RDONLY) except OSError: # Some platforms (such as Windows) do not allow opening a directory descriptor. return try: os.fsync(dir_fd) except OSError: pass finally: os.close(dir_fd)Implement create operations: check, copy, then commit
Every
create_*method follows the exact same three-step discipline so memory and disk never drift apart:- Validate that parent namespaces exist and the new name is not a duplicate (plus valid, unique column definitions for
create_table). - Mutate a deep copy of
self.catalograther than mutatingself.catalogdirectly. If disk I/O fails (for instance, disk full),self.catalogin memory remains untouched and still matchescatalog.jsonon disk. - Create the empty
.logfile before saving the catalog increate_table. Why this order? If we crash after creatingt1.logbut beforeos.replacecommitscatalog.json,t1.logis just a harmless orphan file that the nextcreate_tablecall overwrites (next_fileis still1incatalog.json). The opposite order could commit a table entry pointing to a missing file!
def _save_catalog(self, new_catalog: dict) -> None: """Atomically persist `new_catalog` via write-temp + fsync + os.replace + dir fsync.""" tmp_path = self.catalog_path + ".tmp" with open(tmp_path, "w", encoding="utf-8") as file_obj: json.dump(new_catalog, file_obj) _sync_file(file_obj) # os.replace swaps the directory entry atomically: readers see old or new, never half-written JSON. os.replace(tmp_path, self.catalog_path) _sync_dir(self.root) # Update in-memory catalog only after the atomic rename has succeeded. self.catalog = new_catalog def create_table(self, database: str, schema: str, table: str, columns: List[Tuple[str, str]]) -> None: if table in self._tables(database, schema): raise StorageError(f"table {database}.{schema}.{table} already exists") seen_names = set() for col_name, type_name in columns: if type_name not in TYPES: raise StorageError(f"unknown type {type_name!r}") if col_name in seen_names: raise StorageError(f"duplicate column {col_name!r}") seen_names.add(col_name) new_catalog = copy.deepcopy(self.catalog) file_name = f"t{new_catalog['next_file']}.log" new_catalog["next_file"] += 1 # Create the empty data file BEFORE committing the catalog so a committed table # never points to a missing file; if we crash first, the next create_table truncates it. data_path = os.path.join(self.root, file_name) open(data_path, "wb").close() column_list = [[col_name, type_name] for col_name, type_name in columns] schema_tables = new_catalog["databases"][database][schema] schema_tables[table] = {"columns": column_list, "file": file_name} self._save_catalog(new_catalog)- Validate that parent namespaces exist and the new name is not a duplicate (plus valid, unique column definitions for
Choose a row layout: an append-only log of row versions
How should rows live on disk so updates (even when a string grows longer!) and deletes are fast and crash-safe? Compare the three classic choices:
Layout Update / delete cost Crash safety "Row grew bigger" problem ---------------------------- -------------------------- ------------------------ ------------------------- Rewrite whole table file O(entire table) bytes Temp file + rename None Fixed-size pages in place O(1) page write Needs undo/redo journal Move row + forwarding ptr Append-only log of versions O(changed rows) appended Append + commit marker None (append at end)An append-only log (writing new events strictly at the end of the file, never overwriting earlier bytes) solves both problems cleanly: - Every inserted row receives a permanent integer
row_id(1, 2, 3, ...) that is never reused, even if that row is deleted. - Inserting or updating row7appends{"op": "put", "id": 7, "row": [values...]}. Because we never overwrite row7in place, a longer string simply appends a longer JSON line at the end. - Deleting row7appends a tombstone record{"op": "del", "id": 7}saying row7is gone. - When the table is opened, we replay the log sequentially into an in-memory Python dictionaryself.rows({row_id: [val_0, val_1, ...]}), which preserves insertion order automatically!Make multi-row statements atomic with commit markers
Suppose an
UPDATEmatches 3 rows and crashes after writing only 2putlines. Without a boundary marker, restarting would apply 2 of the 3 updates and violate atomicity.To make every statement all-or-nothing,
_commitappends allput/delrecords for that statement followed by a{"op": "commit"}line, flushes andfsyncs the file, and updatesself.rowsin memory only after disk persistence succeeds. If anOSErroroccurs mid-write (such as a full disk), we immediatelytruncateback tosize_beforeso no partial bytes remain.def _apply(self, record: dict) -> None: """Apply one committed log record ('put' or 'del') to the in-memory table state.""" op = record["op"] row_id = record["id"] if op == "put": # Python dicts preserve original key insertion order when overwriting an existing key. self.rows[row_id] = record["row"] # Advance next_id past every row_id ever committed, even if a later 'del' removes it. if row_id >= self.next_id: self.next_id = row_id + 1 elif op == "del": self.rows.pop(row_id, None) def _commit(self, records: List[dict]) -> None: """Append one statement plus its commit marker to disk, sync, then update memory.""" all_records = records + [{"op": "commit"}] encoded_lines = [] for record in all_records: line_bytes = json.dumps(record).encode("utf-8") + b"\n" encoded_lines.append(line_bytes) payload = b"".join(encoded_lines) size_before = os.path.getsize(self.path) try: with open(self.path, "ab") as file_obj: file_obj.write(payload) _sync_file(file_obj) except OSError: # Roll back any partial bytes (e.g. disk full) before re-raising so the log stays clean. with open(self.path, "r+b") as file_obj: file_obj.truncate(size_before) raise # Update in-memory state only after the disk write and fsync have succeeded. for record in records: self._apply(record)Notice how
self.next_idupdates during"put"even if a later"del"pops that row: because the historical"put"stays in the log,next_idnever hands out a deleted row's ID after a restart.Replay the log on restart and truncate any crashed tail
When
_Tableopens an existing log file,_replayscans line by line while buffering uncommitted records inpending:Byte offset Log line Action during _replay ----------- ------------------------------------------------ ------------------------------------------ 0 .. 46 {"op": "put", "id": 1, "row": [101, "lamp"]}\n buffer in pending 46 .. 65 {"op": "commit"}\n apply pending -> row 1="lamp"; committed_end = 65 65 .. 111 {"op": "put", "id": 2, "row": [102, "desk"]}\n buffer in pending 111 .. 130 {"op": "commit"}\n apply pending -> row 2="desk"; committed_end = 130 130 .. 174 {"op": "put", "id": 1, "row": [101, "rug"]}\n buffer in pending (no commit yet!) 174 .. 191 {"op": "put", "id": 2, "ro missing '\n' (torn write) -> break! Result: rows = {1: [101, "lamp"], 2: [102, "desk"]}, file truncated cleanly at byte 130.Why must we
truncate(committed_end)instead of just ignoring the unfinished tail? If we left bytes130..191in the file, the next statement's append would get glued onto the broken line{"op": "put", "id": 2, "ro{"op": ..., causing the next restart to stop at byte 174 and lose future committed writes!def _replay(self) -> None: """Read committed statements from disk and truncate any crashed tail.""" if not os.path.exists(self.path): open(self.path, "wb").close() # Byte offset immediately after the last valid {"op": "commit"} line. committed_end = 0 # Buffer of put/del records waiting for their matching commit marker. pending: List[dict] = [] offset = 0 with open(self.path, "rb") as file_obj: for line in file_obj: offset += len(line) # A line without a trailing newline was cut off mid-write during a crash. if not line.endswith(b"\n"): break try: record = json.loads(line) except ValueError: # Broken UTF-8 or truncated JSON means the crash happened on this line. break if not isinstance(record, dict) or "op" not in record: # Guard against non-object JSON fragments (such as "123\n") in a corrupted tail. break if record["op"] == "commit": # Only apply buffered row changes once their commit marker is confirmed. for item in pending: self._apply(item) pending = [] committed_end = offset else: pending.append(record) # Truncate any uncommitted tail so future appends do not land after half-written garbage. if os.path.getsize(self.path) > committed_end: with open(self.path, "r+b") as file_obj: file_obj.truncate(committed_end) _sync_file(file_obj)Validate column types and implement CRUD operations
Type checking happens before we write anything to disk so an invalid column name or type leaves the table completely unchanged. Watch out for a classic Python gotcha:
boolis a subclass ofint(isinstance(True, int)evaluates toTrue!), so we must rejectboolvalues explicitly whenever the column type is not"BOOL". Also, for"REAL"columns, we convert integer inputs like3to3.0immediately so in-memory reads match post-restart JSON reads.def _check_value(self, col_name: str, value: Any) -> Any: """Validate one column value against the schema and normalize REAL values to float.""" if col_name not in self.position: raise StorageError(f"unknown column {col_name!r}") if value is None: return None col_index = self.position[col_name] type_name = self.columns[col_index][1] allowed_types = TYPES[type_name] # In Python, bool is a subclass of int (isinstance(True, int) is True), # so we must explicitly reject booleans for INT and REAL columns. if isinstance(value, bool) and type_name != "BOOL": raise StorageError(f"column {col_name!r} is {type_name}, got {value!r}") if not isinstance(value, allowed_types): raise StorageError(f"column {col_name!r} is {type_name}, got {value!r}") # Convert int inputs on REAL columns (e.g. 3 -> 3.0) so reads match before and after restart. if type_name == "REAL": return float(value) return valueWith
_check_value,_matching_ids, and_commitready, all four CRUD operations (insert,select,update,delete) become short and clean: -insert: start with[None] * len(columns), fill validated values by column position, and commit oneputrecord. -select: return fresh dictionaries via_as_dictfor every matching row ID so caller mutations cannot corrupt stored rows. -update: validatechangesonce upfront, build updated value lists for all matching row IDs, and commit allputrecords in one atomic call. -delete: collect onedelrecord per matching row ID and commit them in one atomic call.Complete solution
Putting
_TableandStorageEnginetogether gives the complete crash-safe storage engine:from typing import Any, Callable, Dict, List, Optional, Tuple import copy import json import os Row = Dict[str, Any] Where = Optional[Callable[[Row], bool]] # Column type name -> allowed Python runtime types. # None (SQL NULL) is accepted for every column. TYPES = { "INT": (int,), "REAL": (int, float), "TEXT": (str,), "BOOL": (bool,), } class StorageError(Exception): """Raised when an operation fails due to stored state (duplicates, missing objects, bad types).""" def _sync_file(file_obj) -> None: """Flush Python's buffer to the OS and force the OS to write bytes to disk.""" file_obj.flush() os.fsync(file_obj.fileno()) def _sync_dir(dir_path: str) -> None: """Flush a directory entry so an atomic file rename (os.replace) survives power loss.""" try: dir_fd = os.open(dir_path, os.O_RDONLY) except OSError: # Some platforms (such as Windows) do not allow opening a directory descriptor. return try: os.fsync(dir_fd) except OSError: pass finally: os.close(dir_fd) class _Table: """Stores one table as an append-only JSON-lines log on disk, replayed into memory on open. Each line in the log file is one JSON dict: {"op": "put", "id": 7, "row": [1, "ann", 9.5, true]} # insert or overwrite row 7 {"op": "del", "id": 7} # delete row 7 {"op": "commit"} # marks all preceding pending records durable """ def __init__(self, path: str, columns: List[List[str]]): self.path = path # self.columns: [["id", "INT"], ["name", "TEXT"], ...] in table schema order. self.columns = columns # self.position: {"id": 0, "name": 1, ...} mapping column name -> index in value list. self.position: Dict[str, int] = {} for index, (col_name, _) in enumerate(columns): self.position[col_name] = index # self.rows: {row_id: [val_0, val_1, ...]} holding live rows in insertion order. self.rows: Dict[int, List[Any]] = {} # Monotonic row identifier; starts at 1 and never reuses deleted IDs. self.next_id = 1 # Phase: rebuild in-memory state from the on-disk append-only log. self._replay() def _replay(self) -> None: """Read committed statements from disk and truncate any crashed tail.""" if not os.path.exists(self.path): open(self.path, "wb").close() # Byte offset immediately after the last valid {"op": "commit"} line. committed_end = 0 # Buffer of put/del records waiting for their matching commit marker. pending: List[dict] = [] offset = 0 with open(self.path, "rb") as file_obj: for line in file_obj: offset += len(line) # A line without a trailing newline was cut off mid-write during a crash. if not line.endswith(b"\n"): break try: record = json.loads(line) except ValueError: # Broken UTF-8 or truncated JSON means the crash happened on this line. break if not isinstance(record, dict) or "op" not in record: # Guard against non-object JSON fragments (such as "123\n") in a corrupted tail. break if record["op"] == "commit": # Only apply buffered row changes once their commit marker is confirmed. for item in pending: self._apply(item) pending = [] committed_end = offset else: pending.append(record) # Truncate any uncommitted tail so future appends do not land after half-written garbage. if os.path.getsize(self.path) > committed_end: with open(self.path, "r+b") as file_obj: file_obj.truncate(committed_end) _sync_file(file_obj) def _apply(self, record: dict) -> None: """Apply one committed log record ('put' or 'del') to the in-memory table state.""" op = record["op"] row_id = record["id"] if op == "put": # Python dicts preserve original key insertion order when overwriting an existing key. self.rows[row_id] = record["row"] # Advance next_id past every row_id ever committed, even if a later 'del' removes it. if row_id >= self.next_id: self.next_id = row_id + 1 elif op == "del": self.rows.pop(row_id, None) def _commit(self, records: List[dict]) -> None: """Append one statement plus its commit marker to disk, sync, then update memory.""" all_records = records + [{"op": "commit"}] encoded_lines = [] for record in all_records: line_bytes = json.dumps(record).encode("utf-8") + b"\n" encoded_lines.append(line_bytes) payload = b"".join(encoded_lines) size_before = os.path.getsize(self.path) try: with open(self.path, "ab") as file_obj: file_obj.write(payload) _sync_file(file_obj) except OSError: # Roll back any partial bytes (e.g. disk full) before re-raising so the log stays clean. with open(self.path, "r+b") as file_obj: file_obj.truncate(size_before) raise # Update in-memory state only after the disk write and fsync have succeeded. for record in records: self._apply(record) def _check_value(self, col_name: str, value: Any) -> Any: """Validate one column value against the schema and normalize REAL values to float.""" if col_name not in self.position: raise StorageError(f"unknown column {col_name!r}") if value is None: return None col_index = self.position[col_name] type_name = self.columns[col_index][1] allowed_types = TYPES[type_name] # In Python, bool is a subclass of int (isinstance(True, int) is True), # so we must explicitly reject booleans for INT and REAL columns. if isinstance(value, bool) and type_name != "BOOL": raise StorageError(f"column {col_name!r} is {type_name}, got {value!r}") if not isinstance(value, allowed_types): raise StorageError(f"column {col_name!r} is {type_name}, got {value!r}") # Convert int inputs on REAL columns (e.g. 3 -> 3.0) so reads match before and after restart. if type_name == "REAL": return float(value) return value def _as_dict(self, values: List[Any]) -> Row: """Build a fresh {column_name: value} dict so callers cannot mutate internal lists.""" row_dict: Row = {} for index, (col_name, _) in enumerate(self.columns): row_dict[col_name] = values[index] return row_dict def _matching_ids(self, where: Where) -> List[int]: """Scan rows in insertion order and return the row IDs matching `where`.""" matched_ids: List[int] = [] for row_id, values in self.rows.items(): if where is None or where(self._as_dict(values)): matched_ids.append(row_id) return matched_ids def insert(self, row: Row) -> int: """Validate `row`, fill omitted columns with None, durably append, and return row_id.""" # Start with NULL (None) for every column, then fill provided columns by position. values: List[Any] = [None] * len(self.columns) for col_name, raw_value in row.items(): checked_value = self._check_value(col_name, raw_value) col_index = self.position[col_name] values[col_index] = checked_value row_id = self.next_id self._commit([{"op": "put", "id": row_id, "row": values}]) return row_id def select(self, where: Where) -> List[Row]: """Return copies of all rows matching `where` in original insertion order.""" result: List[Row] = [] for row_id in self._matching_ids(where): result.append(self._as_dict(self.rows[row_id])) return result def update(self, changes: Row, where: Where) -> int: """Validate `changes`, build new row versions for matches, and commit atomically.""" # Validate every changed value upfront so bad input fails before touching any row. checked_changes: Row = {} for col_name, raw_value in changes.items(): checked_changes[col_name] = self._check_value(col_name, raw_value) records: List[dict] = [] for row_id in self._matching_ids(where): new_values = list(self.rows[row_id]) for col_name, checked_value in checked_changes.items(): col_index = self.position[col_name] new_values[col_index] = checked_value records.append({"op": "put", "id": row_id, "row": new_values}) # Skip disk I/O completely if 0 rows matched the filter. if records: self._commit(records) return len(records) def delete(self, where: Where) -> int: """Commit delete tombstones for all matching rows in a single atomic batch.""" records: List[dict] = [] for row_id in self._matching_ids(where): records.append({"op": "del", "id": row_id}) if records: self._commit(records) return len(records) class StorageEngine: """Executes validated DDL and CRUD operations with crash-safe persistence under `root`. On-disk layout: root/catalog.json {"next_file": 2, "databases": {"db": {"sch": {"tbl": {"columns": [...], "file": "t1.log"}}}}} root/t<N>.log one append-only row log per table """ def __init__(self, root: str): self.root = root os.makedirs(root, exist_ok=True) self.catalog_path = os.path.join(root, "catalog.json") # self.catalog holds the 3-level namespace and counter for numbered table log files. self.catalog: dict = {"next_file": 1, "databases": {}} if os.path.exists(self.catalog_path): with open(self.catalog_path, "r", encoding="utf-8") as file_obj: self.catalog = json.load(file_obj) # self.tables caches opened _Table instances keyed by (database, schema, table). self.tables: Dict[Tuple[str, str, str], _Table] = {} def _save_catalog(self, new_catalog: dict) -> None: """Atomically persist `new_catalog` via write-temp + fsync + os.replace + dir fsync.""" tmp_path = self.catalog_path + ".tmp" with open(tmp_path, "w", encoding="utf-8") as file_obj: json.dump(new_catalog, file_obj) _sync_file(file_obj) # os.replace swaps the directory entry atomically: readers see old or new, never half-written JSON. os.replace(tmp_path, self.catalog_path) _sync_dir(self.root) # Update in-memory catalog only after the atomic rename has succeeded. self.catalog = new_catalog def _schemas(self, database: str) -> dict: """Return the schema map for `database`, or raise StorageError if missing.""" databases = self.catalog["databases"] if database not in databases: raise StorageError(f"database {database!r} does not exist") return databases[database] def _tables(self, database: str, schema: str) -> dict: """Return the table map for `database.schema`, or raise StorageError if missing.""" schemas = self._schemas(database) if schema not in schemas: raise StorageError(f"schema {database}.{schema} does not exist") return schemas[schema] def create_database(self, database: str) -> None: if database in self.catalog["databases"]: raise StorageError(f"database {database!r} already exists") new_catalog = copy.deepcopy(self.catalog) new_catalog["databases"][database] = {} self._save_catalog(new_catalog) def create_schema(self, database: str, schema: str) -> None: if schema in self._schemas(database): raise StorageError(f"schema {database}.{schema} already exists") new_catalog = copy.deepcopy(self.catalog) new_catalog["databases"][database][schema] = {} self._save_catalog(new_catalog) def create_table(self, database: str, schema: str, table: str, columns: List[Tuple[str, str]]) -> None: if table in self._tables(database, schema): raise StorageError(f"table {database}.{schema}.{table} already exists") seen_names = set() for col_name, type_name in columns: if type_name not in TYPES: raise StorageError(f"unknown type {type_name!r}") if col_name in seen_names: raise StorageError(f"duplicate column {col_name!r}") seen_names.add(col_name) new_catalog = copy.deepcopy(self.catalog) file_name = f"t{new_catalog['next_file']}.log" new_catalog["next_file"] += 1 # Create the empty data file BEFORE committing the catalog so a committed table # never points to a missing file; if we crash first, the next create_table truncates it. data_path = os.path.join(self.root, file_name) open(data_path, "wb").close() column_list = [[col_name, type_name] for col_name, type_name in columns] schema_tables = new_catalog["databases"][database][schema] schema_tables[table] = {"columns": column_list, "file": file_name} self._save_catalog(new_catalog) def _table(self, database: str, schema: str, table: str) -> _Table: """Look up and lazily open `_Table` for `database.schema.table`.""" key = (database, schema, table) if key not in self.tables: schema_tables = self._tables(database, schema) if table not in schema_tables: raise StorageError(f"table {database}.{schema}.{table} does not exist") entry = schema_tables[table] log_path = os.path.join(self.root, entry["file"]) self.tables[key] = _Table(log_path, entry["columns"]) return self.tables[key] def data_file(self, database: str, schema: str, table: str) -> str: """Path of the table's append-only log.""" return self._table(database, schema, table).path def insert(self, database: str, schema: str, table: str, row: Row) -> int: """Insert one row (missing columns are NULL) and return its row id. Row ids start at 1 and are never reused, also across restarts.""" return self._table(database, schema, table).insert(row) def select(self, database: str, schema: str, table: str, where: Where = None) -> List[Row]: """Rows matching `where` (all rows if None), as dicts, in insertion order.""" return self._table(database, schema, table).select(where) def update(self, database: str, schema: str, table: str, changes: Row, where: Where = None) -> int: """Set `changes` on every matching row as one all-or-nothing statement.""" return self._table(database, schema, table).update(changes, where) def delete(self, database: str, schema: str, table: str, where: Where = None) -> int: """Delete every matching row as one all-or-nothing statement.""" return self._table(database, schema, table).delete(where)✅ Submit now — all tests should pass.
Intuition & how it works
Think of this storage layer like an accountant's ink ledger paired with a replaceable table of contents:
- The table of contents (
catalog.json) lists every database, schema, table, column definition, and numbered log filename (t1.log,t2.log, ...). Whenever we create a database, schema, or table, we write a brand-new copy ofcatalog.jsonto a temporary file (catalog.json.tmp), force its bytes to physical storage withfsync(an operating-system call that flushes cached data to disk), and swap it into place with an atomic rename (os.replace, a filesystem operation that switches a filename from the old file to the new one instantaneously). - Each table's ink ledger (
t<N>.log) is an append-only log — a file where new lines are only ever added at the end and existing bytes are never overwritten. Every row gets a permanent integer ID (1, 2, 3, ...). Inserting or updating a row appends a"put"line with the row's latest values; deleting a row appends a"del"tombstone (a marker recording that a specific ID was deleted); and finishing any statement appends a"commit"marker line.
Why does a naive approach — such as storing each table in a JSON or CSV file and overwriting rows in place — fail? First, if an UPDATE replaces "lamp" with "floor lamp", the new row is longer than the old one and would overwrite neighboring bytes unless you rewrite the entire file on every single change. Second, if the process crashes halfway through overwriting a file or updating 50 rows, the file on disk is left corrupted or half-updated with no way to recover the previous state.
Walk through a tiny concrete trace on table store.sales.products(sku INT, title TEXT):
1. insert({"sku": 101, "title": "lamp"}) appends {"op": "put", "id": 1, "row": [101, "lamp"]} plus {"op": "commit"}. In memory: {1: [101, "lamp"]}.
2. insert({"sku": 102, "title": "desk"}) appends {"op": "put", "id": 2, "row": [102, "desk"]} plus {"op": "commit"}. In memory: {1: [101, "lamp"], 2: [102, "desk"]}.
3. Suppose an update tries to change both titles to "rug", writes {"op": "put", "id": 1, "row": [101, "rug"]}, and crashes mid-line on row 2 before writing {"op": "commit"}.
4. On restart, _replay reads the log from top to bottom, buffers pending records until each "commit" line, stops at the torn write (a line cut off mid-write without a valid newline and JSON body), and truncates the file right after the second "commit". Both rows cleanly remain "lamp" and "desk".
Complexity
Let n be the number of live rows in an opened table, c be the number of columns, k be the number of rows matched by where, and L be the total number of log records ever written to that table's file:
create_database/create_schema/create_table— Time:O(catalog size)plus twofsynccalls. We deep-copy the catalog dictionary, serialize it tocatalog.json.tmp, flush the file, atomically rename it, and flush the directory. Catalog changes are rare and the metadata dictionary is tiny.insert— Time:O(c)plus onefsync. We validate at mostccolumn values inO(1)dictionary lookups each, serialize one JSON line plus a commit marker, append it to the end of the file, and update the in-memory dictionary inO(1).select— Time:O(n * c)(assuming anO(1)predicate). Without secondary indexes, we scan allnlive rows in insertion order and build a freshc-key dictionary per row.update/delete— Time:O(n * c)plus onefsync. Scanning allnlive rows to evaluatewheretakesO(n * c), building and appending theknew versions or tombstones takesO(k * c)(withk <= n), and the entire statement shares a singlefsync.- Opening a table on restart — Time:
O(L * c). Replaying the log reads every historical"put","del", and"commit"line in the file until compaction removes obsolete versions. - Space — Memory:
O(n * c)per opened table plusO(catalog size); Disk:O(L * c). Memory holds only the latest live version of each row inself.rows, whereas the append-only file retains every committed version and tombstone until compacted.
In practice, disk synchronization dominates write latency: an SSD cache flush takes roughly 1–5 ms (Note: on macOS, standard os.fsync only flushes to the drive controller cache in tens of microseconds; true power-loss durability there uses fcntl.fcntl(fd, fcntl.F_FULLFSYNC)), whereas the in-memory Python work takes microseconds. High-throughput engines amortize this by batching concurrent transactions into one fsync (group commit).
Edge cases
- Duplicate or orphan DDL objects: Creating an existing database, schema, or table, or creating inside a non-existent database or schema, raises
StorageErrorwithout touching disk. - Same table name in different schemas or databases: Allowed (
store.sales.productsandarchive.sales.productsmap to distinct numbered filest1.logandt2.log). - Python
boolvsinttrap: Becauseisinstance(True, int)isTruein Python, passingTrueto anINTorREALcolumn must be explicitly rejected. - Integer passed to a
REALcolumn:24is normalized to24.0immediately on write soselectreturnsfloatboth before and after a restart. - Missing columns on
insert: Filled withNone(NULL), while unknown column names ininsertorupdateraiseStorageErrorbefore any bytes are written. - Zero matching rows in
updateordelete: Returns0and skips disk I/O completely (no empty"commit"lines appended). - Crash at any byte of a multi-row statement: Uncommitted records at the tail are ignored and truncated on restart so future writes append cleanly.
- Deleted row IDs across restarts: Deleting row
3(the highest ID), restarting, and inserting a new row assigns ID4, never reusing3, because row3's earlier"put"record still advancesnext_idduring replay.
Common mistakes
- Overwriting
catalog.jsondirectly in place: Openingcatalog.jsonwith"w"truncates it to 0 bytes first; a crash mid-write destroys the entire catalog. Always write a.tmpfile,fsync, andos.replace. - Calling
file.flush()withoutos.fsync():flush()only copies bytes from Python's user-space buffer into the operating system's RAM cache; power loss still loses the write unlessos.fsync()forces it to storage. - Mutating in-memory state before disk I/O succeeds: Updating
self.catalogorself.rowsbeforeos.replace/_sync_fileleaves memory out of sync with disk if anOSErroroccurs. - Skipping a torn tail without truncating it: If you leave half-written bytes at the end of
t1.log, the nextopen(..., "ab")appends right onto the broken line and corrupts the newly committed record too. - Creating a table's
.logfile after committingcatalog.json: A crash between the two steps leaves a committed table whose log file is missing (or worse, if a previous failed attempt left partial data). Creating/truncating the.logfile first makes any pre-commit crash harmless. - Returning internal row dicts or lists directly from
select: A caller doingrows[0]["name"] = "hacked"would silently mutate the table in memory without persisting or type-checking.
Alternative approaches
- Slotted pages + buffer pool + write-ahead log (WAL): Traditional relational engines (such as PostgreSQL and SQLite) divide table files into fixed-size 4 KB or 8 KB slotted pages (blocks with a header array of byte offsets pointing to variable-length rows packed from the end of the page) cached in a fixed-size buffer pool in RAM so tables can far exceed available memory. If an updated row no longer fits on its page, it moves to another page and leaves a forwarding pointer behind so its
(page_id, slot_id)identifier stays stable. Crash safety then requires a write-ahead log (WAL) — a sequential journal recording redo and undo information before any dirty data page is written to disk. - Log-structured file with in-memory offset index (
Bitcaskstyle): Keep the append-only data file on disk, but store only{row_id: (byte_offset, byte_length)}in RAM instead of full row values. Memory drops toO(n)integers, at the cost of a disk read per row duringselect.
Follow-up questions
- Suppose power fails mid-way through a multi-row update statement. What state will the table recover to on startup, and how do you guarantee atomic statement execution? In our design, startup recovers the table to the exact state right before
updatebegan. Every statement writes all of its"put"records first and appends{"op": "commit"}last; during startup,_replayholds records in a temporarypendinglist until it sees a complete"commit"line, discards any uncommitted tail, and truncates the file back tocommitted_end. In a page-based database that modifies pages in place, you achieve the same atomicity with a write-ahead log (replaying committed transactions and rolling back uncommitted ones usingundorecords on restart) or shadow paging. - Read workloads frequently filter by equality or range on a single column. How would you introduce a secondary index and maintain it across updates, deletes, and crash recovery? Add an in-memory index mapping each column value to matching row IDs — a hash map
{value: set_of_row_ids}for equality lookups (col = x) and a sorted structure (like a B-tree) for range scans (col < x). Update the index inside_apply, which is the single code path shared by live writes and startup log replay: before overwriting or deletingrow_id, removerow_idfromold_values[col_idx]'s entry, and on a"put", insertrow_idintonew_values[col_idx]'s entry. Rebuilding the index automatically during_replayguarantees crash recovery without maintaining a separate on-disk index file, thoughwheremust accept structured predicates (such as("sku", "=", 101)) rather than an opaque Python lambda so the engine knows which index to consult. - Repeated updates and deletes cause the append-only table log to grow indefinitely. How can you compact the file and reclaim disk space without risking data loss on a crash? Run log compaction (garbage-collecting obsolete versions and tombstones by writing only live state to a fresh file) once the log size exceeds, say,
2xthe size of live rows. Write a metadata record{"op": "meta", "next_id": self.next_id}(so deleted high row IDs are still never reused!), followed by one"put"per live row inself.rowsand one"commit"tot1.log.compact,fsyncthat file, atomically swap it overt1.logwithos.replace, andfsyncthe directory. A crash beforeos.replaceleaves the originalt1.logcompletely intact; a crash afteros.replaceleaves the complete compacted log. - What anomalies or corruptions happen if two client sessions mutate the same table concurrently, and what is the most straightforward locking design to prevent them? If two
StorageEngineinstances open the same directory concurrently, each holds an independent stale RAM copy ofcatalogandrows: both can assign the samenext_id(silently overwriting one inserted row), overwrite each other's updates (lost updates), interleave bytes insidecatalog.json.tmp(corrupting the catalog), or clobber each other'scatalog.jsonvia racingos.replacecalls. The simplest correct fix is single-writer locking: acquire an exclusive OS file lock (fcntl.flockonroot/engine.lock) whenStorageEngineopens so a second process cannot open the same directory concurrently, and guard every public method on that sharedStorageEngineinstance with athreading.Lockso threads serialize cleanly. If higher concurrency is needed later, evolve to per-table read/write locks and eventually multi-version concurrency control (MVCC), where readers view consistent snapshots without blocking writers.
Follow-up questions
- Suppose power fails mid-way through a multi-row update statement. What state will the table recover to on startup, and how do you guarantee atomic statement execution?
- Read workloads frequently filter by equality or range on a single column. How would you introduce a secondary index and maintain it across updates, deletes, and crash recovery?
- Repeated updates and deletes cause the append-only table log to grow indefinitely. How can you compact the file and reclaim disk space without risking data loss on a crash?
- What anomalies or corruptions happen if two client sessions mutate the same table concurrently, and what is the most straightforward locking design to prevent them?
Similar questions
- Core Mobile Chat Architecture: Delivery Flow, Storage Design, and Scale
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager