Skip to content

fix(errors): errors pickle, so they cross process boundaries - #72

Merged
kalaspuff merged 20 commits into
fixes-stack/09-bounded-limitsfrom
fixes-stack/10-picklable-errors
Oct 30, 2026
Merged

kalaspuff merged 20 commits into
fixes-stack/09-bounded-limitsfrom
fixes-stack/10-picklable-errors

Conversation

@fctl-sh

@fctl-sh fctl-sh Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

What and why

dynamoxy's errors could not cross a process boundary. The native exception classes (ValidationError, ConditionalCheckFailedError, ThrottlingError and the rest of the tree in dynamoxy._core) were created with _core as their module, which cannot be imported. So pickle.dumps(dynamoxy.ValidationError("x")) failed with PicklingError: ... No module named '_core'. An error raised in a ProcessPoolExecutor worker, by multiprocessing or in a task queue reached the caller as a PicklingError, or broke the pool, and its type, code and message were lost: except dynamoxy.ConditionalCheckFailedError never matched. UnprocessedItemsError failed differently: unpickling calls the class with the message only, and its unprocessed argument was required. The Python-defined errors (ItemNotFoundError, VersionConflictError, ...) already pickled.

The native classes now name dynamoxy._core, where pickle finds them (PyO3 supports dotted module names). UnprocessedItemsError(message) builds an error with no unprocessed items, so unpickling restores the real ones. A ValidationError keeps the values that failed validation in its FieldErrors: a value that does not pickle (a function given as a field value, a lock) is left out of the pickle, and copies keep it. Every error pickles with its attributes: code, request id, retry classification, attempts, .item, and the model and key of model errors.

Verified with new unit tests that round-trip every native error class, real errors from the in-memory backend (a failed condition, ItemAlreadyExistsError, UniqueConstraintError, ThrottlingError after retries) and the Python-defined errors, comparing their attributes, plus a ValidationError for a function given as a field value. Also with the whole Rust and Python suites, clippy, ruff, pyrefly and the consistency checks.

Checklist

  • Tests cover the change (unit tests, with errors of real calls on the in-memory backend)
  • Docs updated (errors guide, changelog)
  • make check passes locally (lint, types, clippy, consistency, Rust and Python tests)
  • Breaking change? No: type(error).__module__ is now dynamoxy._core, where the classes live

fctl session


Note

Low risk. It changes only the module name the native error classes report, one constructor default and how a FieldError pickles, so the visible effect is that errors now pickle. Tracebacks and reprs show dynamoxy._core. in place of _core. for the native errors.

What it does. The native error classes (ValidationError, ConditionalCheckFailedError, ThrottlingError and the rest) were created with the unimportable module name _core, so pickling one failed. They now name dynamoxy._core, which pickle can import, and UnprocessedItemsError makes unprocessed optional so that unpickling, which calls the class with the message only, can rebuild it. A FieldError pickles its rejected value only when that value pickles, and leaves it out (None) otherwise, so a ValidationError for a function given as a field value still crosses process boundaries. New unit tests round-trip every native class, errors from real in-memory calls, the Python-defined errors and such a ValidationError.

Exception module name. type(error).__module__ for the native errors changes from _core to dynamoxy._core, which shows in tracebacks and reprs; nothing in the repository compares against the old name.

fctl review's first look at 0f8f36a · 5 files, +160 −25 · Review agent settings

fctl-sh Bot and others added 17 commits October 30, 2026 22:17
…e process

The conversions between Python values and DynamoDB values, the
expression parser and the PartiQL parser recursed without a bound. A
value with thousands of nested lists or maps, one that contains itself
(`item["self"] = item`), a crafted pagination cursor, or an expression
or statement with a few thousand nested parentheses exhausted the stack
and killed the interpreter with SIGSEGV. The parsers run for AWS
clients too: update expressions and PartiQL statements are parsed on a
runtime thread (2 MiB of stack) to decide whether a retry is safe, so a
3 KB UPDATE statement crashed the process before any request was sent.

- The binding stops at DynamoDB's limit of 32 nested levels and raises
  ValidationError with DynamoDB's message ("Nesting Levels have exceeded
  supported limits"), before any request. That also catches cycles.
- Both parsers refuse parentheses, NOT, functions and value brackets
  nested more than 100 levels deep with a ValidationException. DynamoDB
  refuses redundant parentheses and allows 300 operators, so only
  contrived expressions nest that deep. Parentheses are now handled
  next to NOT, which keeps the large frame of the comparison parser off
  the recursion: 400 levels fit in a debug build's 2 MiB stack, where
  200 did before, so the limit leaves a wide margin.

Co-authored-by: Carl Oscar Aaro <[email protected]>
The expression lexer reported an unexpected character with a span of
one byte, so a character outside ASCII (`größe > :v`, or a non-breaking
space pasted into `a = :v`) made the error message slice into the
middle of it and panic. In-memory calls raised an internal error, and
`_core._apply_update()` and `_core._check_expressions()` raised a
PanicException, which `except Exception` does not catch. AWS clients
failed the same way before sending UpdateItem, whose expression the core
parses to decide whether a retry is safe.

The span now covers the whole character: such expressions are syntax
errors (ValidationException), and AWS clients send them to DynamoDB.

Co-authored-by: Carl Oscar Aaro <[email protected]>
…ynamoDB does

Review fixes for the nesting limits:

- PartiQL statements longer than DynamoDB's 8,192 characters are
  refused (ValidationException). `a AND a AND ...` builds a nested
  condition tree without nesting, and dropping a 20,000-term chain
  overflowed the stack of a runtime thread, also for AWS clients,
  whose statements are parsed before sending.
- The elements of a set are no level of their own, as in DynamoDB: a
  set inside 31 lists is valid again. Only a set in a set is converted
  one level deeper, so nested frozensets stay bounded.
- decode_cursor() turns a RecursionError of the JSON parser (cursors
  nested about 20,000 levels deep, on Python 3.12 and 3.13) into
  "invalid cursor".

Co-authored-by: Carl Oscar Aaro <[email protected]>
…are unknown

After an attempt that may have been applied (a timeout, a lost
connection, a 5xx), a write whose later attempts were throttled until
the attempts ran out raised the last attempt's error, a ThrottlingError
or InternalServerError that says it is retryable. The repository's
write ids, which settle unknown outcomes, never ran: `create()` raised
ThrottlingError for an item it had stored, and the application's retry
raised ItemAlreadyExistsError. A transaction that was applied raised
TransactionInProgressError, and repeating it (with a new token) applied
it twice. The last attempt's own uncertainty was ignored too: a 5xx on
attempt 1 of an `ADD` raised WriteOutcomeUnknownError, on the last one a
retryable InternalServerError.

The retry loop now records every attempt that may have been applied,
the last one included, and a write whose call ends without an answer
that settles the outcome (a retryable error, no response) raises
WriteOutcomeUnknownError. Transactions get the same rule; their later
answers are settled by the token. Reads are unchanged.

close() also refused the retries of calls in progress, so a write whose
first attempt may have been applied raised ShutdownError. Calls in
progress now finish their retries, as the core's close() documented;
new calls are refused.

Co-authored-by: Carl Oscar Aaro <[email protected]>
…aved

A loaded instance whose item was stored without a version (written
before the model gained `version()`) has version None. save() treated
it like a new instance and required `attribute_not_exists(pk)`, so it
failed with an unexplained ConditionalCheckFailedError every time, after
refresh() too, and so did tx.save().

save() of such an instance now requires that the item still exists
without a version, and stores version 1. When another writer saved it
first, or deleted it, the call raises VersionConflictError ("stored
version 1, expected no version", "deleted after it was loaded"). The
conflict messages now say "expected version 1".

Co-authored-by: Carl Oscar Aaro <[email protected]>
…nt fields

A member of a `(str, Enum)` or `(int, Enum)`, the mixins of code
written before StrEnum and IntEnum, passed the validation of a str, int
or Literal field and was kept as it was. The item stored its value
(`"book"`), but key templates, derived index keys and unique guards
rendered its str(), which is "Kind.BOOK" for such enums. The item got
the key `KIND#Kind.BOOK#s1`: reads by the value missed it, the loaded
instance rendered `KIND#book#s1` so its save() raised "key changed",
and a unique value written as "book" was not taken.

The str and int codecs now return the plain str or int a subclass holds,
and the Literal codec the literal a value matches, so instances,
templates, guards and conditions use what DynamoDB stores.

Co-authored-by: Carl Oscar Aaro <[email protected]>
…of items

When dynamoxy's own filters (the entity type, guard items) or client
checks (a templated sort key prefix that where() replaced) removed items
from a page, the next request asked for four times as many, without a
bound. After about 16 such pages in a row (16 MB of other entities in a
shared table), the Limit no longer fit the request's unsigned 32-bit
integer, and first(), exists(), limit() and iteration raised
OverflowError. `limit(n)` with n above that raised it at once.

Requests now ask for at most 1,048,576 items, more than a 1 MB page
can hold, so the page size bounds them as before.

Co-authored-by: Carl Oscar Aaro <[email protected]>
…s too

`Literal[Kind.BOOK, Kind.CD]` with `class Kind(str, Enum)`: the Literal
codec returned the declared member, whose str() is "Kind.BOOK", so
templates and guards rendered it again, now also for items read back.
It returns the plain str or int of the literal a value matches.

Co-authored-by: Carl Oscar Aaro <[email protected]>
The native exception classes (ValidationError, ConditionalCheckFailedError,
ThrottlingError, ...) were created with the module `_core`, which is not
importable: pickling one raised PicklingError ("No module named
'_core'"). An error raised in a ProcessPoolExecutor worker, by
multiprocessing or in a task queue reached the caller as a PicklingError
or broke the pool, so `except dynamoxy.ConditionalCheckFailedError` never
matched. UnprocessedItemsError required its keyword argument, which
unpickling does not pass.

The native classes now name `dynamoxy._core` (where pickle finds them),
and UnprocessedItemsError's `unprocessed` defaults to an empty list; both
pickle with their attributes.

Co-authored-by: Carl Oscar Aaro <[email protected]>
@fctl-sh

fctl-sh Bot commented Oct 30, 2026

Copy link
Copy Markdown
Contributor Author

Stack of 5 open pull requests (from a pass over the library for bugs; #61 to #65 are merged already), merged in this order with "Squash and merge":

  1. fix(client): writes whose retries run out after an uncertain attempt are unknown #67 fix(client): writes whose retries run out after an uncertain attempt are unknown
  2. fix(repository): items stored before the model had a version can be saved #68 fix(repository): items stored before the model had a version can be saved
  3. fix(models): members of mixin enums are the plain values of str and int fields #69 fix(models): members of mixin enums are the plain values of str and int fields
  4. fix(query): requests of growing reads ask for at most a page's worth of items #70 fix(query): requests of growing reads ask for at most a page's worth of items
  5. fix(errors): errors pickle, so they cross process boundaries #72 fix(errors): errors pickle, so they cross process boundaries ← this pull request

The findings that are not fixed here are filed as issues (see the next comment on #72).

@fctl-review

This comment has been minimized.

Comment thread tests/unit/test_errors.py Resolved
fctl-sh Bot and others added 3 commits October 30, 2026 21:43
…lable-errors

# Conflicts:
#	CHANGELOG.md
#	python/dynamoxy/query.py
#	tests/integration/test_repository.py
#	tests/integration/test_single_table.py
A ValidationError keeps the values that failed validation in its
FieldErrors, so one raised for a function or a lock given as a field
value still failed to pickle. FieldError's pickle now leaves out a value
that does not pickle; copies keep it.

Co-authored-by: Carl Oscar Aaro <[email protected]>
This was referenced Oct 30, 2026
@fctl-sh

fctl-sh Bot commented Oct 30, 2026

Copy link
Copy Markdown
Contributor Author

The findings of this review that are not fixed in the stack are filed as issues, by priority: #102

@kalaspuff
kalaspuff added this pull request to stack #71 October 30, 2026 21:55
@kalaspuff
kalaspuff merged commit abc07e3 into main Oct 30, 2026
23 checks passed
@kalaspuff
kalaspuff deleted the fixes-stack/10-picklable-errors branch October 30, 2026 22:08
kalaspuff added a commit that referenced this pull request Oct 31, 2026
## Summary

The error classes raised by the Rust core (`AccessDeniedError`,
`ThrottlingError`, `ValidationError`, `ResourceNotFoundError`, …) are
the same classes `dynamoxy.errors` exports, so `except
dynamoxy.errors.AccessDeniedError` already caught them, but they named
the native module as theirs: tracebacks showed `_core.AccessDeniedError`
(`dynamoxy._core.AccessDeniedError` since #72) while the Python-defined
errors showed `dynamoxy.errors.ItemAlreadyExistsError`. They now name
`dynamoxy.errors`, so a failed call without valid credentials ends in
`dynamoxy.errors.AccessDeniedError: ListTables failed:
UnrecognizedClientException: …`. `dynamoxy.errors` re-exports every
native class, so `pickle` finds them there, and pickles written with the
old module name still load because `dynamoxy._core` keeps the classes.

Verified with the unit test that round-trips every native error class,
which now also checks its module, that `dynamoxy.errors` holds that very
class, and the traceback line; by calling `list_tables()` on AWS with
invalid credentials; and with `make check`.

## Worth confirming

- **Decision:** I changed the unreleased changelog entry of #72 (which
had moved the classes to `dynamoxy._core`) to say `dynamoxy.errors`,
rather than adding a second entry, since neither name has been released
after 0.3.0's `_core`.

[fctl session](https://app.fctl.sh/s/ses_01M691K3TWYC4YZ5T45RSXVXC1)

<!-- FCTL_REVIEW_SUMMARY -->
---

> [!NOTE]
> **Low risk.** It only changes the module name the native error classes
report; the classes, their hierarchy and `except` matching stay the
same. Pickles use the new module name, and old pickles still load
because `dynamoxy._core` keeps the classes.
>
> **What it does.** The error classes raised by the Rust core
(`AccessDeniedError`, `ThrottlingError`, `ValidationError`, and so on)
now name `dynamoxy.errors` as their module instead of `dynamoxy._core`.
Tracebacks then show `dynamoxy.errors.AccessDeniedError` like the
Python-defined errors, and `pickle` finds the classes in
`dynamoxy.errors`, which re-exports them. The unit test, the guide and
the unreleased changelog entry are updated to match.
>
> <sub>[fctl
review](https://app.fctl.sh/s/ses_01M691WJ8YAHPJRR358YV3G3RB)'s first
look at
[`40d85ad`](40d85ad)
· 4 files, +34 −25 · [Review agent
settings](https://app.fctl.sh/p/dynamoxy?tab=reviews)</sub>

<!-- /FCTL_REVIEW_SUMMARY -->

Co-authored-by: fctl-sh[bot] <343971779+fctl-sh[bot]@users.noreply.github.com>
Co-authored-by: Carl Oscar Aaro <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant