AI Coding Interview Practice Beta

Cake Database (Progressive Build)

Build the bakery's in-memory order database in four levels, from set/get to TTLs and backup/restore. The design you pick in level 1 decides how painful level 4 is.

Progressive build · Medium · 75-minute time box · Python 3.10+

Quick start

  1. Download the starter repo and unzip it.
  2. Open the folder in your editor, with any AI assistant you like.
  3. Run the tests from the repo's folder: python3 -m unittest discover -s tests. The tests for the stages you haven't done yet fail.
  4. Set a timer for 75 minutes and work through the stages in order.

Stages

  1. Level 1: set, get and delete fields on order records
  2. Level 2: scan a record sorted by field name, and scan by field-name prefix
  3. Level 3: timestamped operations, with fields that expire after a TTL
  4. Level 4: backup and restore, recalculating remaining TTLs on restore

What it practices

  • designing data structures that survive changing requirements
  • turning a precise spec into tests
  • boundary conditions (half-open time intervals)
  • deep vs. shallow copies
  • keeping earlier levels passing while you extend the code
  • reviewing AI-written code level by level

Similar to

  • CodeSignal Industry Coding Framework (progressive levels)
  • Progressive (multi-level) coding screens

The scenario

The bakery wants a small in-memory database for its order records. Each record has a key (an order id like order-1042) and any number of fields, each a field name mapped to a string value: flavour -> chocolate, status -> proofing, and so on.

This is a progressive build: one task, revealed in four levels, where each level adds to the last. It's the format of CodeSignal's Industry Coding Framework and similar leveled coding screens. The catch is that the design you pick for level 1 decides how painful levels 3 and 4 are, and every later level has to keep the earlier levels' tests passing.

The starter repo gives you the public interface: an OrderDatabase class in cakedb/database.py whose methods all raise NotImplementedError, with docstrings that specify the behavior exactly. There's also a working command-line driver (cakedb/cli.py) that replays a file of queries, a format_field helper, and one test file per level. Run the tests from the repo root:

python3 -m unittest discover -s tests

In a real progressive round you only see the next level once the current one passes. Here all four are listed, but do them in order, and for the most realistic practice, don't read a level's docstrings until you've finished the one before it.

What to build

  1. Level 1: records (tests/test_stage1.py). set(key, field, value), get(key, field) and delete(key, field).

    • get returns None for a missing record or field, and never raises.
    • set creates the record if needed and overwrites an existing field.
    • delete returns True only if it removed a field. Removing a record's last field removes the record.
  2. Level 2: scans (tests/test_stage2.py). scan(key) and scan_by_prefix(key, prefix).

    • Both return "field(value)" strings sorted by field name, using Python's default string ordering.
    • The prefix is matched against field names, never values. It's case-sensitive and a true prefix (not a substring), and an empty prefix matches everything.
    • A missing record scans as an empty list.
  3. Level 3: timestamps and TTLs (tests/test_stage3.py). set_at, set_at_with_ttl, get_at, delete_at, scan_at and scan_by_prefix_at, each taking the current timestamp.

    • A field written at time T with TTL N is live for T <= t < T + N. At exactly T + N it's gone.
    • Expired fields are invisible: get_at returns None, scans leave them out, and delete_at returns False.
    • Writing a field again replaces its expiry (set_at clears any TTL). A TTL of zero or less raises ValueError and changes nothing.
    • Levels 1 and 2 still pass.
  4. Level 4: backup and restore (tests/test_stage4.py). backup(timestamp) and restore(timestamp, timestamp_to_restore).

    • backup saves a snapshot and returns the number of records with at least one live field.
    • Nothing you do afterwards, including restoring, may change a saved snapshot.
    • restore uses the latest backup taken at or before timestamp_to_restore (a backup at exactly that time counts) and replaces the whole database with it. If there's no such backup it raises NoBackupError.
    • TTLs are recalculated relative to the restore: a field that had r units left at backup time now expires at timestamp + r.

You're done when python3 -m unittest discover -s tests passes all 93 tests. Then replay a day at the bakery with python3 -m cakedb.cli examples/demo_queries.txt. Time box: 75 minutes. Level 1 should take minutes; level 4 is the stretch.

How to work with an AI assistant on a progressive build

A progressive build rewards a steady loop: understand one level, pin it down with tests, implement it in a small diff, run the whole suite, then move on. AI assistants are great at the implementation step and risky at the others, because they like to rewrite everything at once. Here's how to keep control.

1. Read before you prompt (5 minutes)

  • README.md for the levels and the rules.
  • The module docstring and the Level 1 docstrings in cakedb/database.py. These are the spec. The rule "a record with no fields is the same as a record that doesn't exist" matters later.
  • tests/test_existing.py and cakedb/cli.py, to see how the methods are called. Notice that format_field already exists; use it instead of hand-building "field(value)" strings.

2. Give the AI the interface and the current level's spec, not a vague goal

Point the assistant at cakedb/database.py (or paste the class skeleton and the current level's docstrings), and say which level you're on. A good first prompt:

I'm doing a progressive build in cakedb/database.py. We're on Level 1 only:
set, get and delete. Read the module docstring and those three docstrings.
Before writing code, propose a storage layout in two or three sentences,
keeping in mind that later levels will probably attach more data to each
field. Don't implement anything yet.

You can't see later levels in a real round, but you can ask for a design that's easy to extend: one dict per record, and every read going through one or two helper methods instead of being repeated in each public method.

3. Ask for tests (or a test map) first

The level tests already exist, but you'll learn more by making the AI restate the spec as cases before it writes code. For example, at level 3:

For Level 3, list the boundary cases as a table: write time, ttl, read
time, expected result. Include reading at the write time, at
write time + ttl - 1 and at exactly write time + ttl. Then tell me which
test in tests/test_stage3.py covers each row, and which rows no test covers.

If a row is uncovered and you think it matters, add your own test in a separate file. Don't edit the provided tests.

4. Keep each level's code reviewable

  • One level per prompt, and one diff per level. Read the diff before you run anything.
  • Run git init and commit after each level passes, so you can git diff the next level's changes against working code.
  • Ask for shared helpers (one place that decides whether a field is live, one place that builds a scan) rather than six copies of the same loop.
  • Run the whole suite, not just the current level's file. A level 3 refactor that breaks level 1 is the classic progressive-round failure.

5. Don't let it rewrite earlier levels

At level 3 you'll probably change how fields are stored. That's a refactor of levels 1 and 2, and it's where assistants overreach: renaming methods, changing signatures, "simplifying" behavior the docstrings pin down, or even editing tests to make them pass. Be explicit:

Level 3. You may change the internal storage, but set/get/delete/scan/
scan_by_prefix must keep exactly their current behavior and signatures.
Don't edit anything in tests/. After the change, run the full suite and
show me the output.

6. What to verify yourself

  • Every comparison against an expiry time. < vs. <= is the whole of level 3's boundary rule.
  • Every place a backup is created or restored. Ask yourself, "Could a write after this line change the backup?" Check both directions: backup to live data and live data to backup.
  • The restore docstring example, by hand. Write at 10 with TTL 20, back up at 15, restore at 100: the field should expire at 115, not at 30 or 120.

A rough time plan: level 1 in 5-10 minutes, level 2 in about 10, level 3 in 20-25, and level 4 with whatever's left.

Self-check rubric

Progressive rounds are usually scored mostly on how many levels pass, but when a human is watching (or reading your transcript), this is what they look for.

Area Strong signal Weak signal
Understanding the codebase and spec Reads the docstrings and test_existing.py first; spots the "empty record doesn't exist" rule and the half-open TTL interval before coding; reuses format_field. Pastes "build a key-value store with TTL" into the AI and starts from whatever comes back; re-implements helpers that already exist.
Design for change Stores per-field data in one place, so level 3 is "add an expiry to each field and filter on read"; all reads go through one or two helpers. Six methods each walk the dicts their own way, so TTL logic has to be pasted into all of them, and one gets missed.
Correctness Gets the boundaries right (expired at exactly T + N; a backup at exactly timestamp_to_restore counts); deep-copies in both directions; recalculates the remaining TTL on restore. Passes the happy-path tests by luck; off-by-one at the TTL boundary; backups that change when the live data does.
Tests Runs the full suite after every change; maps docstring sentences to tests; adds a test for any case they think is uncovered. Only runs the current level's file and finds out at the end that level 1 broke; edits a provided test to make it pass.
Code quality Small, readable diffs per level; type hints kept; a tiny entry class instead of parallel dicts; no dead code from abandoned attempts. A 200-line AI rewrite at each level; if timestamp is None branches scattered everywhere; leftover debug prints.
Use of AI Gives the AI the interface and one level's spec; asks for cases before code; reads and questions every diff ("why <= here?"); rejects unrequested rewrites. Accepts whole-file rewrites without reading them; lets the AI change signatures or tests; can't explain a line it accepted.
Communication Says the plan for each level out loud, names the trade-off (filter on read vs. purging expired fields), and states what they verified. Silent prompting; "the AI says it's done"; can't say which levels pass.

Walkthrough

Show the walkthrough (spoilers)

The design that makes every level easy

Use a dict of dicts (a hash map of hash maps): record key, then field name, then a tiny immutable entry. At level 1 the entry could just be the string value, but the important habit is routing every read through one helper. Then level 3 is "give each entry an expiry and filter in that helper," and level 4 is "copy the live entries."

Level 1: records

def __init__(self) -> None:
    self._records: dict[str, dict[str, str]] = {}

def set(self, key: str, field: str, value: str) -> None:
    self._records.setdefault(key, {})[field] = value

def get(self, key: str, field: str) -> str | None:
    return self._records.get(key, {}).get(field)

def delete(self, key: str, field: str) -> bool:
    record = self._records.get(key)
    if record is None or field not in record:
        return False
    del record[field]
    if not record:
        del self._records[key]  # a record with no fields doesn't exist
    return True

Pitfalls.

  • self._records[key][field] raises KeyError for a missing record. The spec says to return None.
  • Returning "" instead of None for a missing field.
  • Leaving empty records behind is harmless now, but at level 4 a backup that returns len(self._records) would count them.

Weak prompt: "Implement the database."

Strong prompt: "Implement only Level 1 (set, get, delete) in cakedb/database.py as a dict of dicts. Follow the docstrings exactly: get returns None for a missing key or field, and delete returns True only if it removed something and drops a record when its last field goes. Don't touch the other methods."

Level 2: scans

One helper serves both scans. Sort the field names, filter on the name with startswith, and build each item with format_field. scan(key) is just _scan(key, ""), since every string starts with the empty string.

def _scan(self, key: str, prefix: str) -> list[str]:
    record = self._records.get(key, {})
    return [
        format_field(field, record[field])
        for field in sorted(record)
        if field.startswith(prefix)
    ]

Pitfalls.

  • Forgetting to sort. Python dicts keep insertion order, so a quick manual test that happens to insert fields alphabetically looks right.
  • Matching the prefix against values. An AI that reads "scan by prefix" without the docstring often filters on value.startswith(prefix).
  • prefix in field (substring) instead of field.startswith(prefix).
  • "Helpful" sorting (case-insensitive, or natural order so tier2 comes before tier10). The spec says default string ordering.

Weak prompt: "Add scan and prefix search."

Strong prompt: "Level 2: implement scan and scan_by_prefix through one private helper. Sort by field name with plain sorted(), match the prefix against field names only (not values) with startswith, and format items with format_field. Show me the diff; don't change Level 1."

Level 3: timestamps and TTLs

Store an absolute expiry time per field and filter on read. A field is live while now < expires_at: a half-open interval, so at exactly timestamp + ttl it's gone. Fields without a TTL get expires_at = None. The level 1 and 2 methods call the same helpers with now=None, which means "no clock, everything is live," so their behavior doesn't change.

@dataclass(frozen=True)
class _Entry:
    value: str
    expires_at: int | None = None  # None: never expires

    def is_live(self, now: int | None) -> bool:
        return self.expires_at is None or now is None or now < self.expires_at

def set_at(self, key, field, value, timestamp):
    self._write(key, field, _Entry(value))  # a fresh entry clears any old TTL

def set_at_with_ttl(self, key, field, value, timestamp, ttl):
    if ttl <= 0:
        raise ValueError(f"ttl must be a positive integer, got {ttl}")
    self._write(key, field, _Entry(value, expires_at=timestamp + ttl))

def get_at(self, key, field, timestamp):
    return self._read(key, field, now=timestamp)

def get(self, key, field):
    return self._read(key, field, now=None)

_read, _delete and _scan each check entry.is_live(now), and that's the only place expiry is decided. delete_at on an expired field returns False. You don't need a background sweep or a heap of expiry times: filtering on read is simple and correct, and the tests never need memory to be reclaimed.

Pitfalls.

  • now <= expires_at (inclusive) keeps the field alive one tick too long. This is the most common bug, and the tests check reads at both T + N - 1 and T + N.
  • expires_at = ttl counts the TTL from time 0 instead of from the write.
  • Updating only the value on set_at keeps the old TTL. Writing a field replaces its expiry too.
  • Validating ttl after creating the record, or not at all.
  • The refactor breaking level 1 or 2. Run the whole suite.

Weak prompt: "Add TTL support."

Strong prompt: "Level 3. Change the storage so each field holds its value and an optional absolute expiry (timestamp + ttl). A field is live while now < expires_at. Route the level 1-2 methods and the new _at methods through the same helpers, passing now=None for the methods without a timestamp. Raise ValueError for ttl <= 0 before writing anything. Keep every signature and every level 1-2 behavior the same, then run the full suite."

Level 4: backup and restore

A backup saves, for every field live at backup time, its value and its remaining TTL (expires_at - timestamp), not its absolute expiry. Restoring rebuilds fresh dicts with expires_at = restore_timestamp + remaining. Because the entries are immutable and every dict is new, that rebuild is the deep copy, in both directions. (If your entries are mutable, use copy.deepcopy on backup and on restore.) Backups are appended in time order, so the latest one at or before timestamp_to_restore is a binary search away.

def backup(self, timestamp: int) -> int:
    saved = {}
    for key in self._records:
        live = self._live_fields(key, timestamp)
        if live:
            saved[key] = {
                field: _SavedField(entry.value, _ttl_left(entry, timestamp))
                for field, entry in live.items()
            }
    self._backups.append(_Backup(timestamp, saved))
    return len(saved)  # records with at least one live field

def restore(self, timestamp: int, timestamp_to_restore: int) -> None:
    backup = self._latest_backup_at_or_before(timestamp_to_restore)
    self._records = {
        key: {
            field: _Entry(
                saved.value,
                None if saved.ttl_left is None else timestamp + saved.ttl_left,
            )
            for field, saved in fields.items()
        }
        for key, fields in backup.records.items()
    }

def _latest_backup_at_or_before(self, timestamp: int) -> _Backup:
    index = bisect_right(self._backups, timestamp, key=lambda b: b.taken_at)
    if index == 0:
        raise NoBackupError(f"no backup at or before {timestamp}")
    return self._backups[index - 1]

Pitfalls.

  • self._backups.append(self._records) stores a reference, so every later write changes the "backup."
  • dict(self._records) or copy.copy is a shallow copy. The outer dict is new, but each record's field dict is shared, so changing a field in an existing record leaks into the backup.
  • Handing the backup's own dicts to the live database on restore. The next write changes the backup, and restoring it a second time gives a different result.
  • Restoring absolute expiry times. A field that expired at 30 would be dead immediately after a restore at 100, but it had 15 units left at backup time, so it should live until 115.
  • Measuring the remaining TTL from timestamp_to_restore instead of the backup's own timestamp. They differ whenever you ask for a time between backups.
  • < instead of <= when choosing the backup, or picking the earliest backup instead of the latest.
  • Counting every stored record (including empty or fully expired ones) instead of records with a live field.

Weak prompt: "Add backup and restore."

Strong prompt: "Level 4. backup(t) saves, for each field live at t, its value and its remaining TTL (expires_at - t), and returns the number of records with at least one live field. restore(t, t_req) picks the latest backup taken at or before t_req, or raises NoBackupError, and rebuilds the records with expires_at = t + remaining. No dict may be shared between the live data and any backup, in either direction. After coding, trace the restore docstring example and tell me the expiry you get."

What a strong finish looks like

All 93 tests pass, the demo in examples/demo_queries.txt runs cleanly, and you can explain three decisions without looking at the AI chat: why expiry is stored per field and checked on read, why the boundary is <, and why a backup stores the remaining TTL and shares no dicts with the live data.

Files in the starter repo

Here's everything in the starter repo, so you can look around before you download it. Click a file to open it.

README.md 69 lines
# Cake Database: a progressive build

The bakery wants a tiny in-memory database for its order records. Each record
has a key (an order id like `order-1042`) and any number of fields, such as
`flavour -> chocolate` or `status -> proofing`. You'll build it in four levels,
and each level builds on the last, so the design you pick in level 1 decides
how painful levels 3 and 4 are.

## Run the tests

Python 3.10 or newer, standard library only. From this folder (the repo root):

    python3 -m unittest discover -s tests

To run one level at a time:

    python3 -m unittest discover -s tests -p test_stage1.py

`tests/test_existing.py` passes already. Every `tests/test_stageN.py` fails
until you finish that level. The whole suite runs every time, so finishing a
later level must not break an earlier one.

Once you're done, replay a day at the bakery through the command-line driver:

    python3 -m cakedb.cli examples/demo_queries.txt

## The levels

Do them in order. The exact behaviour is in the docstrings in
`cakedb/database.py`; read the whole docstring for a level before you start it.

1. **Level 1: records.** `set`, `get` (None when missing) and `delete`
   (True if something was removed).
2. **Level 2: scans.** `scan(key)` returns `"field(value)"` strings sorted by
   field name; `scan_by_prefix(key, prefix)` keeps only fields whose name
   starts with the prefix.
3. **Level 3: timestamps and TTLs.** Timestamped versions of every operation
   (`set_at`, `set_at_with_ttl`, `get_at`, `delete_at`, `scan_at`,
   `scan_by_prefix_at`). A field written at time T with TTL N is live for
   T <= t < T + N, and invisible from T + N on.
4. **Level 4: backup and restore.** `backup(timestamp)` saves a snapshot and
   returns the number of non-empty records. `restore(timestamp,
   timestamp_to_restore)` restores the latest backup at or before
   `timestamp_to_restore`, with TTLs recalculated relative to the restore.

## Files

- `cakedb/database.py`: the `OrderDatabase` class. All your work goes here.
- `cakedb/cli.py`: replays a file of queries (one per line) against a fresh
  database. Already works; you shouldn't need to change it.
- `cakedb/formatting.py`: `format_field`, which builds the `"field(value)"`
  strings, and how the CLI prints results.
- `cakedb/errors.py`: `NoBackupError` and friends.
- `tests/`: one test file per level, plus `test_existing.py`.

## Time box

75 minutes. Level 1 should take minutes; level 4 is the stretch. Progressive
rounds are usually scored by how far you get with passing tests, so a clean,
working level 3 beats a half-finished level 4.

## Rules

Use any editor and any AI assistant you like. In a real AI-allowed interview
you'd be expected to explain and verify everything the AI writes, so practice
that too.

Don't change the method names or parameters in `cakedb/database.py`, and
don't edit the tests.
cakedb/__init__.py 20 lines
"""cakedb: the bakery's in-memory database of order records.

Import the database from here::

    from cakedb import OrderDatabase

The command-line driver lives in ``cakedb.cli``.
"""

from cakedb.database import OrderDatabase
from cakedb.errors import CakeDbError, CommandError, NoBackupError
from cakedb.formatting import format_field

__all__ = [
    "CakeDbError",
    "CommandError",
    "NoBackupError",
    "OrderDatabase",
    "format_field",
]
cakedb/cli.py 146 lines
"""Replay a file of queries against a fresh OrderDatabase and print the results.

Each non-blank line is one query: a command followed by its arguments,
separated by whitespace. Lines starting with ``#`` are comments::

    SET order-1 flavour chocolate
    GET order-1 flavour
    SET_AT_WITH_TTL order-1 status proofing 100 30
    SCAN_AT order-1 120
    BACKUP 125
    RESTORE 200 125

Every query prints one line: the query, then the method's return value as
rendered by ``cakedb.formatting.render_result`` (or ``error: ...`` if the
query failed).
(Because arguments are split on whitespace, values can't contain spaces
here; use ``SCAN`` rather than ``SCAN_BY_PREFIX`` with an empty prefix.)

Usage, from the repo root::

    python3 -m cakedb.cli examples/demo_queries.txt
    python3 -m cakedb.cli < my_queries.txt
"""

from __future__ import annotations

import sys
from collections.abc import Iterable, Iterator
from dataclasses import dataclass

from cakedb.database import OrderDatabase
from cakedb.errors import CakeDbError, CommandError
from cakedb.formatting import render_result

# Parameters that are converted to int before the method is called.
INT_PARAMS = frozenset({"timestamp", "ttl", "timestamp_to_restore"})


@dataclass(frozen=True)
class Command:
    """One CLI command: the database method it calls and that method's parameters."""

    method: str
    params: tuple[str, ...]

    def usage(self, name: str) -> str:
        return " ".join([name, *(p.upper() for p in self.params)])


COMMANDS: dict[str, Command] = {
    # Level 1
    "SET": Command("set", ("key", "field", "value")),
    "GET": Command("get", ("key", "field")),
    "DELETE": Command("delete", ("key", "field")),
    # Level 2
    "SCAN": Command("scan", ("key",)),
    "SCAN_BY_PREFIX": Command("scan_by_prefix", ("key", "prefix")),
    # Level 3
    "SET_AT": Command("set_at", ("key", "field", "value", "timestamp")),
    "SET_AT_WITH_TTL": Command(
        "set_at_with_ttl", ("key", "field", "value", "timestamp", "ttl")
    ),
    "GET_AT": Command("get_at", ("key", "field", "timestamp")),
    "DELETE_AT": Command("delete_at", ("key", "field", "timestamp")),
    "SCAN_AT": Command("scan_at", ("key", "timestamp")),
    "SCAN_BY_PREFIX_AT": Command("scan_by_prefix_at", ("key", "prefix", "timestamp")),
    # Level 4
    "BACKUP": Command("backup", ("timestamp",)),
    "RESTORE": Command("restore", ("timestamp", "timestamp_to_restore")),
}


def parse_query(line: str) -> tuple[Command, list[str | int]]:
    """Split a query line into its command and converted arguments.

    Raises CommandError for an unknown command, the wrong number of
    arguments, or a non-integer where an integer is expected.
    """
    name, *raw_args = line.split()
    command = COMMANDS.get(name.upper())
    if command is None:
        raise CommandError(f"unknown command {name!r}")
    if len(raw_args) != len(command.params):
        raise CommandError(f"usage: {command.usage(name.upper())}")

    args: list[str | int] = []
    for param, raw in zip(command.params, raw_args):
        if param in INT_PARAMS:
            try:
                args.append(int(raw))
            except ValueError:
                raise CommandError(f"{param} must be an integer, got {raw!r}") from None
        else:
            args.append(raw)
    return command, args


def run_query(db: OrderDatabase, line: str) -> str:
    """Run one query line against ``db`` and return its line of output."""
    try:
        command, args = parse_query(line)
        result = getattr(db, command.method)(*args)
    except NotImplementedError as exc:
        return f"error: not implemented yet ({exc})"
    except (CakeDbError, ValueError) as exc:
        # Errors the docstrings promise (bad TTL, no backup, bad query line).
        # Anything else is a bug and should crash loudly.
        return f"error: {exc}"
    return render_result(result)


def iter_queries(lines: Iterable[str]) -> Iterator[str]:
    """Yield the query lines, stripped, skipping blank lines and ``#`` comments."""
    for line in lines:
        stripped = line.strip()
        if stripped and not stripped.startswith("#"):
            yield stripped


def run_queries(db: OrderDatabase, lines: Iterable[str]) -> list[str]:
    """Run every query in ``lines`` against ``db``; one output per query."""
    return [run_query(db, query) for query in iter_queries(lines)]


def main(argv: list[str] | None = None) -> int:
    args = sys.argv[1:] if argv is None else argv
    if len(args) > 1:
        print("usage: python3 -m cakedb.cli [QUERY_FILE]", file=sys.stderr)
        return 2

    if args:
        with open(args[0], encoding="utf-8") as query_file:
            lines = query_file.readlines()
    else:
        lines = sys.stdin.readlines()

    db = OrderDatabase()
    queries = list(iter_queries(lines))
    width = max((len(query) for query in queries), default=0)
    for query in queries:
        print(f"{query:<{width}}  => {run_query(db, query)}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
cakedb/database.py 225 lines
"""An in-memory database for the bakery's order records.

Each record is identified by a key (an order id such as ``"order-1042"``)
and holds any number of fields. A field maps a field name to a string value::

    order-1042:  flavour -> "chocolate", tiers -> "3", status -> "baking"

The work comes in four levels. Do them in order; the whole test suite runs
every time, so a later level must not break an earlier one.

    Level 1  set, get, delete                        tests/test_stage1.py
    Level 2  scan, scan_by_prefix                    tests/test_stage2.py
    Level 3  the *_at methods: timestamps and TTLs   tests/test_stage3.py
    Level 4  backup, restore                         tests/test_stage4.py

Rules that hold at every level:

* Keys, field names and values are non-empty strings. All matching is exact
  and case-sensitive.
* A record with no fields is the same as a record that doesn't exist.
* Timestamps and TTLs are integers (think "seconds since the shop opened").
  Calls happen in time order: the ``timestamp`` argument never decreases
  from one call to the next on the same database.
"""

from __future__ import annotations


class OrderDatabase:
    """The bakery's order records, kept in memory.

    Every method below is a stub. Replace the ``raise NotImplementedError``
    lines level by level; don't change the method names or parameters (the
    tests and ``cakedb.cli`` call them by name).
    """

    def __init__(self) -> None:
        # TODO (level 1): set up your storage here.
        pass

    # ------------------------------------------------------------------
    # Level 1: basic records
    # ------------------------------------------------------------------

    def set(self, key: str, field: str, value: str) -> None:
        """Set ``field`` of record ``key`` to ``value``.

        Creates the record if it doesn't exist yet. If the field already
        exists, its value is replaced.

        >>> db = OrderDatabase()
        >>> db.set("order-1", "flavour", "lemon")
        >>> db.set("order-1", "flavour", "chocolate")
        >>> db.get("order-1", "flavour")
        'chocolate'
        """
        raise NotImplementedError("Level 1: set")

    def get(self, key: str, field: str) -> str | None:
        """Return the value of ``field`` in record ``key``.

        Returns None if the record doesn't exist or doesn't have that field.
        Never raises for a missing key or field.
        """
        raise NotImplementedError("Level 1: get")

    def delete(self, key: str, field: str) -> bool:
        """Remove ``field`` from record ``key``.

        Returns True if the field existed and was removed. Returns False,
        and changes nothing, if the record or the field doesn't exist.

        Removing a record's last field removes the record: a record with no
        fields is the same as a record that doesn't exist.
        """
        raise NotImplementedError("Level 1: delete")

    # ------------------------------------------------------------------
    # Level 2: scanning a record
    # ------------------------------------------------------------------

    def scan(self, key: str) -> list[str]:
        """Return every field of record ``key`` as ``"field(value)"`` strings.

        The list is sorted by field name in ascending order, using Python's
        default string ordering (so ``"Zest"`` sorts before ``"apple"``, and
        ``"tier10"`` before ``"tier2"``). Returns an empty list if the record
        doesn't exist.

        >>> db = OrderDatabase()
        >>> db.set("order-1", "tiers", "3")
        >>> db.set("order-1", "flavour", "lemon")
        >>> db.scan("order-1")
        ['flavour(lemon)', 'tiers(3)']
        """
        raise NotImplementedError("Level 2: scan")

    def scan_by_prefix(self, key: str, prefix: str) -> list[str]:
        """Like ``scan``, but only the fields whose *name* starts with ``prefix``.

        The prefix is matched against field names, never against values,
        and is case-sensitive. An empty prefix matches every field. Same
        format and order as ``scan``; an empty list if nothing matches.

        >>> db = OrderDatabase()
        >>> db.set("order-1", "filling", "fudge")
        >>> db.set("order-1", "flavour", "lemon")
        >>> db.set("order-1", "topper", "fondant rose")
        >>> db.scan_by_prefix("order-1", "f")
        ['filling(fudge)', 'flavour(lemon)']
        """
        raise NotImplementedError("Level 2: scan_by_prefix")

    # ------------------------------------------------------------------
    # Level 3: timestamps and time-to-live (TTL)
    #
    # Every level 3 method takes the current time as ``timestamp``.
    #
    # A field written with a TTL is *live* from the timestamp it was written
    # at up to, but NOT including, ``timestamp + ttl``. At exactly
    # ``timestamp + ttl`` it has expired. An expired field behaves exactly as
    # if it had been deleted: get_at returns None for it, scans leave it out,
    # delete_at returns False for it, and a record whose fields have all
    # expired counts as a record that doesn't exist.
    #
    # A field written without a TTL never expires. Writing a field again
    # replaces both its value and its expiry: set_at clears any TTL, and
    # set_at_with_ttl starts a new one.
    #
    # The level 1 and 2 methods have no clock. They must keep passing their
    # own tests, which only use fields written without a TTL; the tests never
    # mix them with the timestamped methods (levels 3 and 4) on one database.
    # ------------------------------------------------------------------

    def set_at(self, key: str, field: str, value: str, timestamp: int) -> None:
        """Like ``set``, at time ``timestamp``. The field never expires."""
        raise NotImplementedError("Level 3: set_at")

    def set_at_with_ttl(
        self, key: str, field: str, value: str, timestamp: int, ttl: int
    ) -> None:
        """Like ``set_at``, but the field expires ``ttl`` units after ``timestamp``.

        The field is live at time ``t`` when
        ``timestamp <= t < timestamp + ttl``.

        ``ttl`` must be a positive integer. If it isn't, raises ValueError
        and changes nothing.

        >>> db = OrderDatabase()
        >>> db.set_at_with_ttl("order-7", "status", "proofing", 100, 30)
        >>> db.get_at("order-7", "status", 129)
        'proofing'
        >>> db.get_at("order-7", "status", 130) is None
        True
        """
        raise NotImplementedError("Level 3: set_at_with_ttl")

    def get_at(self, key: str, field: str, timestamp: int) -> str | None:
        """Like ``get``, at time ``timestamp``. None if the field has expired."""
        raise NotImplementedError("Level 3: get_at")

    def delete_at(self, key: str, field: str, timestamp: int) -> bool:
        """Like ``delete``, at time ``timestamp``.

        Returns False, and changes nothing visible, if the field has expired.
        """
        raise NotImplementedError("Level 3: delete_at")

    def scan_at(self, key: str, timestamp: int) -> list[str]:
        """Like ``scan``, at time ``timestamp``. Expired fields are left out."""
        raise NotImplementedError("Level 3: scan_at")

    def scan_by_prefix_at(self, key: str, prefix: str, timestamp: int) -> list[str]:
        """Like ``scan_by_prefix``, at time ``timestamp``. Expired fields are left out."""
        raise NotImplementedError("Level 3: scan_by_prefix_at")

    # ------------------------------------------------------------------
    # Level 4: backup and restore
    # ------------------------------------------------------------------

    def backup(self, timestamp: int) -> int:
        """Save a snapshot of the database as it is at ``timestamp``.

        The snapshot holds every field that is live at ``timestamp``: its
        value and, for a field with a TTL, its *remaining* TTL (its expiry
        time minus ``timestamp``). Fields that have expired are not saved.

        Later changes to the database must not change a saved snapshot, and
        neither must restoring it: the same backup can be restored any number
        of times and gives the same result each time.

        Returns the number of non-empty records at ``timestamp``, that is,
        records with at least one live field.
        """
        raise NotImplementedError("Level 4: backup")

    def restore(self, timestamp: int, timestamp_to_restore: int) -> None:
        """Replace the whole database with a saved snapshot, at time ``timestamp``.

        Uses the latest backup taken at or before ``timestamp_to_restore``
        (a backup taken exactly at ``timestamp_to_restore`` counts). Everything
        currently in the database is replaced, so records and fields written
        after that backup are gone.

        TTLs are recalculated relative to the restore: a field that had ``r``
        units left when the backup was taken now expires at ``timestamp + r``.
        Fields without a TTL still never expire. Restoring doesn't remove any
        backup.

        ``timestamp_to_restore`` is always <= ``timestamp``. Raises
        NoBackupError if no backup was taken at or before
        ``timestamp_to_restore``; the database is unchanged in that case.

        >>> db = OrderDatabase()
        >>> db.set_at_with_ttl("order-7", "status", "proofing", 10, 20)
        >>> db.backup(15)  # "status" has 30 - 15 = 15 units left
        1
        >>> db.restore(100, 15)  # so now it expires at 100 + 15 = 115
        >>> db.get_at("order-7", "status", 114)
        'proofing'
        >>> db.get_at("order-7", "status", 115) is None
        True
        """
        raise NotImplementedError("Level 4: restore")
cakedb/errors.py 20 lines
"""Exceptions raised by cakedb."""


class CakeDbError(Exception):
    """Base class for every error cakedb raises on purpose."""


class NoBackupError(CakeDbError, LookupError):
    """``restore`` was asked for a backup that doesn't exist.

    Raised when no backup was taken at or before the requested time.
    """


class CommandError(CakeDbError, ValueError):
    """A line in a query file couldn't be understood by the CLI.

    For example: an unknown command, the wrong number of arguments, or a
    timestamp that isn't an integer.
    """
cakedb/formatting.py 37 lines
"""How cakedb turns fields and results into text."""

from __future__ import annotations

from collections.abc import Sequence


def format_field(field: str, value: str) -> str:
    """Format one field the way scans return it.

    >>> format_field("flavour", "chocolate")
    'flavour(chocolate)'
    """
    return f"{field}({value})"


def render_result(result: object) -> str:
    """Render a database method's return value as one line of CLI output.

    * ``None`` (what the setters and ``restore`` return, and what ``get``
      returns for a missing field) becomes an empty string.
    * Booleans become ``"true"`` or ``"false"``.
    * A list of scan items is joined with ``", "``.
    * Anything else (strings, counts) goes through ``str()``.

    >>> render_result(["flavour(lemon)", "tiers(3)"])
    'flavour(lemon), tiers(3)'
    >>> render_result(True)
    'true'
    """
    if result is None:
        return ""
    if isinstance(result, bool):
        return "true" if result else "false"
    if isinstance(result, Sequence) and not isinstance(result, str):
        return ", ".join(str(item) for item in result)
    return str(result)
examples/demo_queries.txt 33 lines
# A day at the bakery, one query per line.
# Run it from the repo root once you've finished the levels:
#     python3 -m cakedb.cli examples/demo_queries.txt

# Level 1: an order comes in, then changes its mind about the flavour.
SET order-1042 flavour lemon
SET order-1042 tiers 3
SET order-1042 flavour chocolate
GET order-1042 flavour
DELETE order-1042 tiers
DELETE order-1042 tiers

# Level 2: what's on the order?
SET order-1042 filling fudge
SET order-1042 topper fondant-rose
SCAN order-1042
SCAN_BY_PREFIX order-1042 f

# Level 3: a fresh order whose "status" only lasts while it proofs.
SET_AT order-2001 flavour carrot 100
SET_AT_WITH_TTL order-2001 status proofing 100 30
GET_AT order-2001 status 129
GET_AT order-2001 status 130
SCAN_AT order-2001 130

# Level 4: back up, change things, then roll back.
SET_AT_WITH_TTL order-2001 status baking 140 60
BACKUP 150
SET_AT order-2001 flavour beetroot 160
RESTORE 300 155
SCAN_AT order-2001 300
GET_AT order-2001 status 349
GET_AT order-2001 status 350
tests/test_existing.py 125 lines
"""What already works before level 1: the package, its interface, and the CLI plumbing."""

import inspect
import unittest

from cakedb import CommandError, NoBackupError, OrderDatabase, format_field
from cakedb.cli import COMMANDS, parse_query, run_queries
from cakedb.formatting import render_result

EXPECTED_INTERFACE = {
    "set": ["key", "field", "value"],
    "get": ["key", "field"],
    "delete": ["key", "field"],
    "scan": ["key"],
    "scan_by_prefix": ["key", "prefix"],
    "set_at": ["key", "field", "value", "timestamp"],
    "set_at_with_ttl": ["key", "field", "value", "timestamp", "ttl"],
    "get_at": ["key", "field", "timestamp"],
    "delete_at": ["key", "field", "timestamp"],
    "scan_at": ["key", "timestamp"],
    "scan_by_prefix_at": ["key", "prefix", "timestamp"],
    "backup": ["timestamp"],
    "restore": ["timestamp", "timestamp_to_restore"],
}


def parameter_names(method):
    return [name for name in inspect.signature(method).parameters if name != "self"]


class RecordingDatabase:
    """Stands in for OrderDatabase and records which methods the CLI calls."""

    def __init__(self):
        self.calls = []

    def __getattr__(self, name):
        def method(*args):
            self.calls.append((name, args))
            return {"get": "lemon", "delete": True, "scan": ["a(1)", "b(2)"], "backup": 2}.get(name)

        return method


class InterfaceTest(unittest.TestCase):
    def test_database_can_be_created(self):
        OrderDatabase()

    def test_every_method_exists_with_the_documented_parameters(self):
        for name, params in EXPECTED_INTERFACE.items():
            with self.subTest(method=name):
                method = getattr(OrderDatabase, name, None)
                self.assertTrue(callable(method), f"OrderDatabase.{name} is missing")
                self.assertEqual(parameter_names(method), params)

    def test_no_backup_error_is_a_lookup_error(self):
        self.assertTrue(issubclass(NoBackupError, LookupError))


class FormattingTest(unittest.TestCase):
    def test_format_field(self):
        self.assertEqual(format_field("flavour", "chocolate"), "flavour(chocolate)")

    def test_render_result(self):
        self.assertEqual(render_result(None), "")
        self.assertEqual(render_result(True), "true")
        self.assertEqual(render_result(False), "false")
        self.assertEqual(render_result(3), "3")
        self.assertEqual(render_result("lemon"), "lemon")
        self.assertEqual(render_result(["a(1)", "b(2)"]), "a(1), b(2)")
        self.assertEqual(render_result([]), "")


class CliTest(unittest.TestCase):
    def test_every_command_matches_a_database_method(self):
        for name, command in COMMANDS.items():
            with self.subTest(command=name):
                self.assertEqual(list(command.params), EXPECTED_INTERFACE[command.method])

    def test_parse_query_converts_timestamps_and_ttls_to_int(self):
        command, args = parse_query("set_at_with_ttl order-1 status proofing 100 30")
        self.assertEqual(command.method, "set_at_with_ttl")
        self.assertEqual(args, ["order-1", "status", "proofing", 100, 30])

    def test_parse_query_rejects_bad_lines(self):
        for line in ["FROST order-1", "GET order-1", "GET_AT order-1 flavour soon"]:
            with self.subTest(line=line):
                with self.assertRaises(CommandError):
                    parse_query(line)

    def test_run_queries_dispatches_and_renders(self):
        db = RecordingDatabase()
        outputs = run_queries(
            db,
            [
                "# a comment",
                "SET order-1 flavour lemon",
                "",
                "GET order-1 flavour",
                "DELETE order-1 flavour",
                "SCAN order-1",
                "BACKUP 5",
                "RESTORE 9 5",
                "FROST order-1",
            ],
        )
        self.assertEqual(
            db.calls,
            [
                ("set", ("order-1", "flavour", "lemon")),
                ("get", ("order-1", "flavour")),
                ("delete", ("order-1", "flavour")),
                ("scan", ("order-1",)),
                ("backup", (5,)),
                ("restore", (9, 5)),
            ],
        )
        self.assertEqual(
            outputs,
            ["", "lemon", "true", "a(1), b(2)", "2", "", "error: unknown command 'FROST'"],
        )


if __name__ == "__main__":
    unittest.main()
tests/test_stage1.py 91 lines
"""Level 1: set, get and delete fields on order records."""

import unittest

from cakedb import OrderDatabase


class SetAndGetTest(unittest.TestCase):
    def setUp(self):
        self.db = OrderDatabase()

    def test_get_returns_what_was_set(self):
        self.assertIsNone(self.db.set("order-1", "flavour", "lemon"))
        self.assertEqual(self.db.get("order-1", "flavour"), "lemon")

    def test_get_missing_record_returns_none(self):
        self.assertIsNone(self.db.get("order-404", "flavour"))

    def test_get_missing_field_returns_none(self):
        self.db.set("order-1", "flavour", "lemon")
        self.assertIsNone(self.db.get("order-1", "tiers"))

    def test_set_replaces_an_existing_value(self):
        self.db.set("order-1", "flavour", "lemon")
        self.db.set("order-1", "flavour", "chocolate")
        self.assertEqual(self.db.get("order-1", "flavour"), "chocolate")

    def test_a_record_holds_many_fields(self):
        self.db.set("order-1", "flavour", "lemon")
        self.db.set("order-1", "tiers", "3")
        self.db.set("order-1", "status", "baking")
        self.assertEqual(self.db.get("order-1", "flavour"), "lemon")
        self.assertEqual(self.db.get("order-1", "tiers"), "3")
        self.assertEqual(self.db.get("order-1", "status"), "baking")

    def test_records_are_independent(self):
        self.db.set("order-1", "flavour", "lemon")
        self.db.set("order-2", "flavour", "carrot")
        self.assertEqual(self.db.get("order-1", "flavour"), "lemon")
        self.assertEqual(self.db.get("order-2", "flavour"), "carrot")
        self.assertIsNone(self.db.get("order-3", "flavour"))

    def test_matching_is_case_sensitive(self):
        self.db.set("order-1", "flavour", "lemon")
        self.assertIsNone(self.db.get("order-1", "Flavour"))
        self.assertIsNone(self.db.get("ORDER-1", "flavour"))


class DeleteTest(unittest.TestCase):
    def setUp(self):
        self.db = OrderDatabase()
        self.db.set("order-1", "flavour", "lemon")
        self.db.set("order-1", "tiers", "3")

    def test_delete_existing_field_returns_true_and_removes_it(self):
        self.assertIs(self.db.delete("order-1", "flavour"), True)
        self.assertIsNone(self.db.get("order-1", "flavour"))

    def test_delete_leaves_other_fields_alone(self):
        self.db.delete("order-1", "flavour")
        self.assertEqual(self.db.get("order-1", "tiers"), "3")

    def test_delete_missing_field_returns_false(self):
        self.assertIs(self.db.delete("order-1", "filling"), False)
        self.assertEqual(self.db.get("order-1", "flavour"), "lemon")

    def test_delete_missing_record_returns_false(self):
        self.assertIs(self.db.delete("order-404", "flavour"), False)

    def test_deleting_twice_returns_false_the_second_time(self):
        self.assertIs(self.db.delete("order-1", "flavour"), True)
        self.assertIs(self.db.delete("order-1", "flavour"), False)

    def test_deleting_every_field_then_setting_again(self):
        self.assertIs(self.db.delete("order-1", "flavour"), True)
        self.assertIs(self.db.delete("order-1", "tiers"), True)
        self.assertIsNone(self.db.get("order-1", "tiers"))
        self.assertIs(self.db.delete("order-1", "tiers"), False)

        self.db.set("order-1", "flavour", "vanilla")
        self.assertEqual(self.db.get("order-1", "flavour"), "vanilla")
        self.assertIsNone(self.db.get("order-1", "tiers"))

    def test_delete_only_touches_its_own_record(self):
        self.db.set("order-2", "flavour", "carrot")
        self.db.delete("order-1", "flavour")
        self.assertEqual(self.db.get("order-2", "flavour"), "carrot")


if __name__ == "__main__":
    unittest.main()
tests/test_stage2.py 113 lines
"""Level 2: scan a record (sorted by field name) and scan by field-name prefix."""

import unittest

from cakedb import OrderDatabase


class ScanTest(unittest.TestCase):
    def setUp(self):
        self.db = OrderDatabase()

    def test_scan_formats_fields_as_field_parens_value(self):
        self.db.set("order-1", "flavour", "lemon")
        self.assertEqual(self.db.scan("order-1"), ["flavour(lemon)"])

    def test_scan_sorts_by_field_name_not_insertion_order(self):
        self.db.set("order-1", "tiers", "3")
        self.db.set("order-1", "flavour", "lemon")
        self.db.set("order-1", "status", "baking")
        self.db.set("order-1", "box", "large")
        self.assertEqual(
            self.db.scan("order-1"),
            ["box(large)", "flavour(lemon)", "status(baking)", "tiers(3)"],
        )

    def test_scan_sorts_by_field_name_not_by_value(self):
        self.db.set("order-1", "alpha", "zebra")
        self.db.set("order-1", "beta", "apple")
        self.assertEqual(self.db.scan("order-1"), ["alpha(zebra)", "beta(apple)"])

    def test_scan_uses_default_string_ordering(self):
        for field in ["tier2", "apple", "tier10", "Zest"]:
            self.db.set("order-1", field, "x")
        self.assertEqual(
            self.db.scan("order-1"),
            ["Zest(x)", "apple(x)", "tier10(x)", "tier2(x)"],
        )

    def test_scan_missing_record_returns_empty_list(self):
        self.assertEqual(self.db.scan("order-404"), [])

    def test_scan_sees_overwrites_and_deletes(self):
        self.db.set("order-1", "flavour", "lemon")
        self.db.set("order-1", "tiers", "3")
        self.db.set("order-1", "flavour", "chocolate")
        self.db.delete("order-1", "tiers")
        self.assertEqual(self.db.scan("order-1"), ["flavour(chocolate)"])

    def test_scan_after_deleting_every_field_is_empty(self):
        self.db.set("order-1", "flavour", "lemon")
        self.db.delete("order-1", "flavour")
        self.assertEqual(self.db.scan("order-1"), [])

    def test_scan_only_shows_its_own_record(self):
        self.db.set("order-1", "flavour", "lemon")
        self.db.set("order-2", "filling", "jam")
        self.assertEqual(self.db.scan("order-1"), ["flavour(lemon)"])
        self.assertEqual(self.db.scan("order-2"), ["filling(jam)"])


class ScanByPrefixTest(unittest.TestCase):
    def setUp(self):
        self.db = OrderDatabase()
        self.db.set("order-1", "topper", "fondant-rose")
        self.db.set("order-1", "flavour", "lemon")
        self.db.set("order-1", "tiers", "3")
        self.db.set("order-1", "filling", "fudge")

    def test_returns_matching_fields_sorted(self):
        self.assertEqual(
            self.db.scan_by_prefix("order-1", "f"),
            ["filling(fudge)", "flavour(lemon)"],
        )
        self.assertEqual(
            self.db.scan_by_prefix("order-1", "t"),
            ["tiers(3)", "topper(fondant-rose)"],
        )

    def test_matches_field_names_not_values(self):
        # "topper" has the value "fondant-rose", but its name doesn't start with "fon".
        self.assertEqual(self.db.scan_by_prefix("order-1", "fon"), [])
        self.assertEqual(self.db.scan_by_prefix("order-1", "lem"), [])

    def test_is_a_prefix_match_not_a_substring_match(self):
        self.assertEqual(self.db.scan_by_prefix("order-1", "ill"), [])
        self.assertEqual(self.db.scan_by_prefix("order-1", "fill"), ["filling(fudge)"])

    def test_whole_field_name_is_a_prefix_of_itself(self):
        self.assertEqual(self.db.scan_by_prefix("order-1", "tiers"), ["tiers(3)"])

    def test_prefix_longer_than_field_name_does_not_match(self):
        self.assertEqual(self.db.scan_by_prefix("order-1", "tiers2"), [])

    def test_is_case_sensitive(self):
        self.assertEqual(self.db.scan_by_prefix("order-1", "F"), [])
        self.db.set("order-1", "Frosting", "buttercream")
        self.assertEqual(self.db.scan_by_prefix("order-1", "F"), ["Frosting(buttercream)"])

    def test_empty_prefix_matches_every_field(self):
        self.assertEqual(self.db.scan_by_prefix("order-1", ""), self.db.scan("order-1"))
        self.assertEqual(len(self.db.scan_by_prefix("order-1", "")), 4)

    def test_missing_record_returns_empty_list(self):
        self.assertEqual(self.db.scan_by_prefix("order-404", "f"), [])

    def test_sees_overwrites_and_deletes(self):
        self.db.set("order-1", "flavour", "pistachio")
        self.db.delete("order-1", "filling")
        self.assertEqual(self.db.scan_by_prefix("order-1", "f"), ["flavour(pistachio)"])


if __name__ == "__main__":
    unittest.main()
tests/test_stage3.py 185 lines
"""Level 3: timestamped operations, and fields that expire after a TTL.

A field written at time T with a TTL of N is live for T <= t < T + N.
"""

import unittest

from cakedb import OrderDatabase


class TimestampedBasicsTest(unittest.TestCase):
    def setUp(self):
        self.db = OrderDatabase()

    def test_set_at_and_get_at(self):
        self.assertIsNone(self.db.set_at("order-1", "flavour", "lemon", 1))
        self.assertEqual(self.db.get_at("order-1", "flavour", 2), "lemon")
        self.assertIsNone(self.db.get_at("order-1", "tiers", 3))
        self.assertIsNone(self.db.get_at("order-404", "flavour", 4))

    def test_field_without_ttl_never_expires(self):
        self.db.set_at("order-1", "flavour", "lemon", 1)
        self.assertEqual(self.db.get_at("order-1", "flavour", 10**9), "lemon")

    def test_delete_at_and_scans_without_ttls(self):
        self.db.set_at("order-1", "tiers", "3", 1)
        self.db.set_at("order-1", "flavour", "lemon", 2)
        self.db.set_at("order-1", "filling", "jam", 3)
        self.assertEqual(
            self.db.scan_at("order-1", 4),
            ["filling(jam)", "flavour(lemon)", "tiers(3)"],
        )
        self.assertEqual(
            self.db.scan_by_prefix_at("order-1", "fl", 5), ["flavour(lemon)"]
        )
        self.assertIs(self.db.delete_at("order-1", "tiers", 6), True)
        self.assertIs(self.db.delete_at("order-1", "tiers", 7), False)
        self.assertIs(self.db.delete_at("order-404", "tiers", 8), False)
        self.assertEqual(
            self.db.scan_at("order-1", 9), ["filling(jam)", "flavour(lemon)"]
        )


class TtlBoundaryTest(unittest.TestCase):
    def setUp(self):
        self.db = OrderDatabase()
        # Written at 100 with a TTL of 30: live for 100 <= t < 130.
        self.db.set_at_with_ttl("order-7", "status", "proofing", 100, 30)

    def test_live_at_the_moment_it_was_written(self):
        self.assertEqual(self.db.get_at("order-7", "status", 100), "proofing")

    def test_live_one_unit_before_expiry(self):
        self.assertEqual(self.db.get_at("order-7", "status", 129), "proofing")

    def test_expired_at_exactly_timestamp_plus_ttl(self):
        self.assertIsNone(self.db.get_at("order-7", "status", 130))

    def test_stays_expired(self):
        self.assertIsNone(self.db.get_at("order-7", "status", 131))
        self.assertIsNone(self.db.get_at("order-7", "status", 10**9))

    def test_ttl_counts_from_the_write_not_from_zero(self):
        # If the TTL were counted from time 0, the field would already be gone at 100.
        self.assertEqual(self.db.get_at("order-7", "status", 115), "proofing")

    def test_ttl_of_one_is_live_for_exactly_one_timestamp(self):
        self.db.set_at_with_ttl("order-8", "status", "boxed", 200, 1)
        self.assertEqual(self.db.get_at("order-8", "status", 200), "boxed")
        self.assertIsNone(self.db.get_at("order-8", "status", 201))


class ExpiryHidesFieldsTest(unittest.TestCase):
    def setUp(self):
        self.db = OrderDatabase()
        self.db.set_at("order-1", "flavour", "lemon", 10)
        self.db.set_at_with_ttl("order-1", "status", "proofing", 10, 20)  # live 10..29
        self.db.set_at_with_ttl("order-1", "filling", "jam", 10, 5)  # live 10..14
        self.db.set_at_with_ttl("order-1", "frosting", "ganache", 10, 50)  # live 10..59

    def test_scan_at_leaves_out_expired_fields(self):
        self.assertEqual(
            self.db.scan_at("order-1", 14),
            ["filling(jam)", "flavour(lemon)", "frosting(ganache)", "status(proofing)"],
        )
        self.assertEqual(
            self.db.scan_at("order-1", 15),
            ["flavour(lemon)", "frosting(ganache)", "status(proofing)"],
        )
        self.assertEqual(
            self.db.scan_at("order-1", 30), ["flavour(lemon)", "frosting(ganache)"]
        )

    def test_scan_by_prefix_at_leaves_out_expired_fields(self):
        self.assertEqual(
            self.db.scan_by_prefix_at("order-1", "f", 14),
            ["filling(jam)", "flavour(lemon)", "frosting(ganache)"],
        )
        self.assertEqual(
            self.db.scan_by_prefix_at("order-1", "f", 15),
            ["flavour(lemon)", "frosting(ganache)"],
        )
        self.assertEqual(self.db.scan_by_prefix_at("order-1", "s", 30), [])

    def test_scan_by_prefix_at_still_matches_names_not_values(self):
        self.assertEqual(self.db.scan_by_prefix_at("order-1", "pro", 11), [])
        self.assertEqual(self.db.scan_by_prefix_at("order-1", "st", 11), ["status(proofing)"])

    def test_delete_at_live_field_returns_true(self):
        self.assertIs(self.db.delete_at("order-1", "status", 29), True)
        self.assertIsNone(self.db.get_at("order-1", "status", 29))

    def test_delete_at_expired_field_returns_false(self):
        self.assertIs(self.db.delete_at("order-1", "filling", 15), False)
        self.assertIs(self.db.delete_at("order-1", "status", 30), False)
        self.assertEqual(self.db.get_at("order-1", "flavour", 31), "lemon")

    def test_record_whose_fields_all_expired_scans_empty(self):
        self.db.set_at_with_ttl("order-2", "status", "cooling", 10, 5)
        self.db.set_at_with_ttl("order-2", "box", "small", 10, 8)
        self.assertEqual(self.db.scan_at("order-2", 15), ["box(small)"])
        self.assertEqual(self.db.scan_at("order-2", 18), [])
        self.assertEqual(self.db.scan_by_prefix_at("order-2", "", 18), [])


class RewritingFieldsTest(unittest.TestCase):
    def setUp(self):
        self.db = OrderDatabase()

    def test_set_at_clears_an_earlier_ttl(self):
        self.db.set_at_with_ttl("order-1", "status", "proofing", 10, 5)
        self.db.set_at("order-1", "status", "baking", 12)
        self.assertEqual(self.db.get_at("order-1", "status", 15), "baking")
        self.assertEqual(self.db.get_at("order-1", "status", 10**9), "baking")

    def test_new_ttl_replaces_a_longer_old_one(self):
        self.db.set_at_with_ttl("order-1", "status", "proofing", 10, 100)  # until 110
        self.db.set_at_with_ttl("order-1", "status", "baking", 20, 5)  # until 25
        self.assertEqual(self.db.get_at("order-1", "status", 24), "baking")
        self.assertIsNone(self.db.get_at("order-1", "status", 25))

    def test_new_ttl_replaces_a_shorter_old_one(self):
        self.db.set_at_with_ttl("order-1", "status", "proofing", 10, 5)  # until 15
        self.db.set_at_with_ttl("order-1", "status", "baking", 12, 10)  # until 22
        self.assertEqual(self.db.get_at("order-1", "status", 21), "baking")
        self.assertIsNone(self.db.get_at("order-1", "status", 22))

    def test_ttl_can_be_added_to_a_field_that_had_none(self):
        self.db.set_at("order-1", "status", "boxed", 10)
        self.db.set_at_with_ttl("order-1", "status", "on-the-counter", 20, 10)
        self.assertEqual(self.db.get_at("order-1", "status", 29), "on-the-counter")
        self.assertIsNone(self.db.get_at("order-1", "status", 30))

    def test_expired_field_can_be_written_again(self):
        self.db.set_at_with_ttl("order-1", "status", "proofing", 10, 5)
        self.assertIsNone(self.db.get_at("order-1", "status", 15))
        self.db.set_at_with_ttl("order-1", "status", "baking", 16, 5)
        self.assertEqual(self.db.scan_at("order-1", 20), ["status(baking)"])
        self.assertIsNone(self.db.get_at("order-1", "status", 21))


class TtlValidationTest(unittest.TestCase):
    def setUp(self):
        self.db = OrderDatabase()
        self.db.set_at("order-1", "status", "boxed", 1)

    def test_zero_ttl_is_rejected(self):
        with self.assertRaises(ValueError):
            self.db.set_at_with_ttl("order-1", "status", "gone", 2, 0)

    def test_negative_ttl_is_rejected(self):
        with self.assertRaises(ValueError):
            self.db.set_at_with_ttl("order-1", "status", "gone", 2, -5)

    def test_rejected_write_changes_nothing(self):
        with self.assertRaises(ValueError):
            self.db.set_at_with_ttl("order-1", "status", "gone", 2, 0)
        with self.assertRaises(ValueError):
            self.db.set_at_with_ttl("order-2", "status", "gone", 3, -1)
        self.assertEqual(self.db.get_at("order-1", "status", 4), "boxed")
        self.assertEqual(self.db.scan_at("order-2", 5), [])


if __name__ == "__main__":
    unittest.main()
tests/test_stage4.py 224 lines
"""Level 4: backup and restore, with TTLs recalculated relative to the restore."""

import unittest

from cakedb import NoBackupError, OrderDatabase


class BackupCountTest(unittest.TestCase):
    def setUp(self):
        self.db = OrderDatabase()

    def test_backup_of_empty_database_returns_zero(self):
        self.assertEqual(self.db.backup(1), 0)

    def test_backup_returns_number_of_non_empty_records(self):
        self.db.set_at("order-1", "flavour", "lemon", 1)
        self.db.set_at("order-1", "tiers", "3", 2)
        self.db.set_at("order-2", "flavour", "carrot", 3)
        self.assertEqual(self.db.backup(4), 2)

    def test_record_with_every_field_deleted_is_not_counted(self):
        self.db.set_at("order-1", "flavour", "lemon", 1)
        self.db.set_at("order-2", "flavour", "carrot", 2)
        self.db.delete_at("order-2", "flavour", 3)
        self.assertEqual(self.db.backup(4), 1)

    def test_record_with_every_field_expired_is_not_counted(self):
        self.db.set_at("order-1", "flavour", "lemon", 1)
        self.db.set_at_with_ttl("order-2", "status", "cooling", 1, 9)  # live 1..9
        self.db.set_at_with_ttl("order-3", "status", "boxed", 1, 10)  # live 1..10
        self.assertEqual(self.db.backup(10), 2)  # order-2 expired at exactly 10

    def test_record_with_some_fields_expired_is_counted(self):
        self.db.set_at_with_ttl("order-1", "status", "cooling", 1, 5)
        self.db.set_at("order-1", "flavour", "lemon", 1)
        self.assertEqual(self.db.backup(20), 1)


class RestoreStateTest(unittest.TestCase):
    def setUp(self):
        self.db = OrderDatabase()
        self.db.set_at("order-1", "flavour", "lemon", 1)
        self.db.set_at("order-1", "tiers", "3", 2)
        self.db.backup(3)

    def test_restore_brings_back_changed_and_deleted_fields(self):
        self.db.set_at("order-1", "flavour", "chocolate", 4)
        self.db.delete_at("order-1", "tiers", 5)
        self.assertIsNone(self.db.restore(6, 3))
        self.assertEqual(self.db.scan_at("order-1", 7), ["flavour(lemon)", "tiers(3)"])

    def test_restore_removes_fields_and_records_written_after_the_backup(self):
        self.db.set_at("order-1", "filling", "jam", 4)
        self.db.set_at("order-2", "flavour", "carrot", 5)
        self.db.restore(6, 3)
        self.assertIsNone(self.db.get_at("order-1", "filling", 7))
        self.assertEqual(self.db.scan_at("order-2", 7), [])
        self.assertEqual(self.db.backup(8), 1)

    def test_restored_fields_without_ttl_never_expire(self):
        self.db.restore(4, 3)
        self.assertEqual(self.db.get_at("order-1", "flavour", 10**9), "lemon")

    def test_restored_database_keeps_working(self):
        self.db.restore(4, 3)
        self.db.set_at("order-1", "flavour", "vanilla", 5)
        self.assertIs(self.db.delete_at("order-1", "tiers", 6), True)
        self.assertEqual(self.db.scan_at("order-1", 7), ["flavour(vanilla)"])


class SnapshotIsolationTest(unittest.TestCase):
    """A backup is a snapshot: nothing done to the live database may leak into it."""

    def setUp(self):
        self.db = OrderDatabase()
        self.db.set_at("order-1", "flavour", "lemon", 1)
        self.db.backup(2)

    def test_changing_a_field_after_backup_does_not_change_the_backup(self):
        self.db.set_at("order-1", "flavour", "chocolate", 3)
        self.db.restore(4, 2)
        self.assertEqual(self.db.get_at("order-1", "flavour", 5), "lemon")

    def test_adding_a_field_to_a_backed_up_record_does_not_change_the_backup(self):
        self.db.set_at("order-1", "filling", "jam", 3)
        self.db.restore(4, 2)
        self.assertEqual(self.db.scan_at("order-1", 5), ["flavour(lemon)"])

    def test_deleting_after_backup_does_not_change_the_backup(self):
        self.db.delete_at("order-1", "flavour", 3)
        self.db.restore(4, 2)
        self.assertEqual(self.db.get_at("order-1", "flavour", 5), "lemon")

    def test_changes_after_a_restore_do_not_change_the_backup(self):
        self.db.restore(3, 2)
        self.db.set_at("order-1", "flavour", "chocolate", 4)
        self.db.set_at("order-1", "filling", "jam", 5)
        self.db.restore(6, 2)
        self.assertEqual(self.db.scan_at("order-1", 7), ["flavour(lemon)"])

    def test_the_same_backup_can_be_restored_many_times(self):
        for now in (10, 20, 30):
            self.db.set_at("order-1", "flavour", f"attempt-{now}", now)
            self.db.restore(now + 1, 2)
            self.assertEqual(self.db.get_at("order-1", "flavour", now + 2), "lemon")


class ChoosingABackupTest(unittest.TestCase):
    def setUp(self):
        self.db = OrderDatabase()
        self.db.set_at("order-1", "flavour", "v10", 1)
        self.db.backup(10)
        self.db.set_at("order-1", "flavour", "v20", 11)
        self.db.backup(20)
        self.db.set_at("order-1", "flavour", "v30", 21)
        self.db.backup(30)
        self.db.set_at("order-1", "flavour", "current", 31)

    def test_uses_latest_backup_before_the_requested_time(self):
        self.db.restore(40, 25)
        self.assertEqual(self.db.get_at("order-1", "flavour", 41), "v20")

    def test_a_backup_exactly_at_the_requested_time_counts(self):
        self.db.restore(40, 20)
        self.assertEqual(self.db.get_at("order-1", "flavour", 41), "v20")

    def test_one_unit_before_a_backup_uses_the_previous_one(self):
        self.db.restore(40, 19)
        self.assertEqual(self.db.get_at("order-1", "flavour", 41), "v10")

    def test_requested_time_after_every_backup_uses_the_last_one(self):
        self.db.restore(40, 40)
        self.assertEqual(self.db.get_at("order-1", "flavour", 41), "v30")

    def test_restoring_does_not_remove_backups(self):
        self.db.restore(40, 10)
        self.db.restore(41, 30)
        self.assertEqual(self.db.get_at("order-1", "flavour", 42), "v30")
        self.db.restore(43, 10)
        self.assertEqual(self.db.get_at("order-1", "flavour", 44), "v10")

    def test_backups_taken_after_a_restore_are_used(self):
        self.db.restore(40, 10)
        self.db.set_at("order-1", "flavour", "v50", 50)
        self.db.backup(55)
        self.db.restore(60, 57)
        self.assertEqual(self.db.get_at("order-1", "flavour", 61), "v50")


class NoBackupTest(unittest.TestCase):
    def setUp(self):
        self.db = OrderDatabase()
        self.db.set_at("order-1", "flavour", "lemon", 1)

    def test_restore_with_no_backups_at_all_raises(self):
        with self.assertRaises(NoBackupError):
            self.db.restore(5, 5)

    def test_restore_before_the_first_backup_raises(self):
        self.db.backup(10)
        with self.assertRaises(NoBackupError):
            self.db.restore(20, 9)

    def test_failed_restore_leaves_database_unchanged(self):
        self.db.backup(10)
        self.db.set_at("order-1", "flavour", "chocolate", 11)
        with self.assertRaises(NoBackupError):
            self.db.restore(20, 9)
        self.assertEqual(self.db.get_at("order-1", "flavour", 21), "chocolate")


class RestoreRecalculatesTtlTest(unittest.TestCase):
    def setUp(self):
        self.db = OrderDatabase()
        # Live 10 <= t < 30. At the backup (t=15) it has 15 units left.
        self.db.set_at_with_ttl("order-7", "status", "proofing", 10, 20)
        self.db.set_at("order-7", "flavour", "lemon", 10)
        self.assertEqual(self.db.backup(15), 1)

    def test_remaining_ttl_is_counted_from_the_restore(self):
        self.db.restore(100, 15)
        # 100 + 15 = 115. An absolute expiry (30) would already be gone here.
        self.assertEqual(self.db.get_at("order-7", "status", 114), "proofing")

    def test_restored_field_expires_at_restore_time_plus_remaining_ttl(self):
        self.db.restore(100, 15)
        # Using the original TTL (100 + 20 = 120) would keep it live here.
        self.assertIsNone(self.db.get_at("order-7", "status", 115))
        self.assertEqual(self.db.scan_at("order-7", 115), ["flavour(lemon)"])

    def test_remaining_ttl_is_measured_at_the_backup_not_the_requested_time(self):
        # Asking for 18 uses the backup taken at 15, when 15 units were left.
        self.db.restore(100, 18)
        self.assertEqual(self.db.get_at("order-7", "status", 114), "proofing")
        self.assertIsNone(self.db.get_at("order-7", "status", 115))

    def test_restoring_before_the_original_expiry(self):
        self.db.restore(20, 15)  # expires at 35, not 30
        self.assertEqual(self.db.get_at("order-7", "status", 34), "proofing")
        self.assertIsNone(self.db.get_at("order-7", "status", 35))

    def test_each_restore_recalculates_from_the_backup(self):
        self.db.restore(100, 15)  # expires at 115
        self.db.restore(200, 15)  # expires at 215
        self.assertEqual(self.db.get_at("order-7", "status", 214), "proofing")
        self.assertIsNone(self.db.get_at("order-7", "status", 215))

    def test_backing_up_a_restored_field_saves_its_new_remaining_ttl(self):
        self.db.restore(100, 15)  # expires at 115
        self.assertEqual(self.db.backup(110), 1)  # 5 units left
        self.db.restore(300, 110)  # expires at 305
        self.assertEqual(self.db.get_at("order-7", "status", 304), "proofing")
        self.assertIsNone(self.db.get_at("order-7", "status", 305))

    def test_field_expired_at_backup_time_is_not_restored(self):
        self.db.set_at_with_ttl("order-8", "status", "cooling", 16, 4)  # live 16..19
        self.assertEqual(self.db.backup(20), 1)  # only order-7
        self.db.restore(30, 20)
        self.assertIsNone(self.db.get_at("order-8", "status", 30))
        self.assertEqual(self.db.scan_at("order-8", 30), [])


if __name__ == "__main__":
    unittest.main()

Download the starter repo. Done, or out of time? Download the reference solution (spoilers) and compare it with yours.

More AI coding interview practice

Reviewed by Stephen Cognetta, CEO of Aced. Last updated: December 4, 2026

. . .