Codec

Codec layer #

The “codec” in this engine is the mapping between protocol-level structures and the KV pairs ledis writes. It is not a serialization format you can choose — it is fixed by ledis and visible only through side effects such as key limits, ordering and migration.

What gets encoded #

Logical operationPhysical operations
SET k vPut(KVType + k, v)
HSET k f vPut(HashType + k + f, v), IncrBy(HSizeType + k, 1) on a new field
RPUSH k vPut(ListType + k + index, v), update LMetaType + k (head, tail, count)
SADD k mPut(SetType + k + m, nil), IncrBy(SSizeType + k, 1)
ZADD k score mPut(ZSetType + k + m, score), Put(ZScoreType + k + score + m, nil), size counter
EXPIRE k sPut(ExpTimeType + k, timestamp), Put(ExpMetaType + k, …)

Deletes are the inverse: a hash field delete removes one HashType record and decrements the size counter, while HCLEAR walks them all and removes the counters and expiry records too.

Why the type byte matters #

Because the type is part of the storage key, two types never collide, and no type check is needed on read: GET k simply looks up KVType + k and returns nil if it is absent, even if a hash exists under HashType + k. That is the mechanical reason there is no WRONGTYPE — and why you cannot ask a key for its type.

Ordering guarantees that fall out of the encoding #

  • Sorted sets are ordered by the encoded score record: sign separator, then big-endian score, then member. Range queries are index scans, and equal scores sort by member.
  • Lists are ordered by a uint32 index with a head/tail metadata record, so LPUSH and RPUSH are both O(1) and LINDEX is a direct lookup — but LINSERT/LREM rewrite the whole range.
  • Sets and hashes have no inherent order: iteration is physical key order of the backend, which is why reply order differs between goleveldb and badger and must not be relied on.

Values are opaque #

The codec never interprets values. A string value is the bytes you sent; a hash field value likewise. Compression, encryption and content addressing are driver concerns (ipfs-synckv encrypts, ipfs addresses by CID, badger compresses blocks). This is why --storage-backend changes durability and privacy but never command semantics.

Migration implications #

  • The encoding is stable across releases in this tree; changing it would break on-disk compatibility and is why the ledger of storage behaviours in COMMAND-AUDIT.md is treated as a contract.
  • Snapshots are not encoded: writeSnapshot streams raw physical key/value pairs, so a restore depends on the same ledis encoding being present in the target binary. Back up across versions with that in mind: restore with a binary whose ledis layer matches the snapshot’s.