Skip to content

feat: UUID.entropy() builds TA/TB entropy from an optional seed - #103

Merged
Shinrai merged 4 commits into
nextfrom
feat/entropy-helper
Nov 10, 2026
Merged

Shinrai merged 4 commits into
nextfrom
feat/entropy-helper

Conversation

@cldmv-bot

@cldmv-bot cldmv-bot Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

🚀 What's Changed

✨ Features

  • feat: UUID.entropy() builds TA/TB entropy from an optional seed (e718c10)

🐛 Bug Fixes

  • fix: UUID.entropy() review fixes - stamped form only, "advance" default for seconds, no wait across a clock step back (503519a)
  • fix: UUID.entropy() overflow wait gives up on a frozen clock (70f3af9)
  • fix: take the entropy helper's random bits with masks and shifts (75e9602)
👥 Contributors

Resolves #102

UUID.entropy({ seed, precision, onOverflow }) returns the 16-byte entropy
argument TA()/TB() read, filling only the 49 bits they keep (bit 79 and
bytes 10-15): a 12-bit per-tick counter, 16 bits of SHA-1(seed) (random
without a seed) and 21 random bits. The counter starts each tick at a
random value in 0-2047, so two calls in one process on the same tick never
repeat. On overflow it waits for the next tick or, with "advance", moves
ahead of the clock; the tick used is returned as .timestamp for stamping
the id. precision "s" counts seconds for TA. Only the rng and hash
subpaths are imported, so it runs in the browser. TA() and TB() are
unchanged.

Resolves #102
@cldmv-bot cldmv-bot Bot added ! feature → next v4 flow: contributor PR targeting the next integration branch type: feature Implements new functionality — a PR or issue that adds a feature area: core Touches core library / runtime source code area: tests Touches test files, fixtures, or test infrastructure type: documentation Relates to docs, README updates, guides, or inline code comments labels Nov 9, 2026
Comment thread src/lib/entropy.mjs Fixed
Comment thread src/lib/entropy.mjs Fixed
Comment thread src/lib/entropy.mjs Fixed
…lt for seconds, no wait across a clock step back

- Every example, JSDoc and the type test stamp the id with the returned
  .timestamp. The README says plainly that TB(undefined, e) gives up the
  no-repeat guarantee on overflow, with "advance" or after a clock step back.
- onOverflow defaults to "wait" for "ms" and "advance" for "s", where a wait
  could block for a second. The docs note that a coarsened browser Date.now
  can make an "ms" wait spin that long.
- The overflow wait stops spinning when a reading comes back below the tick
  it started on, and advances to the next tick instead.
- The docs give the cross-instance odds (about 2^-32 per pair with one seed,
  2^-48 without), say the counter is per module instance and per worker or
  thread, and warn that TA needs precision "s".
- Tests check every result for bits outside 79-127, a counter within 4095,
  unique (tick, counter) pairs, a last counter of 4095 on an overflowed tick
  and stamped ids sorting in mint order, which kills the off-by-one overflow
  mutant. They load the helper through the package entry, so test:dist runs
  them against the build. Headers come from fix-headers.

Resolves #102
The "wait" spin stops after 1,000,000 readings without the clock moving and
advances the tick itself, as the step-back branch does. Before, a frozen
Date.now (fake timers) hung any caller that minted more than about 2048 ids
in one millisecond. The module docs, the onOverflow option and the README
document the fallback.

New tests mint 6000 ids at "ms" with the default "wait" on a frozen clock,
once with a pinned Date.now and once under vi.useFakeTimers: both return
with no repeats and consecutive ticks. The test clocks are plain counting
functions instead of spies, and throw after a set number of readings, so a
spin bug fails with a clear message instead of exhausting the heap.

Resolves #102
The counter's random start takes the top 11 bits of two random bytes with
a shift and mask instead of a modulo, and the 49-bit field is written
byte by byte with masks and shifts instead of summing into one number and
dividing it back out. The layout and the distribution are unchanged; this
clears the js/biased-cryptographic-random alerts CodeQL raised on the
modulo, addition and division.

Resolves #102
@Shinrai
Shinrai merged commit 6fa4aae into next Nov 10, 2026
28 checks passed
@cldmv-bot
cldmv-bot Bot deleted the feat/entropy-helper branch November 10, 2026 04:16
cldmv-bot Bot added a commit that referenced this pull request Nov 10, 2026
# `@cldmv/uuid` v1.5.0 Changelog

**Release Date**: November 2026
**Release Type**: Minor
**Branch**: `release/1.5.0`

---

## Overview

v1.5.0 adds `UUID.entropy()`, a helper that builds the `entropy` argument for `UUID.TA()` and `UUID.TB()`. It packs a per-tick counter, a 16-bit fingerprint of an optional seed and random bits into the 49 entropy bits those variants keep (or any other length, with the `bits` option), so two ids minted by one module instance on the same tick never repeat (at any length of 12 bits or more). `TA()` and `TB()` themselves don't change, and ids minted without the helper are exactly as before.

The test suite also runs against the built `dist/` now, not only against `src/`, so a bundling problem fails the build instead of reaching a consumer.

---

## ✨ Features

### `UUID.entropy()` ([#103](#103), fixes [#102](#102))

- `UUID.entropy({ seed, precision, bits, onOverflow })` returns a 16-byte `Uint8Array` with bits 79-127 filled by default and a `timestamp` property: the tick the counter was taken on. Stamp the id with it: `UUID.TB(e.timestamp, e)`.
- Bit layout of the 49 bits: a 12-bit counter (bits 79-90) that starts each tick at a random value in 0-2047 and counts up, so an instance gets at least 2048 ids per tick and ids from one instance in one tick sort in the order they were made; 16 bits of SHA-1 of the seed (bits 91-106), random when there is no seed; and 21 random bits (bits 107-127).
- `bits` sets the length in bits; the default, 49, is the layout above. Any length of 0 or more works ([#105](#105)): the same fields fill the last `bits` bits in the same order, longer lengths get more random bits, and a short one cuts them where it runs out (under 28 bits the seed fingerprint keeps only its top bits, under 12 the counter keeps only its low bits and repeats inside a tick after 2^`bits` calls). The array is 16 bytes, longer past 128 bits.
- `precision: "ms"` (default) matches `TB()`. `TA()` stores seconds, so use `precision: "s"` with it.
- `onOverflow`: when the counter runs out inside a tick, `"wait"` spins until the next tick and `"advance"` moves to the next tick at once. The default is `"wait"` for milliseconds and `"advance"` for seconds, where a wait could block for up to a second.
- The tick never moves backwards. After a clock step back the helper stays on its last tick and keeps counting, and a wait gives up after 1,000,000 readings with no change, so a frozen `Date.now()` (fake timers in a test suite) can't hang it.
- The guarantee is per module instance (per worker or thread). Between instances it rests on chance: at the default length, about 2^-32 for two instances with the same seed minting on the same tick, about 2^-48 with no seed.
- Browser-safe: it uses the package's own `rng` and `hash` modules, which switch to Web Crypto and a pure-JS SHA-1 under the `browser` condition.
- Typed in `types/src/uuid.d.mts` and covered by the consumer type test.

## 🧪 Tests

- New `tests/entropy.test.vitest.mjs` and `tests/entropy-browser.test.vitest.mjs`: the bit layout, the seed fingerprint, no repeats inside a tick and across overflow, both overflow modes, clock steps back, the frozen-clock cap, and the browser build ([#103](#103)); the `bits` option at the default, longer, past-128, short and zero lengths ([#105](#105)).
- `npm run test:dist` builds and runs the Vitest suites against `dist/` (`--mode=dist` leaves the `uuid-dev` condition off). `npm test` and `ci:coverage` include it, and `tests/resolve.test.vitest.mjs` checks that `@cldmv/uuid` resolved to the tree the run is meant to test ([#98](#98)).

## 📚 Documentation

- README: a `UUID.entropy([options])` section with the options, the bit layout, what a custom `bits` length holds, the stamping rule, the scope of the guarantee and examples for `TB` and `TA` ([#103](#103)). The test commands list `test:dist` ([#98](#98)).
- **NEW:** [docs/changelog/v1/v1.5.0.md](./v1.5.0.md): this changelog.
- README What's New promoted to v1.5.0.

## 🔧 Dependencies

- No dependency changes.

---

## Upgrade notes

- No breaking changes. `UUID.entropy()` is new and opt-in; existing calls to `TA()`, `TB()` and every other variant behave as in v1.4.0.
- When using the helper, always pass its `timestamp` to `TA()`/`TB()`. Passing `undefined` lets them read the clock themselves, which gives up the no-repeat guarantee on counter overflow, with `"advance"`, or after a clock step back.



<details>
<summary>👥 Contributors</summary>

- @Shinrai

</details>

---

<!-- coverage-start -->

![coverage](https://img.shields.io/badge/coverage-85.1%25-green?style=for-the-badge&logo=vitest&logoColor=white)

| Metric | Coverage |
|--------|----------|
| Statements | 82.8% |
| Branches   | 85.2% |
| Functions  | 90.3% |
| Lines      | 82.4% |

*Avg: **85.1%** · `72b2436` · Node lts/**

<!-- coverage-end -->

<!-- co-authors -->

Co-authored-by: Shinrai <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: core Touches core library / runtime source code area: tests Touches test files, fixtures, or test infrastructure ! feature → next v4 flow: contributor PR targeting the next integration branch type: documentation Relates to docs, README updates, guides, or inline code comments type: feature Implements new functionality — a PR or issue that adds a feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants