Implement an in-memory “database” that stores records by key and fields within each key. Each operation is given a timestamp (integer, non-decreasing across calls) and should behave as if executed at that time.
A record conceptually looks like:
DB[key][field] = value
(value is an integer)
However, later levels add TTL expiration and historical (“time-travel”) queries, so your implementation must maintain enough history to answer those queries.
key
or
field
does not exist (or is expired at the queried time), treat it as missing.
timestamp
as the “current time” for visibility/expiration.
field
ascending.
Implement:
set(timestamp: int, key: str, field: str, value: int) -> None
DB[key][field] = value
at
timestamp
.
get(timestamp: int, key: str, field: str) -> Optional[int]
(key, field)
at
timestamp
, or
None
if missing.
compare_and_set(timestamp: int, key: str, field: str, expected_value: int, new_value: int) -> bool
timestamp
equals
expected_value
, update it to
new_value
and return
True
.
False
(no change).
compare_and_delete(timestamp: int, key: str, field: str, expected_value: int) -> bool
timestamp
equals
expected_value
, delete the field and return
True
.
False
.
Implement:
scan(timestamp: int, key: str) -> List[str]
key
at
timestamp
formatted as:
"{field}({value})"
.
field
ascending.
scan_with_prefix(timestamp: int, key: str, prefix: str) -> List[str]
scan
, but only include entries where the formatted string starts with
prefix
.
prefix
.)
Add per-write TTL (time-to-live). A value written with TTL is visible only in the half-open interval:
t
where
write_timestamp <= t < write_timestamp + ttl
.
Implement:
set_with_ttl(timestamp: int, key: str, field: str, value: int, ttl: int) -> None
compare_and_set_with_ttl(timestamp: int, key: str, field: str, expected_value: int, new_value: int, ttl: int) -> bool
compare_and_set
, but when the update happens it writes
new_value
with the provided
ttl
.
Additionally, all previously implemented read/write operations must be updated so that:
get
,
scan
,
scan_with_prefix
) do not return expired values,
timestamp
(treat expired as missing).
Implement:
get_when(timestamp: int, key: str, field: str, at_timestamp: int) -> Optional[int]
It should return the value of (key, field) as it was visible at time at_timestamp, considering:
set
/
set_with_ttl
Assume at_timestamp <= timestamp. If the value was missing or expired at at_timestamp, return None.