Implement an in-memory database that supports key-field records with optional TTL, historical queries, and compare-and-set operations. The database is organized as a collection of records, each identified by a unique string key. Within each record, data is stored in named fields that hold string values. You must support the following commands:
SET(key, field, value, ttl=None) – Set a field in a record to a value. If ttl (seconds) is provided, the field expires ttl seconds after the moment of this call. Fields without TTL never expire.
GET(key, field) – Return the current value of the field in the record, or empty string "" if the key or field does not exist or is expired.
DELETE(key, field) – Delete a field from a record. No-op if the key or field does not exist.
SCAN(key) – Return a comma-separated string of "field(value)" pairs for every non-expired field in the record, sorted lexicographically by field name. Return empty string "" if the key does not exist or has no non-expired fields.
COMPARE_AND_SET(key, field, expected_value, new_value) – Atomically set field to new_value only if the field currently equals expected_value. Return "true" if the swap succeeded, "false" otherwise (including when the field is missing or expired).
GET_AT(key, field, at_timestamp) – Return the value that the field contained at or immediately before at_timestamp (seconds since epoch), based on the history of writes. Return "" if the key/field had not been created yet at that time.
Your implementation must be thread-safe for concurrent calls. All timestamps are integers in seconds. Expiry is evaluated lazily on access: a field is considered expired when current_timestamp >= expiry_time, and expiry_time itself is treated as expired.