Row identity and primary keys

v3.2.0

Every row is named by a 48-bit integer key that is never changed and never handed to another row, except after an explicit PURGE.

In this article

Every row in KDBS has one permanent name: its primary key, a 48-bit integer stored in the first column. The key cannot be updated, and once a row with that key has committed, the key never names a different row. The one exception is an explicit PURGE. Because of this rule, indexes, Cabins and other structures can store a row’s key instead of its physical address, and an application can keep a key without worrying that it will later point at someone else’s row.

The engine’s own messages and system views call this key the tuple key.

How it works

The Keystone word

Every row starts with a 64-bit word called the Keystone word. It holds the row’s identity:

 bits 0-47          48-55      56-63
+------------------+----------+----------+
| id (primary key) | flags    | reserved |
+------------------+----------+----------+
  1 .. 2^48 - 1      written 0  written 0
  • The id field is the primary key. It ranges from 1 to 2^48 − 1 (281,474,976,710,655). 0 means “unset”.
  • The key is stored only here. It is not stored a second time as an ordinary column.
  • The first column of every table must have an integer type. Its declared width is for display only: the key always lives in the 48-bit field.

Where a key comes from

Each INSERT row either names its key or leaves it out. The choice is made per row, not per table, and one statement can mix both:

  • Name the key. Give a value for every column. The first value is the key.
  • Leave it out. Give one value fewer. The engine issues a key.
  • With a column list, the key is named when the list includes the key column and issued when it does not.
INSERT INTO accounts VALUES (500, 'erin', 750);              -- key 500, named
INSERT INTO accounts VALUES ('frank', 120);                  -- key issued by the engine
INSERT INTO accounts VALUES (100, 'grace', 300);             -- a named key may sort below the mark
INSERT INTO accounts (balance, owner) VALUES (5, 'ken');     -- column list without the key: issued
kdbs> INSERT INTO accounts VALUES (500, 'erin', 750)
INSERTED oid=4002 id=500 page=132 slot=3
kdbs> INSERT INTO accounts VALUES ('frank', 120)
INSERTED oid=4002 id=501 page=132 slot=4
kdbs> INSERT INTO accounts VALUES (100, 'grace', 300)
INSERTED oid=4002 id=100 page=132 slot=3
kdbs> INSERT INTO accounts (balance, owner) VALUES (5, 'ken')
INSERTED oid=4002 id=502 page=132 slot=7

Each table keeps a high-water mark, next_id. It is stored, never computed as max(id) + 1, so deleting the highest row does not make its key available for reissue. An issued key is the current mark. A named key at or above the mark moves the mark past it, which is why naming 500 and then omitting the key gave 501. A named key below the mark does not move it.

Issued keys ascend in the order they are issued, across all cores. Named keys carry no order: a named key may be any free key, in any order. The table’s B+ tree places each row where its key sorts.

When a key is refused

A named key is refused for exactly two reasons. In both cases nothing is written.

ReasonError classExample message
The key is already bound to a row, live or deletedAlreadyExistsduplicate tuple key 100 already present at page 132 slot 3
The key is outside [1, 2^48 − 1]OutOfRangetuple key 0 is outside the Keystone id space [1, 281474976710655]
kdbs> INSERT INTO accounts VALUES (100, 'heidi', 50)
                                   ^
ERR duplicate tuple key 100 already present at page 132 slot 3 (byte 29)
kdbs> INSERT INTO accounts VALUES (281474976710656, 'big', 0)
                                   ^
ERR tuple key 281474976710656 is outside the Keystone id space [1, 281474976710655] (byte 29)

A row with the wrong number of values is refused with both accepted counts:

kdbs> INSERT INTO accounts VALUES (1, 2, 3, 4)
                                   ^
ERR expected 3 value(s) including tuple key column 'id', or 2 to have it issued; got 4 (byte 29)

The life of a key

 free ──INSERT──▶ placed, uncommitted ──COMMIT──▶ bound ──DELETE──▶ bound (deleted row)
  ▲                       │                                              │
  └──────ROLLBACK─────────┘                                              │
  ▲                                                                      │
  └─────────────────────────────PURGE (once no reader can see it)────────┘
  • Rolled back: the key is free again. Naming it a second time places it.
  • Committed: the key stays bound, even after DELETE. A DELETE only marks the row deleted; the row stays in place for older snapshots, and it holds its key.
  • Purged: PURGE removes deleted rows in a key range and frees their keys. After it, an INSERT that names the key places a new row.
kdbs> DELETE FROM accounts WHERE id = 100
DELETED 1
kdbs> INSERT INTO accounts VALUES (100, 'grace', 300)
                                   ^
ERR duplicate tuple key 100: a row with this key was deleted; PURGE frees its key (page 132 slot 3) (byte 29)
kdbs> PURGE FROM accounts WHERE id = 100
PURGED 1
kdbs> INSERT INTO accounts VALUES (100, 'grace', 300)
INSERTED oid=4002 id=100 page=132 slot=4

The engine never issues a purged key by itself. Only an INSERT that names it takes it again.

The key cannot be updated

The key is the row’s identity, not one of its fields. An UPDATE that assigns it is refused when the statement is compiled, so nothing is written:

kdbs> UPDATE accounts SET id = 9 WHERE id = 1
                          ^
ERR tuple key column 'id' cannot be updated at byte 20; it is the tuple's identity, not a field of it

To give a row a new key, delete it and insert a new row.

What it guarantees

  • One key, one committed row. A key is bound to at most one committed row for the life of the table, except across a PURGE that freed it.
  • A stored key never points at the wrong row. A key kept elsewhere can dangle (its row was deleted), but it cannot name another committed row unless that key was purged and inserted again.
  • The issue cursor never goes back. next_id only rises, and an issued key is never issued twice.
  • Every reader re-checks. Indexes, Cabins and Waystone trails store keys. Each one compares a stored key against the row actually found, so a purged and re-inserted key reads as the new row.

What it costs

  • Keys are unique, not gapless. A failed insert can use up an issued key, and a caller may skip ranges. Nothing in the engine depends on keys being consecutive.
  • Deleted rows keep their keys and their space until PURGE runs. A key that was deleted cannot be named again before that.
  • Sparse named keys use the key budget faster. The budget is the key space (2^48 − 1 keys per table), not a row count. Naming key 1,000,000 moves the mark past every key below it.
  • No key changes. A row that needs a different key must be deleted and inserted again.
  • A purged key is a new identity. A system outside the engine that recorded a key must treat a purged and reused key as a different row. The purge is written to the log, which records when the key was freed.

How to observe it

sys.relation_stats shows each table’s mark (next_id), the keys issued and the keys left. After the INSERT examples above:

kdbs> SELECT name, next_id, ids_issued, ids_remaining, budget_used_ppm, budget_warning FROM sys.relation_stats WHERE name = 'accounts'
    name  next_id  ids_issued    ids_remaining  budget_used_ppm  budget_warning
--------  -------  ----------  ---------------  ---------------  --------------
accounts      502         501  281474976710154                0               0

SHOW BUDGET lists the same columns for every table. budget_warning turns to 1 once a table has used 90% of its key space, and budget_exhausted once it has used all of it. To list only the tables near their limit, filter the view: SELECT name FROM sys.relation_stats WHERE budget_warning = 1.

DESCRIBE marks the key column with tuple_key 1:

kdbs> DESCRIBE accounts
rel_id,rel_name,pos,name,type_val,type,notnull,tuple_key,cabin,references
4002,accounts,0,id,4,int64,1,1,NULL,NULL
4002,accounts,1,owner,9,varchar,1,0,auto,NULL
4002,accounts,2,balance,4,int64,1,0,auto,NULL

The INSERTED reply names the key and where the row was placed. The slot is the slot at placement; a later insert into the same page can move it.

Limitations

  • The key must be the first column, and an integer. There are no composite or text primary keys. A natural key, such as an email address, can be kept unique with a UNIQUE index.
  • A named key must be an integer: a literal, or a constant expression such as 800 + 1 that folds to one. A non-integer value is refused InvalidArgument.
  • An omitted key can be refused. If another session names the exact key the engine just issued, the engine draws again. After 8 such draws in a row the INSERT is refused AlreadyExists. This needs a client that names each next key as it is issued.
  • PURGE runs in autocommit only, on B+ tree tables only, and needs the admin role. It waits up to 1 second for older readers and is then refused with a retryable TXN_CONFLICT. It is refused on a table that carries a Transition. See PURGE.
  • No engine-internal purge exists. Deleted rows are removed only by PURGE.

See also