Decouple generator state#65
Merged
Merged
Conversation
…ULIDGenerator Extracts the stateful monotonicity tracking, thread locks, and clock/randomness sourcing out of the global class-level scope and encapsulates it in a clean, isolated `ULIDGenerator` class. Why this change was made: 1. Global isolation: Avoids global mutable state pollution where calling ULID() affects the generation of all other ULIDs in different parts of an application. 2. Testability: Tests no longer need to mutate global class-level properties of `ULID.provider` directly. They can now cleanly instantiate isolated generators and inject mock clocks or mock randomness sources, aligning with the principle "the interface is the test surface". 3. Customizability: Callers can now configure and instantiate distinct generator instances with different lifecycles and behaviors. All backward compatibility is fully preserved. A default shared generator is created inside `ulid` so that calls to `ULID()` and `from_timestamp` continue working out-of-the-box. Added full unit tests to cover state isolation and custom clocks/entropy injection.
…e decorator Removes the obsolete `validate_type` generic class/decorator wrapper from all `ULID` class constructors and inlines clean, high-performance `isinstance` checks. Why this change was made: 1. Architectural depth: Replaced a shallow decorator module with direct, readable runtime type validation, satisfying "Proposal 2" of the architectural review. 2. Performance & Debuggability: Eliminates wrapper function overhead in critical paths and keeps stack traces clean during exception reporting. 3. Clean namespace: Safely removed obsolete `Generic` and `TypeVar` typing imports. Preserves exact backwards compatible TypeError messages for all validation paths.
Introduces a swappable `MonotonicityPolicy` interface (Protocol) to configure and vary the generator's behavior during same-millisecond collisions. Implementations added: 1. `StrictMonotonicPolicy`: Always increments the randomness by 1 (default), raising ValueError if the 80-bit randomness is exhausted. 2. `PureRandomPolicy`: Completely ignores monotonicity and always returns fresh, high-entropy random bytes, maximizing security and unpredictability. 3. `LaxMonotonicPolicy`: Attempts to increment monotonically, but on randomness exhaustion, regenerates fresh randomness instead of raising errors or sleeping. Other Changes: - Exposes direct type-assertion checks in the test suite to safely verify isolated states. - Appended robust unit tests verifying the correctness of `PureRandomPolicy` and `LaxMonotonicPolicy` under collision and overflow constraints. - Updated `CONTEXT.md` to formally document swappable Monotonicity Policies.
…ator Consolidate ULID generation behind a single ULIDGenerator seam and expose it as the public surface for customizing generation: - Remove the per-call `policy` keyword from ULID(), from_timestamp, from_datetime and parse. The value object now delegates to a module-level, reassignable `default_generator`; callers wanting a custom policy build a ULIDGenerator and call generate(). - Collapse timestamp coercion into ULIDGenerator._normalize_timestamp so that generate() is the sole normalizer (datetime/int/float/None -> ms), with the narrow TypeError guards kept on the ULID.from_* constructors. - Narrow the MonotonicityPolicy interface: drop the increment_bytes parameter and move the increment into BaseMonotonicPolicy._increment. - Document ULIDGenerator, the monotonicity policies and default_generator in the API reference and add a "Generators and policies" section to the README. - Add 4.0.0 (breaking: ValueProvider/ULID.provider removed) and 3.2.1 changelog entries, and record the Keep a Changelog convention in AGENTS.md.
|
❌ The last analysis has failed. |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #65 +/- ##
==========================================
- Coverage 99.41% 98.65% -0.76%
==========================================
Files 4 4
Lines 342 372 +30
Branches 53 61 +8
==========================================
+ Hits 340 367 +27
- Misses 1 3 +2
- Partials 1 2 +1 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Replaces the internal
ValueProviderwith a publicULIDGeneratorthat owns ULID generation — sampling the clock, sourcing randomness, and enforcing a configurable monotonicity policy.ULID()and theULID.from_*constructors delegate to a swappable module-leveldefault_generator.ULID.providerclass attribute have been removed. To customize generation, build aULIDGeneratorand either callgenerate()or assign it toulid.default_generator:validate_typedecorator was also removed; theULID.from_*constructors still raiseTypeErrorfor wrong-typed input, so runtime behavior is unchanged.Highlights