Repository navigation
Conversation
The docs site example predated the async API and no longer ran. Pull the README's example in via snippets so the two can't drift apart.
Document every package in Google style so the API reference is useful, and correct a few existing docstrings in the event store.
phelma
left a comment
There was a problem hiding this comment.
Code Review: #143 - Document the public API and fix the docs site example
Verdict: COMMENT
This PR fills a long-standing gap with careful, mostly accurate documentation. Spot checks across all four lenses found that the large majority of the ~560 docstrings match the implementation. Replacing the broken docs-site example with a checked snippet from the README is a clear win. There are two main gaps. Several hazards the PR description already identifies (lock defects, late broker registration, memory/Postgres divergence) are missing from the public docstrings users will actually read. And 15 docstrings wrap their Returns:/Yields: descriptions in a way the configured griffe parser splits into separate return items.
Cross-Cutting Themes
- Known defects are documented in the PR, not in the docstrings (flagged by: correctness, usability, documentation): The Postgres lock timeout, in-memory lock removal and late distributed-broker registration are listed in the PR description but missing from, or softened in, the public docstrings. The generated reference therefore promises behaviour the code doesn't deliver. Adopting one
Warning:convention that links a tracking issue would address all of them. - In-memory vs Postgres behaviour divergence (flagged by: correctness, usability, documentation):
REGEX_MATCHESanchoring andKeySetPagingClauseedge cases differ between backends. The publicOperator/clause docstrings either don't mention this or describe only one backend. Users who test in memory and deploy on Postgres will be caught out.
Tradeoff Analysis
- Documenting current behaviour vs avoiding entrenching bugs: Describing current behaviour as plain fact makes later fixes look like breaking changes. Leaving it out means users hit the hazards blind. The recommendation is to describe it, but mark it explicitly as a known defect (
Warning:plus issue link) so that the fix can remove the note.
Strengths
- ✅
docs/index.mdnow includes the README's async example throughpymdownx.snippetswithcheck_paths: true. The docs-site example works again, can't drift from the README, and the build fails if the markers disappear. - ✅ Extension-point contracts are spelled out:
EventStorageAdapterinvariants (contiguous positions, atomic saves, conditions checked under lock),ProjectionStorageAdapterupsert semantics, andEventSubscriber.acceptidempotency. - ✅ The
Projectordocstring includes a working subclass example, explains snake_case handler routing, and warns about event names that collide with projector methods. - ✅ The docstrings are honest about non-obvious behaviour:
max_insert_batch_sizecurrently unused,connection_settingsunused by the singleton broker, retry strategies retrying non-matching exceptions immediately, and snapshot vs paginated scans. - ✅
make_event_brokerdocuments which kwargs each broker/storage combination needs, which**kwargswould otherwise hide. - ✅ The coordinator, observer and error-handler docstrings describe the real sequencing and precedence (withdraw before accept, later-argument-wins), not an idealised version.
- ✅ The house style is followed: Google sections, lower-case
Returnsdescriptions matching the existingstoredocstrings, and consistent British English. The existingassert_satisfieddocstrings were tidied up. - ✅ Docstrings that replace
pass/...placeholder bodies remain valid bodies.
General Findings
- 🟡 Usability / Documentation: Suspected bugs found while documenting have no consistent, visible marker and are recorded only in the PR description. Raise tracking issues and add a
Warning:section on the affected public classes that references each one. - 🔵 Documentation: Most of the new docstrings (in
processing,query,sourcesandpersistence) are not yet rendered on the docs site, becausedocs/index.mdonly has:::entries for parts ofstore,types,projectionandtesting. This depends on #141 landing. - 🔵 Correctness (low confidence): The in-memory
score_similaritycan divide by zero when both strings are shorter than the n-gram size. - 🔵 Correctness (low confidence): The in-memory subscriber state
purgeremoves items from the list it is iterating over, so adjacent stale subscribers can survive. That contradicts the documented contract. - 🔵 Correctness (low confidence): Subscription state
applyis transactional on Postgres but not in memory, and the base docstring doesn't state the intended atomicity. - 🔵 Standards: Nothing lints the docstring convention. Consider ruff
Drules withconvention = "google". - 🔵 Standards:
Type Parameters:andExamplesections are used unevenly across public generic classes. - 🔵 Documentation: No changelog fragment has been added for the docs-site fix and the API docstrings.
Additional Findings
- 🔵
src/logicblocks/event/processing/services/error/retry_strategy.py:45: Include/Exclude retry strategies don't explain how to get "retry only X" (usability) - 🔵
src/logicblocks/event/persistence/postgres/settings.py:57: The unencoded-credentials note gives no remedy (usability) - 🔵
src/logicblocks/event/projection/projector.py:164: Points to a README section that isn't on the docs site (usability) - 🔵
src/logicblocks/event/processing/locks/postgres.py:55: Mixes 'PostgreSQL' and 'Postgres' (standards) - 🔵
src/logicblocks/event/testing/data.py:146: Uses 'id', 'ID' and 'identifier' inconsistently (standards) - 🔵
src/logicblocks/event/persistence/converter.py:10: The class summary's mood differs from its subclasses (standards) - 🔵
src/logicblocks/event/processing/services/error/error.py:350: The summary line wraps onto a second line (standards) - 🔵
src/logicblocks/event/store/adapters/postgres/adapter.py:79: Dataclasses useArgs:vsAttributes:inconsistently (standards)
Review generated by /review-pr
| """Lock manager using PostgreSQL transaction-level advisory locks. | ||
|
|
||
| Each lock attempt opens a new connection, and the lock is held for the | ||
| duration of that connection's transaction. | ||
|
|
||
| Args: | ||
| connection_settings: The settings used to connect to PostgreSQL. | ||
| """ |
There was a problem hiding this comment.
🟡 Correctness / Usability / Documentation
LockManager.wait_for_lock documents timeout as the maximum time to wait. This class doesn't override that docstring and says nothing about timeouts. The implementation builds lock_timeout from timeout.microseconds / 1000, which is only the sub-second part, so timedelta(seconds=5) becomes lock_timeout = 0, which Postgres treats as wait forever. The PR description calls this the most significant suspected bug, and says docstrings describe current behaviour where they touch one. This docstring doesn't.
Impact: A reader of the reference who passes a multi-second timeout gets a call that can block indefinitely instead of returning timed_out=True.
Suggestion: Ideally fix it (timeout.total_seconds() * 1000). Otherwise add a Warning: saying only the sub-second part of timeout is honoured, and link a tracking issue.
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Confirmed. Rendering the statement with psycopg, timedelta(seconds=5) gives SET lock_timeout TO '0.0ms', which turns the timeout off. timedelta(seconds=1, milliseconds=500) gives '500.0ms'. InMemoryLockManager uses total_seconds() (locks/memory.py:52), so the two managers behave differently.
One addition to the fix: clamp it to at least 1ms, e.g. max(1, math.ceil(timeout.total_seconds() * 1000)). Otherwise timedelta(0) and sub-millisecond timeouts still mean wait forever.
Scope: nothing in src calls wait_for_lock today (the coordinator uses try_lock, coordinator.py:195), so only direct callers are affected.
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Not changed in the docstring: this is a code bug, to be fixed in code rather than documented.
|
|
||
|
|
||
| class InMemoryLockManager(LockManager): | ||
| """Lock manager using `asyncio` locks, local to a single event loop.""" |
There was a problem hiding this comment.
🟡 Correctness / Usability
"Lock manager using asyncio locks, local to a single event loop" implies ordinary mutual exclusion. Both try_lock and wait_for_lock, however, pop the lock from the registry in finally (including on timeout) while other coroutines may still hold or await the same asyncio.Lock. The next caller then gets a fresh lock from the defaultdict, so two coroutines can hold the same named lock at once.
Impact: This manager backs in-memory broker coordination and is the natural choice in tests. Tests can pass while work isn't actually serialised.
Suggestion: Either remove a lock only when it is neither held nor awaited, or add a Warning: that mutual exclusion isn't guaranteed under contention, with a link to a tracking issue.
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Partly confirmed. Two coroutines can hold the same lock, but only when wait_for_lock is involved. Reproduced both ways:
- A holds and B waits. A exits and pops the lock. C then gets a fresh lock while B holds the old one.
- A holds. B times out and pops the lock. C then gets a fresh lock while A still holds.
With try_lock alone there's no await between lookup and acquire, and a 200-coroutine run showed no overlap. The broker coordinator only calls try_lock (coordinator.py:195), so the stated impact on in-memory broker coordination doesn't hold.
Any Warning: should say it applies to wait_for_lock. A fix needs its own holder/waiter count, because asyncio.Lock only exposes waiters through the private _waiters.
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Not changed in the docstring: this is a code bug, to be fixed in code rather than documented.
| Returns: | ||
| an async iterator over the events in the stream. | ||
| an async iterator over the events in the stream, in position | ||
| order. |
There was a problem hiding this comment.
🟡 Standards
With docstring_style: google and griffe's default returns_multiple_items: true, a continuation line at the item's own indentation starts a new return item. So in position / order. here renders as two rows in the Returns table, and mkdocs build --strict doesn't warn. I checked this with the installed griffe. 15 docstrings in this PR are affected, including store.py (6), store/adapters/base.py (save, latest, scan), locks/base.py wait_for_lock, difference.py diff, consumers/state/base.py, consumers/state/types.py, services/callable.py and memory/converters/types.py lookup. Others (e.g. types/event.py, Projector.apply) already use a hanging indent.
Suggestion: Either indent continuation lines by 4 spaces, as Args:/Raises: already do, or set docstring_options: {returns_multiple_items: false} for the python handler in mkdocs.yml.
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Confirmed. With griffe 2.4.1 (Google style, default options), EventStream.iterate parses into two return items. Exactly the 15 docstrings listed are affected, all of them new in this PR. Both suggested fixes produce a single item.
One addition: the CallableService.from_maybe_callable implementation (services/callable.py) has no return annotation, so griffe warns No type or annotation for returned value 1. --strict only passes today because processing isn't rendered, so it will fail once it is. That also contradicts the PR description's note that the unannotated Returns: sections were rewritten.
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Fixed in 10d1b03: continuation lines in all 15 Returns:/Yields: sections now use a hanging indent; griffe parses each as a single item.
| EQUAL: The field equals the value. On Postgres, a value of `None` | ||
| matches a null field. | ||
| NOT_EQUAL: The field does not equal the value. On Postgres, a value | ||
| of `None` matches a non-null field. | ||
| GREATER_THAN: The field is greater than the value. | ||
| GREATER_THAN_OR_EQUAL: The field is greater than or equal to the | ||
| value. | ||
| LESS_THAN: The field is less than the value. | ||
| LESS_THAN_OR_EQUAL: The field is less than or equal to the value. | ||
| IN: The field is one of the values in the given sequence. | ||
| CONTAINS: The field contains the value, for example a list | ||
| containing an element or, on Postgres, a JSON object containing | ||
| the given sub-object. | ||
| REGEX_MATCHES: The field is a string matching the regular | ||
| expression given as the value. | ||
| NOT_REGEX_MATCHES: The field is a string not matching the regular | ||
| expression given as the value. |
There was a problem hiding this comment.
🟡 Usability / Correctness / Documentation
REGEX_MATCHES/NOT_REGEX_MATCHES are documented simply as matching the regular expression. In memory they use re.match, which is anchored at the start and uses Python syntax. Postgres uses ~, which matches anywhere and uses POSIX syntax. This docstring already scopes EQUAL/NOT_EQUAL/CONTAINS to Postgres where the backends differ, so leaving regex out implies the two backends behave the same.
Impact: REGEX_MATCHES "bloggs" matches "joe.bloggs" on Postgres but not in memory, so tests and production disagree.
Suggestion: Either switch the in-memory converter to re.search, or document the difference and recommend anchoring patterns explicitly (^...) for portable results.
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Confirmed. Pattern "world" matches "hello world" on Postgres (~, postgres/query.py:254-255) but not in memory (re.match). The Postgres unit tests use "world$", which would only match in memory if the string started with "world".
The fix is only partial. re.search fixes anchoring, but Python re and Postgres AREs still differ in syntax: \b is a backspace in AREs (they use \y, \m, \M), and (?P<name>...) isn't supported. Safer wording would say patterns are anchored at the start in memory but unanchored on Postgres, so anchor explicitly and stick to the common subset.
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Fixed in 10d1b03: REGEX_MATCHES now says the expression must match from the start of the value in memory but can match anywhere on Postgres.
| async def register(self, subscriber: EventSubscriber[E]) -> None: | ||
| """Register a subscriber to receive event sources from the broker. | ||
|
|
||
| Subscribers should be registered before the broker is executed. |
There was a problem hiding this comment.
🟡 Usability
In the distributed broker, subscribers registered after start() go only into the local store and are never allocated a source. The call succeeds and nothing happens. Only the internal DefaultEventSubscriberManager docstring says this clearly.
Impact: A lazily registered consumer sits idle with no error or log.
Suggestion: Say "must", and state the consequence on this public method: "With the distributed broker, subscribers registered after execution starts are never allocated event sources." Consider warning or raising when register is called on a running broker.
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Confirmed, but only for the distributed broker. register only adds to the local store (distributed/broker.py:69-70). Shared state is written only in DefaultEventSubscriberManager.start() (subscribers/manager.py:94-103). Heartbeats never insert a missing subscriber: memory returns early (state/memory.py:92-93) and Postgres only runs an UPDATE (state/postgres.py:79-98).
The singleton broker re-lists subscribers every round (singleton/broker.py:95-96) and handles late registration fine, so the warning should name the distributed broker.
Two nuances:
- It isn't fully silent. Heartbeats debug-log the late subscriber as healthy, which is misleading.
- If the error handler retries
_do_execute,start()runs again and picks the subscriber up.
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Fixed in 10d1b03: register now says subscribers must be registered before execution, as the distributed broker never allocates sources to later ones.
| rather than by position, so pages remain consistent while records are | ||
| added or removed. Records are ordered by any sort clause in the query; | ||
| the Postgres implementation additionally orders by ID to break ties and, | ||
| when there is no sort clause, orders by ID alone. | ||
|
|
||
| With no `last_id`, the first `item_count` records are returned. With a | ||
| `last_id` and forwards direction, up to `item_count` records | ||
| immediately after that record are returned. With a `last_id` and | ||
| backwards direction, up to `item_count` records immediately before that | ||
| record are returned, still in sort order. The record with `last_id` is | ||
| itself excluded. | ||
|
|
There was a problem hiding this comment.
🔵 Correctness / Documentation / Usability
"With no last_id, the first item_count records are returned" holds on Postgres. The in-memory converter, however, returns an empty page for last_id=None with BACKWARDS, which contradicts its own new docstring. Separately, if the last_id record has been deleted, the result is an empty page rather than the next one, which undercuts "remain consistent while records are added or removed".
Suggestion: Either make the converters consistent, or document both edge cases: backwards paging without last_id returns nothing in memory, and an unknown or deleted last_id yields an empty page.
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Partly confirmed. With last_id=None and BACKWARDS, memory returns [] and Postgres returns the first page (verified: [] vs ['1', '2']).
Two corrections:
- The in-memory converter's own new docstring does document the empty page (
memory/converters/clause.py:192-194). What it contradicts is the publicKeySetPagingClausedocstring. - On Postgres, a deleted
last_idonly gives an empty page when there's a sort clause, because thelastCTE is then empty. Without a sort,id > %sstill returns the next page (postgres/converters/clause.py:274-299).
The comment also misses one divergence. If the query's filters exclude the last_id record, memory returns []. Postgres looks the record up in the unfiltered table (clause.py:208-225) and pages relative to it.
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Partly addressed in 10d1b03: dropped the "pages remain consistent while records are added or removed" promise. The edge cases themselves aren't documented, to keep the docstring concise.
| Raises: | ||
| ValueError: If the query is empty. |
There was a problem hiding this comment.
🔵 Correctness
to_fragment() always returns sql.SQL(" ").join(clauses), which is a Composed even when there are no clauses, so the case None branch is unreachable. An empty query is returned as empty SQL rather than raising.
Suggestion: Either remove the Raises: section, or make the code raise when no clauses were collected.
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Confirmed. Query().build() returns (Composed([]), []), which renders as ''. The case None and case _ branches (query.py:908-914) are unreachable.
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Fixed in 10d1b03: removed the unreachable Raises: section.
| """Count the projections matching a query. | ||
|
|
||
| Args: | ||
| search: The query to match. | ||
|
|
||
| Returns: | ||
| the number of matching projections. | ||
| """ |
There was a problem hiding this comment.
🔵 Correctness
Both adapters apply the whole search, including paging (len(await self._find_raw(search)) in memory, and COUNT(*) over the paged query on Postgres). With OffsetPagingClause(item_count=10), count returns at most 10.
Impact: Using the same query for find_many and count to show "page X of Y" gives a wrong total.
Suggestion: Say that paging is applied, and that callers should pass an unpaged query to get the total.
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Confirmed. Memory counts len(await self._find_raw(search)), and its converter applies paging (memory/converters/query.py:56-61). Postgres runs COUNT(*) over convert_query(search), which includes paging (postgres/converters/query.py:46-59).
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Fixed in 10d1b03: count now says any paging in the query is applied, so a paged query counts only that page.
| continue_execution: Exception types that should continue with a | ||
| value. |
There was a problem hiding this comment.
🔵 Correctness
continue_execution is typed ContinueExecutionTypeMappingValue[T], which is a mapping or None with no sequence form, because there is no default continuation value. The docstring says "Each argument is either a sequence of exception types ... or a mapping".
Suggestion: Make an exception for continue_execution and say it must come from continue_execution_type_mapping(...).
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Confirmed. error_handler_type_mappings(continue_execution=[ValueError]) raises TypeError: list indices must be integers or slices, not str at type_mapping_value["value_factory"] (error.py:182).
Two new comments on this function cover related problems: the precedence wording, and NotRequired keys that are actually required.
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Fixed in 10d1b03: the docstring now says continue_execution must be a mapping, from continue_execution_type_mapping.
| All combinations optionally accept an `error_handler`, defaulting to a | ||
| `RetryErrorHandler`. |
There was a problem hiding this comment.
🔵 Usability
error_handler defaults to a RetryErrorHandler with no strategy, which retries immediately and forever. Teams that accept the defaults get a busy loop against a failing dependency.
Suggestion: State the consequence where the default is described, and show how to add back-off (e.g. RetryErrorHandler(ConstantRetryStrategy(...))).
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Confirmed.
- Every broker layer defaults to
RetryErrorHandler()(distributed/broker.py:51,singleton/broker.py:52). - With no strategy, that handler retries every
Exception(error_handler.py:136-137). apply_error_handlingloops without sleeping when there's no wait (error.py:546-563).
The suggested RetryErrorHandler(ConstantRetryStrategy(...)) matches the real signatures.
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Fixed in 10d1b03: the default is now described as a RetryErrorHandler that retries immediately and indefinitely.
phelma
left a comment
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Docstring audit of 43d0fe3
Eight auditors each took one area of the commit (persistence, broker, consumers/locks, services, projection/query, sources/store adapters, store/testing, types/utils). Between them they checked every docstring the commit added or changed against the implementation, and ran experiments where a claim was testable (scratch scripts, plus a throwaway table in a local Postgres). A ninth auditor tried to disprove each finding in the earlier review. Every inline comment here is on a line this commit added.
The AST-only claim holds. With docstrings, pass and ... stripped, the only differences are attribute docstrings after type X = ... statements.
Results
- 37 new inline comments: 1 🔴, 9 🟡, 27 🔵. The 🔴 is
CONTAINS: the sub-object form fails on both backends, and memory and Postgres disagree for strings. - Earlier inline findings: each thread has a reply. 8 are confirmed, some with corrections to the suggested fixes. 2 are partly confirmed:
- In-memory lock: the double hold needs
wait_for_lock. The broker only usestry_lock, so broker coordination isn't affected. - Keyset paging: the in-memory docstring is accurate, and the deleted-
last_idcase only applies on Postgres with a sort clause.
- In-memory lock: the double hold needs
- Common themes in the new findings:
- Contracts on base classes and protocols that one implementation doesn't meet: scan ordering in memory, subscriber
add/heartbeat,Clock.now(tz=None). - Memory and Postgres diverging beyond what the PR description lists:
Noneversus missing keys, integerPathindices,CONTAINSon strings. Raises:sections that leave out the main exception (DeferredFuture.result,apply_error_handling), or describe one that can't happen (Query.build).
- Contracts on base classes and protocols that one implementation doesn't meet: scan ordering in memory, subscriber
Cross-check of the earlier general findings
| # | Finding | Verdict |
|---|---|---|
| G1 | Suspected bugs not flagged in public docstrings | Confirmed |
| G2 | processing/query/sources/persistence not rendered |
Confirmed. This is also why CallableService.from_maybe_callable (no return annotation) doesn't yet fail --strict |
| G3 | score_similarity divides by zero |
Partly. The bug is real, but the trigger is both inputs having no word characters, not being shorter than the n-gram size. Inline comment added |
| G4 | In-memory subscriber purge skips items |
Confirmed: 4 stale in, ['1', '3'] left. Inline comment added |
| G5 | Subscription apply atomic on Postgres but not in memory |
Confirmed. Postgres atomicity relies on the pool connection context committing or rolling back, which assumes the pool isn't autocommit |
| G6 | No docstring lint | Confirmed. Ruff D rules wouldn't catch the Returns: continuation problem, though. Only a griffe or mkdocs --strict check would |
| G7 | Uneven Type Parameters:/Example |
Confirmed. Low value |
| G8 | No changelog fragment | Confirmed. CONTRIBUTING.md asks for one |
Cross-check of the earlier additional findings
| File | Verdict |
|---|---|
retry_strategy.py:45 |
Accurate. Pointing to TypeMappingErrorHandler with retry_execution_type_mapping would answer "retry only X" |
settings.py:57 |
Accurate. A remedy (percent-encode credentials) would help |
projector.py:164 |
Confirmed. The README section exists but isn't on the docs site |
locks/postgres.py:55 |
Partly. This file is consistent ("PostgreSQL"). The mix is across files: about 5 "PostgreSQL" to 32 "Postgres" |
testing/data.py:146 |
Partly. This file is consistent ("id"). The id/ID mix is across files |
converter.py:10 |
Confirmed. Trivial |
error.py:350 |
Undercounted. Three summaries wrap: lines 350, 374 and 397 |
postgres/adapter.py:79 |
Confirmed. Minor |
Not verified
I couldn't confirm locally that check_paths: true fails the build on a missing snippet section, because pymdownx isn't installed in .venv.
| LESS_THAN: The field is less than the value. | ||
| LESS_THAN_OR_EQUAL: The field is less than or equal to the value. | ||
| IN: The field is one of the values in the given sequence. | ||
| CONTAINS: The field contains the value, for example a list |
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
🔴 Correctness
CONTAINS with a sub-object doesn't work on either backend:
- On Postgres, a dict value goes through
value_for_nested_path(postgres/converters/helpers.py:59-68) as a bareto_jsonb(%s)parameter, with noJsonbwrapper and no dict dumper registered. Against a real Postgres this givesProgrammingError: cannot adapt type 'dict' using placeholder '%s'. - In memory,
comparison_value in resolved_value(memory/converters/clause.py:91-92) raisesTypeError: unhashable type: 'dict'.
Strings also diverge. Memory does a substring test, while Postgres @> between two scalars is equality, so "world" doesn't match "hello world". The only behaviour the two backends share is a list field containing a single scalar element.
Suggestion: "CONTAINS: The field is a list containing the value, which must be a single scalar element." Alternatively, make the sub-object claim true by wrapping dict and list values in Jsonb in value_for_nested_path.
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Fixed in 10d1b03: CONTAINS is now just "The field is a list containing the value." The sub-object claim is gone.
| the right operand is the clause's value. | ||
|
|
||
| Attributes: | ||
| EQUAL: The field equals the value. On Postgres, a value of `None` |
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
🟡 Correctness
The None difference is attributed to the wrong thing. Memory also matches a null field with None, through plain == (memory/converters/clause.py:77-80). The real difference is missing nested keys. Postgres turns None into IS NULL on jsonb_extract_path_text (postgres/converters/clause.py:49-53), which matches both JSON null and a missing key. Memory never matches a missing key (MissingNestedPathError → False). Verified: EQUAL None matched ['2', '3'] (null and missing) on Postgres and ['2'] in memory.
Suggestion: "EQUAL: The field equals the value. A value of None matches a null field; on Postgres it also matches a missing nested key, whereas in memory a record missing a nested key never matches." Reword NOT_EQUAL the same way.
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Fixed in 10d1b03: dropped the "on Postgres" qualifier; a value of None matches a null field. The missing-key difference is left out as too fine-grained.
|
|
||
| Args: | ||
| top_level: The name of the top-level attribute. | ||
| *sub_levels: The keys or indices into the nested value. |
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
🟡 Correctness
Integer indices don't work on Postgres. Sub-levels are passed straight to jsonb_extract_path (postgres/converters/helpers.py:25-31), so Path("state", "tags", 0) fails with UndefinedFunction: function jsonb_extract_path(jsonb, unknown, smallint) does not exist. Postgres needs "0", but memory needs an int (memory/converters/types.py:70-71), so no form of index works on both backends.
Suggestion: "*sub_levels: The keys into the nested value. Integer list indices only work with the in-memory implementation; Postgres requires them as strings." Alternatively, stringify int sub-levels in the Postgres converter.
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Fixed in 10d1b03: *sub_levels are now described as keys only.
| ) -> JsonValue: | ||
| """Serialise the identifier to a JSON object. | ||
|
|
||
| The object has a `type` key naming the kind of identifier, plus a |
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
🟡 Correctness
CategoryPartitionIdentifier.serialise (identifier.py:167-170) returns only type and partition, so it drops category. Verified: CategoryPartitionIdentifier(category='c', partition=StreamNamePrefixPartitionIdentifier(value='p')).serialise() gives {'type': 'category-partition', 'partition': {...}}. The serialised form can't tell partitions of different categories apart, e.g. in a projection's source.
Suggestion: Ideally add "category": self.category to the code. If it stays as is, reword this to "plus keys for the identifier's fields" and note the omission on CategoryPartitionIdentifier.
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Not changed in the docstring: this is a code bug, to be fixed in code rather than documented.
| class EventSourceIdentifier(Identifier, ABC): | ||
| """Base class for identifiers of a source of events. | ||
|
|
||
| Built-in subclasses are `LogIdentifier`, `CategoryIdentifier` and |
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
🔵 Correctness
The list is incomplete. LogPartitionIdentifier (line 99) and CategoryPartitionIdentifier (line 150) also subclass EventSourceIdentifier.
Suggestion: "Built-in subclasses are LogIdentifier, LogPartitionIdentifier, CategoryIdentifier, CategoryPartitionIdentifier and StreamIdentifier."
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Fixed in 10d1b03: the list now includes LogPartitionIdentifier and CategoryPartitionIdentifier.
| class FilterClauseConverter[R: Identifiable](ClauseConverter[R, FilterClause]): | ||
| """Converts a `FilterClause` into a transformer that filters results. | ||
|
|
||
| Results missing a nested level of the clause's path never match. |
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
🔵 Correctness
"Never match" only holds for a missing dict key. _matches catches only MissingNestedPathError (line 73), which lookup_in_record raises only on KeyError (types.py:71-76). Other path failures abort the whole filter:
- An out-of-range list index raises
IndexError. Verified withPath("state", "a", 5)against{"a": [1]}. - A scalar part-way along the path raises
TypeError. Verified withPath("state", "a", "b").
The same imprecision is in lookup_in_record's Raises: (types.py:59).
Suggestion: Widen the except to (KeyError, IndexError, TypeError) in lookup_in_record. Otherwise say "Results whose nested value lacks a key along the clause's path never match."
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Not changed: too fine-grained for the docstring, which aims to stay concise.
| """Limits a query to a key-set page. | ||
|
|
||
| The query's existing sort is extended with `id` as a tie-breaker, or | ||
| `id` alone if there is none. For subsequent pages, the sort values of |
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
🔵 Correctness
Without an existing sort, the last CTE isn't used. Subsequent pages compare id > %s or id < %s directly with last_id (subsequent_page_no_sort_row_selection_query, lines 274-299). As a result, a non-existent last_id still returns rows in that case, while the CTE paths return none.
Suggestion: "For subsequent pages without an existing sort, id is compared directly with last_id. Otherwise, the sort values of the record with last_id are looked up in a common table expression named last and …"
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Fixed in 10d1b03: simplified the docstring to describe the paging at a high level, without the CTE details.
|
|
||
| Attributes: | ||
| RAISE: Raise a `MissingProjectionHandlerError`. | ||
| IGNORE: Skip the event, leaving the state unchanged. |
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
🔵 Correctness
IGNORE doesn't fully skip the event. project still calls update_metadata for an unhandled event (lines 242-244). Verified: a projector that counts events in its metadata gave count: 2 for one handled and one unhandled event.
Suggestion: "IGNORE: Leave the state unchanged for the event. update_metadata is still called for it during project."
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Fixed in 10d1b03: IGNORE is now just "Leave the state unchanged."
| of `initial_state_factory`. | ||
|
|
||
| Returns: | ||
| the new state, or the given state unchanged if there is no |
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
🔵 Correctness
When state is None, the unchanged value returned is the initial state from initial_state_factory (lines 205 and 256-260), not a "given state".
Suggestion: "…or the starting state unchanged if there is no handler and missing_handler_behaviour is IGNORE."
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Fixed in 10d1b03: it now says "the state unchanged".
| ](ProjectionStorageAdapter[ItemQuery, CollectionQuery]): | ||
| """A projection storage adapter that keeps projections in memory. | ||
|
|
||
| Projections are stored serialised to JSON values, so they are |
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
🔵 Correctness
Only state and metadata are serialised. source is kept as the identifier object (types/projection.py:139-145).
Suggestion: "Projection state and metadata are stored serialised to JSON values, so they are deserialised again on retrieval."
There was a problem hiding this comment.
Note
🤖 Claude Opus 5.5 responding on behalf of Phil Helm
Not changed: too fine-grained for the docstring, which aims to stay concise.
Cut or simplify claims that didn't match behaviour, fix Returns continuations that griffe split into separate items, and unwrap multi-line summaries.
There was a problem hiding this comment.
🟡 Changes recommended
The documentation overstates backward-pagination consistency across adapters and missing-path handling, since out-of-range sequence indices raise IndexError rather than exclude records.
2 open issues
What changed in this PR
This PR expands the event-store library’s API reference with docstrings and replaces the docs site’s outdated example with the README’s async example. It builds on #142’s documentation corrections without changing library runtime logic.
Changes:
- Documents API contracts, configuration, lifecycle behavior and extension points across the library.
- Reuses the README example through snippet markers to prevent documentation drift.
- Enables snippet-path validation in MkDocs; these site changes overlap with the replacement planned in #141.
| File | Description |
|---|---|
src/logicblocks/event/utils/klass.py |
Documents class-name formatting. |
src/logicblocks/event/utils/clock.py |
Documents clock and timezone behavior. |
src/logicblocks/event/types/string.py |
Documents string conversion protocols. |
src/logicblocks/event/types/projection.py |
Documents projection fields and conversion. |
src/logicblocks/event/types/json.py |
Documents JSON types, protocols and checks. |
src/logicblocks/event/types/identifier.py |
Documents identifiers and construction helpers. |
src/logicblocks/event/types/functions.py |
Documents converter and applier contracts. |
src/logicblocks/event/types/event.py |
Documents event fields and serialization. |
src/logicblocks/event/types/conversion.py |
Documents conversion rules and fallbacks. |
src/logicblocks/event/testing/data.py |
Documents random data generators. |
src/logicblocks/event/testing/builders.py |
Documents test builders and defaults. |
src/logicblocks/event/store/types.py |
Documents stream publish definitions. |
src/logicblocks/event/store/transactions.py |
Documents retry and suppression decorators. |
src/logicblocks/event/store/store.py |
Clarifies store access and async iteration. |
src/logicblocks/event/store/sources.py |
Documents stored-event memory sources. |
src/logicblocks/event/store/source_factories.py |
Documents source constructor registration. |
src/logicblocks/event/store/exceptions.py |
Documents unmet write conditions. |
src/logicblocks/event/store/conditions.py |
Documents conditional publishing. |
src/logicblocks/event/store/adapters/postgres/converters.py |
Documents Postgres constraints and enforcers. |
src/logicblocks/event/store/adapters/postgres/adapter.py |
Documents adapter configuration and lifecycle. |
src/logicblocks/event/store/adapters/memory/locks.py |
Documents multi-lock acquisition order. |
src/logicblocks/event/store/adapters/memory/db.py |
Documents snapshots and buffered transactions. |
src/logicblocks/event/store/adapters/memory/converters.py |
Documents memory constraints and enforcers. |
src/logicblocks/event/store/adapters/memory/adapter.py |
Documents memory storage and scan snapshots. |
src/logicblocks/event/store/adapters/base.py |
Defines storage adapter contracts. |
src/logicblocks/event/sources/memory.py |
Documents memory-source filtering. |
src/logicblocks/event/sources/factory/base.py |
Documents source factory contracts. |
src/logicblocks/event/sources/constraints.py |
Documents declarative query constraints. |
src/logicblocks/event/sources/constrained.py |
Documents delegated constraint behavior. |
src/logicblocks/event/sources/base.py |
Documents async source interfaces. |
src/logicblocks/event/query/utilities.py |
Documents nested query paths. |
src/logicblocks/event/query/queries.py |
Documents search and lookup queries. |
src/logicblocks/event/query/functions.py |
Documents similarity scoring. |
src/logicblocks/event/query/clauses.py |
Documents filtering, sorting and paging. |
src/logicblocks/event/projection/store/store.py |
Documents projection storage operations. |
src/logicblocks/event/projection/store/adapters/postgres.py |
Documents Postgres projection persistence. |
src/logicblocks/event/projection/store/adapters/memory.py |
Documents memory projection persistence. |
src/logicblocks/event/projection/store/adapters/base.py |
Defines projection adapter contracts. |
src/logicblocks/event/projection/projector.py |
Documents subclassing and projection lifecycle. |
src/logicblocks/event/processing/services/types.py |
Documents service execution and isolation modes. |
src/logicblocks/event/processing/services/status.py |
Documents service status tracking. |
src/logicblocks/event/processing/services/polling.py |
Documents polling and failure behavior. |
src/logicblocks/event/processing/services/manager.py |
Documents service registration and lifecycle. |
src/logicblocks/event/processing/services/error/retry_strategy.py |
Documents retry strategy behavior. |
src/logicblocks/event/processing/services/error/retry_strategy_decision.py |
Documents retry decisions. |
src/logicblocks/event/processing/services/error/error.py |
Documents error mappings and execution handling. |
src/logicblocks/event/processing/services/error/error_handler.py |
Documents error handler policies. |
src/logicblocks/event/processing/services/error/error_handler_decision.py |
Documents error handling decisions. |
src/logicblocks/event/processing/services/deferred_future.py |
Documents deferred results and exceptions. |
src/logicblocks/event/processing/services/callable.py |
Documents callable service wrapping. |
src/logicblocks/event/processing/process/multi.py |
Documents combined status precedence. |
src/logicblocks/event/processing/process/base.py |
Documents process status interfaces. |
src/logicblocks/event/processing/locks/postgres.py |
Documents advisory-lock lifetime. |
src/logicblocks/event/processing/locks/memory.py |
Documents event-loop-local locks. |
src/logicblocks/event/processing/locks/base.py |
Documents lock outcomes and acquisition contracts. |
src/logicblocks/event/processing/consumers/types.py |
Documents processing and acknowledgement contracts. |
src/logicblocks/event/processing/consumers/subscription.py |
Documents subscription consumers and factories. |
src/logicblocks/event/processing/consumers/state/types.py |
Documents consumer state conversion. |
src/logicblocks/event/processing/consumers/state/memory.py |
Documents sequence-number progress tracking. |
src/logicblocks/event/processing/consumers/state/base.py |
Documents consumer state persistence. |
src/logicblocks/event/processing/consumers/source.py |
Documents source consumption and commit behavior. |
src/logicblocks/event/processing/consumers/projection.py |
Documents incremental projection processing. |
src/logicblocks/event/processing/broker/types.py |
Documents subscriber identity and allocation contracts. |
src/logicblocks/event/processing/broker/subscribers/stores/instances/memory.py |
Documents in-memory subscriber storage. |
src/logicblocks/event/processing/broker/subscribers/stores/instances/base.py |
Documents subscriber store operations. |
src/logicblocks/event/processing/broker/strategies/singleton/factories.py |
Documents singleton broker factories. |
src/logicblocks/event/processing/broker/strategies/singleton/builder.py |
Documents singleton settings and construction. |
src/logicblocks/event/processing/broker/strategies/singleton/broker.py |
Documents local source distribution. |
src/logicblocks/event/processing/broker/strategies/distributed/subscriptions/stores/state/postgres.py |
Documents Postgres subscription state storage. |
src/logicblocks/event/processing/broker/strategies/distributed/subscriptions/stores/state/memory.py |
Documents memory subscription state storage. |
src/logicblocks/event/processing/broker/strategies/distributed/subscriptions/stores/state/base.py |
Documents subscription state contracts. |
src/logicblocks/event/processing/broker/strategies/distributed/subscribers/stores/state/postgres.py |
Documents Postgres subscriber state configuration. |
src/logicblocks/event/processing/broker/strategies/distributed/subscribers/stores/state/memory.py |
Documents memory subscriber state configuration. |
src/logicblocks/event/processing/broker/strategies/distributed/subscribers/stores/state/base.py |
Documents subscriber presence and heartbeat contracts. |
src/logicblocks/event/processing/broker/strategies/distributed/subscribers/manager.py |
Documents registration and heartbeat lifecycle. |
src/logicblocks/event/processing/broker/strategies/distributed/observer.py |
Documents allocation synchronization. |
src/logicblocks/event/processing/broker/strategies/distributed/factories.py |
Documents distributed broker dependencies. |
src/logicblocks/event/processing/broker/strategies/distributed/difference.py |
Documents allocation change calculation. |
src/logicblocks/event/processing/broker/strategies/distributed/coordinator.py |
Documents leadership and source distribution. |
src/logicblocks/event/processing/broker/strategies/distributed/builder.py |
Documents distributed settings and construction. |
src/logicblocks/event/processing/broker/strategies/distributed/broker.py |
Documents distributed broker lifecycle. |
src/logicblocks/event/processing/broker/factories.py |
Documents broker selection and factory arguments. |
src/logicblocks/event/processing/broker/base.py |
Documents broker registration requirements. |
src/logicblocks/event/persistence/postgres/types.py |
Documents connection and query aliases. |
src/logicblocks/event/persistence/postgres/settings.py |
Documents connection and table settings. |
src/logicblocks/event/persistence/postgres/query.py |
Documents SQL expressions and query building. |
src/logicblocks/event/persistence/postgres/converters/types.py |
Documents SQL converter interfaces. |
src/logicblocks/event/persistence/postgres/converters/query.py |
Documents SQL query conversion registries. |
src/logicblocks/event/persistence/postgres/converters/helpers.py |
Documents SQL path and value expressions. |
src/logicblocks/event/persistence/postgres/converters/function.py |
Documents SQL similarity conversion. |
src/logicblocks/event/persistence/postgres/converters/clause.py |
Documents SQL clause conversion. |
src/logicblocks/event/persistence/postgres/converters/appliers.py |
Documents sequential query transformations. |
src/logicblocks/event/persistence/memory/converters/types.py |
Documents result sets and path lookup. |
src/logicblocks/event/persistence/memory/converters/query.py |
Documents memory query conversion registries. |
src/logicblocks/event/persistence/memory/converters/helpers.py |
Documents transformer composition order. |
src/logicblocks/event/persistence/memory/converters/function.py |
Documents in-memory similarity calculations. |
src/logicblocks/event/persistence/memory/converters/clause.py |
Documents memory filtering, sorting and paging. |
src/logicblocks/event/persistence/converter.py |
Documents exact-type converter registration. |
README.md |
Adds markers around the reusable example. |
mkdocs.yml |
Enables snippet-path validation. |
docs/index.md |
Replaces the stale example with the README snippet. |
Review effort: Balanced
| class FilterClauseConverter[R: Identifiable](ClauseConverter[R, FilterClause]): | ||
| """Converts a `FilterClause` into a transformer that filters results. | ||
|
|
||
| Results missing a nested level of the clause's path never match. |
| With no `last_id`, the first `item_count` records are returned. With a | ||
| `last_id` and forwards direction, up to `item_count` records |
|
Closed in favour of #148, which combines the whole docs stack into one PR. |

Stacked on #142.
The docs site's only example predated the async API and no longer ran. And apart from
store, which had a handful, the library had no docstrings, so the API reference was just bare signatures.Changes
docs/index.mdnow pulls the README's basic example in throughpymdownx.snippets, between marker comments in the README, so the two can't drift apart.check_paths: truemakes the build fail if the snippet goes missing.processing,store,sources,projection,types,query,persistence,testingandutils). They cover the exported API in full: storage adapter contracts, projector subclassing, query clauses and paging, brokers, consumers, services and error handling. A few existing docstrings instoreare also corrected.Only docstrings changed. Comparing each file's AST with docstrings removed against the base shows no code changes; the only other lines that changed were
passand...placeholder bodies, which docstrings now replace.Checks
mkdocs build --strictpasses. Three newReturns:sections sat on methods with no return annotation, which griffe rejected in strict mode, so I rewrote them as one-line summaries.Notes
mkdocs.ymlanddocs/index.md, so it will conflict with the first commit. If Replace the Read the Docs site with Starlight on GitHub Pages #141 lands first, drop that commit. The docstrings are what its "separate docstrings effort" note refers to, and its generated reference will use them.timeout.microseconds, so whole seconds are lost and a 5s timeout becomeslock_timeout = 0, which means wait forever.start().REGEX_MATCHES,CONTAINS,Noneequality and some keyset paging edge cases.Created with Claude Opus 5.5 in Claude Code.