From 457ee6958ebb9d3fdb81e65305dd9b4625ea0cc4 Mon Sep 17 00:00:00 2001 From: Liang Xu <24490353+lx3133584@users.noreply.github.com> Date: Sun, 29 Nov 2026 05:50:16 +0800 Subject: [PATCH] fix(ids): keep time-ordered IDs increasing within a millisecond --- ...uuidv7-makes-a-uuid-of-any-16-byte-type.md | 6 +- ...dered-ids-increase-within-a-millisecond.md | 26 ++++++ docs/decisions/README.md | 13 +-- ids/ids.go | 65 +++++++++++---- ids/ids_test.go | 82 +++++++++++++------ skills/ant/SKILL.md | 7 +- 6 files changed, 150 insertions(+), 49 deletions(-) create mode 100644 docs/decisions/179-time-ordered-ids-increase-within-a-millisecond.md diff --git a/docs/decisions/168-ids-uuidv7-makes-a-uuid-of-any-16-byte-type.md b/docs/decisions/168-ids-uuidv7-makes-a-uuid-of-any-16-byte-type.md index 0071136..16e0f85 100644 --- a/docs/decisions/168-ids-uuidv7-makes-a-uuid-of-any-16-byte-type.md +++ b/docs/decisions/168-ids-uuidv7-makes-a-uuid-of-any-16-byte-type.md @@ -2,11 +2,11 @@ id: 168 title: "ids.UUIDv7 makes a UUID of any 16-byte type" area: models -status: active +status: amended tags: [ids.UUIDv7, ids.UUID, GenerateKey, uuid, keys, text] issues: [344] related: [150] -changed_by: [] +changed_by: [179] code: [ids/ids.go] tests: [ids/ids_test.go, tests/features/keys_and_identity/uuidv7_key_test.go] --- @@ -15,6 +15,8 @@ tests: [ids/ids_test.go, tests/features/keys_and_identity/uuidv7_key_test.go] **In short:** `ids.UUIDv7[T]()` returns a version 7 UUID as any type whose underlying type is `[16]byte`, so `ant.GenerateKey(b, &Users.ID, ids.UUIDv7[uuid.UUID])` fills a key that PostgreSQL stores in a `uuid` column. `ids.UUID` stays, and is the same value as text for a `string` key, which is a `text` column. +> **Amended.** Decision 179 uses 12 bits after the timestamp for a guarded sub-millisecond sequence, so IDs also increase within one millisecond. + ## Decision `ids.UUID` returns a string, so the key it fills is a `string` field, and a `string` field is a `text` column. The key and every foreign key to it then take 37 bytes where a `uuid` takes 16, in the table and in each index; any string is accepted as a key, since `GenerateKey` keeps a key the application supplies; and changing the type later rewrites every table that holds it (#344). A `uuid` column needed `.Type("uuid")` on every model, or a `uuid.UUID` key with a wrapper around `uuid.NewV7`, which returns an error as well and so is not a `func() V`. diff --git a/docs/decisions/179-time-ordered-ids-increase-within-a-millisecond.md b/docs/decisions/179-time-ordered-ids-increase-within-a-millisecond.md new file mode 100644 index 0000000..1974e4d --- /dev/null +++ b/docs/decisions/179-time-ordered-ids-increase-within-a-millisecond.md @@ -0,0 +1,26 @@ +--- +id: 179 +title: "Time-ordered IDs increase within a millisecond" +area: models +status: active +tags: [ids.UUIDv7, ids.UUID, ids.ULID, monotonic, uuid, keys] +issues: [353] +related: [168] +changed_by: [] +code: [ids/ids.go] +tests: [ids/ids_test.go] +--- + +# 179. Time-ordered IDs increase within a millisecond + +**In short:** `ids.UUIDv7`, `ids.UUID` and `ids.ULID` strictly increase within one process, including in a burst within one millisecond. A 12-bit sub-millisecond sequence sits after the UUID version and at the start of the ULID random part. + +## Decision + +Decision 168 put a millisecond timestamp before random bits. Keys made in the same millisecond therefore sorted randomly, giving a primary-key index no better locality than a random UUID in a tight loop (#353). + +The generators now share a clock guard. It reads the fraction of the current millisecond in units of 256 nanoseconds, and returns the previous millisecond-and-fraction pair plus one whenever the clock's pair is not greater. The 48-bit millisecond and 12-bit fraction stay strictly increasing; when a millisecond's 4096 fractions are exhausted, the sequence rolls into the next millisecond rather than waiting or repeating. A mutex covers only this calculation, not the entropy read. + +For UUIDv7, the fraction occupies the 12 bits of `rand_a` after the version, as in RFC 9562 section 6.2 method 3. The variant and every other random bit stay unchanged, and `UUID` is the same value as text. For ULID, it occupies the first 12 bits after the timestamp, leaving the remaining 68 random bits. Both text and binary forms retain their existing layouts and lengths. + +Rejected: keeping random bits immediately after the timestamp. That only orders keys made in different milliseconds, which is precisely the bulk-insert case that needs help. Sleeping after 4096 values was rejected too: rolling the sequence into the next millisecond keeps a bounded, valid value without stopping a hot generator. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 35d617f..59c514f 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -87,8 +87,9 @@ On 2026-11-20 the decisions moved from one file, `docs/DECISIONS.md`, to a file | [150](150-a-zero-key-nothing-fills-is-refused.md) | A zero key that nothing fills is refused | active | `primary-key` `uuid` `zero-value` `GenerateKey` `default` `ErrZeroKey` | | [151](151-deletedat-is-a-time-or-null-in-json.md) | DeletedAt is a time or null in JSON | active | `DeletedAt` `soft-delete` `JSON` `MarshalJSON` | | [152](152-open-refuses-values-the-driver-cannot-take.md) | Open refuses values the driver can't take | active | `Open` `ErrNoColumnType` `driver` `slice` `map` `struct` `PlainValues` `Table` | -| [168](168-ids-uuidv7-makes-a-uuid-of-any-16-byte-type.md) | ids.UUIDv7 makes a UUID of any 16-byte type | active | `ids.UUIDv7` `ids.UUID` `GenerateKey` `uuid` `keys` `text` | +| [168](168-ids-uuidv7-makes-a-uuid-of-any-16-byte-type.md) | ids.UUIDv7 makes a UUID of any 16-byte type | amended by [179](179-time-ordered-ids-increase-within-a-millisecond.md) | `ids.UUIDv7` `ids.UUID` `GenerateKey` `uuid` `keys` `text` | | [176](176-ants-structs-have-camelcase-json-keys.md) | ant's structs have camelCase JSON keys | active | `json` `Base` `Page` `CursorPage` `Point` `Partition` `metrics` `breaking` | +| [179](179-time-ordered-ids-increase-within-a-millisecond.md) | Time-ordered IDs increase within a millisecond | active | `ids.UUIDv7` `ids.UUID` `ids.ULID` `monotonic` `uuid` `keys` | #### Values and types @@ -391,8 +392,8 @@ Before changing a file, read the decisions about it. | `go.mod` | [10](010-module-path.md) | | `graph.go` | [93](093-tracking-follows-what-a-save-wrote.md) [120](120-the-root-does-not-track-and-a-session-does.md) | | `hooks.go` | [47](047-hooks-run-inside-the-write.md) [105](105-read-mostly-registries-are-copy-on-write-snapshots.md) [123](123-an-after-hooks-edit-is-a-change-to-save.md) [154](154-the-ctx-carries-the-transaction.md) [157](157-insert-validation-leaves-zero-default-fields-to-the-database.md) | -| `ids/ids.go` | [168](168-ids-uuidv7-makes-a-uuid-of-any-16-byte-type.md) | -| `ids/ids_test.go` | [168](168-ids-uuidv7-makes-a-uuid-of-any-16-byte-type.md) | +| `ids/ids.go` | [168](168-ids-uuidv7-makes-a-uuid-of-any-16-byte-type.md) [179](179-time-ordered-ids-increase-within-a-millisecond.md) | +| `ids/ids_test.go` | [168](168-ids-uuidv7-makes-a-uuid-of-any-16-byte-type.md) [179](179-time-ordered-ids-increase-within-a-millisecond.md) | | `include.go` | [33](033-include-shape-functions.md) [44](044-many-to-many.md) [65](065-scoped-relations-use-the-same-filter-path.md) [93](093-tracking-follows-what-a-save-wrote.md) [138](138-a-uint64-column-on-postgresql-is-numeric.md) | | `intercept.go` | [46](046-interceptors.md) | | `internal/errs/errs.go` | [17](017-implemented-ahead-of-the-skeleton.md) [125](125-open-refuses-a-model-it-would-misread.md) | @@ -703,6 +704,8 @@ Tags on two or more decisions. Search the headers for the rest: `rg -l '^tags: . - `hooks`: [47](047-hooks-run-inside-the-write.md) [63](063-savechanges-batches-inserts.md) [79](079-a-tracking-context-serves-one-operation-at-a-time.md) [123](123-an-after-hooks-edit-is-a-change-to-save.md) [154](154-the-ctx-carries-the-transaction.md) - `identity`: [94](094-migrations-keep-a-columns-dependents-working-while-it.md) [114](114-an-identity-columns-default-is-not-ants-to-change.md) [138](138-a-uint64-column-on-postgresql-is-numeric.md) [158](158-drift-compares-two-explicit-serial-defaults.md) - `identity-map`: [27](027-all-returns-t.md) [28](028-identity-and-relation-slices.md) [39](039-global-filters-are-lazy.md) [107](107-hot-paths-allocate-for-the-operation-not-for-each-row.md) [108](108-kept-sql-by-shape-unboxed-keys-compact-snapshots-and.md) [112](112-a-locking-read-puts-the-row-into-the-tracked-instance.md) [148](148-a-query-with-computed-fields-stays-tracked.md) +- `ids.UUID`: [168](168-ids-uuidv7-makes-a-uuid-of-any-16-byte-type.md) [179](179-time-ordered-ids-increase-within-a-millisecond.md) +- `ids.UUIDv7`: [168](168-ids-uuidv7-makes-a-uuid-of-any-16-byte-type.md) [179](179-time-ordered-ids-increase-within-a-millisecond.md) - `immutable`: [98](098-an-explicit-write-refuses-the-columns-ant-keeps.md) [139](139-a-field-can-not-ask-for-two-things-ant-can-not-both-do.md) - `In`: [24](024-raw-sql-arguments.md) [95](095-in-means-eq-and-other-value-rules.md) [146](146-ne-matches-null-as-go-does.md) - `Include`: [33](033-include-shape-functions.md) [44](044-many-to-many.md) [65](065-scoped-relations-use-the-same-filter-path.md) [93](093-tracking-follows-what-a-save-wrote.md) [108](108-kept-sql-by-shape-unboxed-keys-compact-snapshots-and.md) @@ -716,7 +719,7 @@ Tags on two or more decisions. Search the headers for the rest: `rg -l '^tags: . - `InTx`: [154](154-the-ctx-carries-the-transaction.md) [155](155-a-bound-transaction-settles-what-its-contexts-did.md) - `JSON`: [42](042-converters-are-scanner-and-valuer.md) [109](109-numbers-inside-an-interface-read-as-json-number.md) [151](151-deletedat-is-a-time-or-null-in-json.md) - `jsonb`: [134](134-a-type-postgresql-has-a-column-for-maps-to-it-and-reads-back.md) [135](135-a-column-ant-made-for-an-earlier-default-is-converted-as-ant-stored-it.md) -- `keys`: [138](138-a-uint64-column-on-postgresql-is-numeric.md) [168](168-ids-uuidv7-makes-a-uuid-of-any-16-byte-type.md) +- `keys`: [138](138-a-uint64-column-on-postgresql-is-numeric.md) [168](168-ids-uuidv7-makes-a-uuid-of-any-16-byte-type.md) [179](179-time-ordered-ids-increase-within-a-millisecond.md) - `LastInsertId`: [75](075-generated-values-without-returning.md) [122](122-what-the-database-fills-is-read-back-by-key.md) - `Latest`: [65](065-scoped-relations-use-the-same-filter-path.md) [163](163-includejoined-applies-the-relations-own-conditions.md) - `LeftJoin`: [136](136-an-outer-joins-side-reads-what-only-the-driver-converts.md) [147](147-a-projection-reads-null-into-a-plain-field-as-zero.md) @@ -824,7 +827,7 @@ Tags on two or more decisions. Search the headers for the rest: `rg -l '^tags: . - `UseTx`: [79](079-a-tracking-context-serves-one-operation-at-a-time.md) [141](141-a-statement-inside-an-each-loop-on-one-connection-is-refused.md) - `utc`: [41](041-automatic-timestamps.md) [76](076-one-clock-for-times-without-a-zone.md) [84](084-every-time-is-bound-in-utc-where-columns-keep-no-zone.md) - `UTCTimes`: [74](074-dialects-state-their-differences.md) [76](076-one-clock-for-times-without-a-zone.md) -- `uuid`: [131](131-a-foreign-key-column-follows-its-target.md) [145](145-helpers-take-a-field-of-any-type.md) [150](150-a-zero-key-nothing-fills-is-refused.md) [168](168-ids-uuidv7-makes-a-uuid-of-any-16-byte-type.md) +- `uuid`: [131](131-a-foreign-key-column-follows-its-target.md) [145](145-helpers-take-a-field-of-any-type.md) [150](150-a-zero-key-nothing-fills-is-refused.md) [168](168-ids-uuidv7-makes-a-uuid-of-any-16-byte-type.md) [179](179-time-ordered-ids-increase-within-a-millisecond.md) - `Validate`: [47](047-hooks-run-inside-the-write.md) [157](157-insert-validation-leaves-zero-default-fields-to-the-database.md) - `valuer`: [42](042-converters-are-scanner-and-valuer.md) [92](092-tracked-values-compare-as-stored.md) - `version`: [80](080-every-write-moves-the-version-on.md) [90](090-merge-keeps-what-other-writes-keep.md) [91](091-an-upsert-checks-a-copys-version-on-mysql-and-mariadb.md) [93](093-tracking-follows-what-a-save-wrote.md) [102](102-updatemany-keeps-what-a-bulk-update-keeps.md) [110](110-a-version-the-application-sets-is-the-one-checked.md) [139](139-a-field-can-not-ask-for-two-things-ant-can-not-both-do.md) [140](140-an-update-that-changed-nothing-is-checked-against-the-row.md) diff --git a/ids/ids.go b/ids/ids.go index 38d9909..e7a6375 100644 --- a/ids/ids.go +++ b/ids/ids.go @@ -4,8 +4,9 @@ // ant.GenerateKey(b, &Orders.ID, ids.UUID) // } // -// UUID, UUIDv7 and ULID sort by creation time, unlike a random UUID, so new rows -// land at the end of an index instead of scattering across it. +// UUID, UUIDv7 and ULID sort by creation time, even within one millisecond, +// unlike a random UUID, so new rows land at the end of an index instead of +// scattering across it. // // UUID fills a string key, which is a text column. For a native uuid column, give // the key a 16-byte type such as github.com/google/uuid's, and fill it with @@ -22,9 +23,8 @@ import ( "time" ) -// UUID returns a version 7 UUID in its usual text form: a millisecond timestamp -// followed by random bits, so values sort by time. It is UUIDv7 as text, for a -// string key. +// UUID returns a version 7 UUID in its usual text form. It has UUIDv7's layout +// and strictly increasing order, for a string key. func UUID() string { b := UUIDv7[[16]byte]() @@ -42,25 +42,53 @@ func UUID() string { return string(out[:]) } -// UUIDv7 returns a version 7 UUID as any 16-byte type: a millisecond timestamp -// followed by random bits, so values sort by time. With a UUID type such as -// github.com/google/uuid's, the key is a native uuid column, where UUID's string -// is a text one: +// UUIDv7 returns a version 7 UUID as any 16-byte type: a millisecond timestamp, +// a 12-bit sub-millisecond sequence, and random bits. Values made by one process +// strictly increase. With a UUID type such as github.com/google/uuid's, the key +// is a native uuid column, where UUID's string is a text one: // // ant.GenerateKey(b, &Orders.ID, ids.UUIDv7[uuid.UUID]) func UUIDv7[T ~[16]byte]() T { var b [16]byte - fillTime(b[:6]) rand.Read(b[6:]) - b[6] = b[6]&0x0f | 0x70 + + ms, sequence := nextTime() + fillTime(b[:6], ms) + b[6] = 0x70 | byte(sequence>>8)&0x0f + b[7] = byte(sequence) b[8] = b[8]&0x3f | 0x80 return T(b) } -func fillTime(b []byte) { - ms := time.Now().UnixMilli() +var ( + timeMu sync.Mutex + lastTime int64 +) + +// nextTime returns a millisecond and a 12-bit fraction of it, in units of 256 +// nanoseconds. The pair strictly increases, even when the clock does not. +func nextTime() (millisecond, sequence int64) { + timeMu.Lock() + defer timeMu.Unlock() + + nano := time.Now().UnixNano() + millisecond = nano / int64(time.Millisecond) + sequence = (nano - millisecond*int64(time.Millisecond)) >> 8 + now := millisecond<<12 | sequence + + if now <= lastTime { + now = lastTime + 1 + millisecond = now >> 12 + sequence = now & 0xfff + } + + lastTime = now + + return millisecond, sequence +} +func fillTime(b []byte, ms int64) { for i := len(b) - 1; i >= 0; i-- { b[i] = byte(ms) ms >>= 8 @@ -69,13 +97,18 @@ func fillTime(b []byte) { const crockford = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" -// ULID returns a 26-character ULID: a millisecond timestamp and random bits in -// Crockford base 32, which sorts by time as text. +// ULID returns a 26-character ULID: a millisecond timestamp, a 12-bit +// sub-millisecond sequence, and random bits in Crockford base 32. Values made by +// one process strictly increase, including as text. func ULID() string { var b [16]byte - fillTime(b[:6]) rand.Read(b[6:]) + ms, sequence := nextTime() + fillTime(b[:6], ms) + b[6] = byte(sequence >> 4) + b[7] = b[7]&0x0f | byte(sequence<<4) + var out [26]byte // 128 bits in 26 characters of 5 bits each, with 2 spare bits at the top. var acc uint32 diff --git a/ids/ids_test.go b/ids/ids_test.go index 4bb2b2a..4cdd0bd 100644 --- a/ids/ids_test.go +++ b/ids/ids_test.go @@ -5,6 +5,7 @@ import ( "encoding/hex" "regexp" "sort" + "sync" "testing" "time" ) @@ -14,15 +15,18 @@ func TestUUID(t *testing.T) { `^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`, ) - first := UUID() - if !shape.MatchString(first) { - t.Fatalf("bad UUID %s", first) + previous := UUID() + if !shape.MatchString(previous) { + t.Fatalf("bad UUID %s", previous) } - time.Sleep(2 * time.Millisecond) + for i := 1; i <= 1000; i++ { + next := UUID() + if next <= previous { + t.Fatalf("UUID %d, %s, does not sort after %s", i, next, previous) + } - if later := UUID(); later <= first { - t.Fatalf("%s does not sort after %s", later, first) + previous = next } } @@ -30,7 +34,9 @@ func TestUUID(t *testing.T) { type key [16]byte func TestUUIDv7(t *testing.T) { - for range 1000 { + var previous key + + for i := 0; i < 1000; i++ { id := UUIDv7[key]() if version := id[6] >> 4; version != 7 { @@ -40,18 +46,12 @@ func TestUUIDv7(t *testing.T) { if variant := id[8] >> 6; variant != 0b10 { t.Fatalf("%x has variant bits %02b, want 10", id, variant) } - } - first := UUIDv7[key]() - - time.Sleep(2 * time.Millisecond) - - if later := UUIDv7[key](); bytes.Compare(later[:], first[:]) <= 0 { - t.Fatalf("%x does not sort after %x", later, first) - } + if i > 0 && bytes.Compare(id[:], previous[:]) <= 0 { + t.Fatalf("UUID %d, %x, does not sort after %x", i, id, previous) + } - if a, b := UUIDv7[key](), UUIDv7[key](); a == b { - t.Fatalf("%x came out twice", a) + previous = id } } @@ -88,15 +88,51 @@ func TestUUIDv7AndUUIDShareALayout(t *testing.T) { } func TestULID(t *testing.T) { - first := ULID() - if len(first) != 26 { - t.Fatalf("bad ULID %s", first) + previous := ULID() + if len(previous) != 26 { + t.Fatalf("bad ULID %s", previous) + } + + for i := 1; i <= 1000; i++ { + next := ULID() + if next <= previous { + t.Fatalf("ULID %d, %s, does not sort after %s", i, next, previous) + } + + previous = next } +} + +func TestNextTimeConcurrent(t *testing.T) { + const ( + workers = 8 + perWorker = 1000 + ) - time.Sleep(2 * time.Millisecond) + times := make(chan int64, workers*perWorker) + + var wg sync.WaitGroup + + for range workers { + wg.Go(func() { + for range perWorker { + ms, sequence := nextTime() + times <- ms<<12 | sequence + } + }) + } + + wg.Wait() + close(times) + + seen := map[int64]bool{} + + for value := range times { + if seen[value] { + t.Fatalf("time and sequence %d came out twice", value) + } - if later := ULID(); later <= first { - t.Fatalf("%s does not sort after %s", later, first) + seen[value] = true } } diff --git a/skills/ant/SKILL.md b/skills/ant/SKILL.md index 4134383..7eaf916 100644 --- a/skills/ant/SKILL.md +++ b/skills/ant/SKILL.md @@ -126,9 +126,10 @@ Calls that take columns of mixed types take `ant.FieldRef`, made with such as `uuid.UUID` or `string`, is yours to fill: set it, generate it in `Configure` with `ant.GenerateKey(b, &Docs.ID, uuid.New)`, or give it a default (`ant:"default=gen_random_uuid()"`). Inserting one at its zero value returns - `ant.ErrZeroKey`. For keys that sort by time, generate with - `ids.UUIDv7[uuid.UUID]` (package `ant/ids`): a `uuid.UUID` key is a `uuid` - column, while a `string` key, such as one `ids.UUID` fills, is a `text` column. + `ant.ErrZeroKey`. For keys that sort by time, even within one millisecond, + generate with `ids.UUIDv7[uuid.UUID]` (package `ant/ids`): a `uuid.UUID` key + is a `uuid` column, while a `string` key, such as one `ids.UUID` fills, is a + `text` column. - `time.Time` fields named `CreatedAt` and `UpdatedAt` are maintained by ant, on any model. `ant.Base` is just `ID`, `CreatedAt` and `UpdatedAt`. A zero `UpdatedAt`, as in a struct decoded from a request body, is stamped on every save.