Skip to content

fix(query): counts of projected reads work, and sort keys may repeat partition key fields - #125

Merged
kalaspuff merged 27 commits into
mainfrom
issues-stack/10-query-counts-and-shared-keys
Oct 31, 2026
Merged

kalaspuff merged 27 commits into
mainfrom
issues-stack/10-query-counts-and-shared-keys

Conversation

@fctl-sh

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

Copy link
Copy Markdown
Contributor

What and why

Three query problems:

  • count() of a projected read always failed: it dropped the projection expression but kept the attribute names it had registered, so Note.query(client, user_id="u1").project(Note.text).count() raised ValidationException: Value provided in ExpressionAttributeNames unused in expressions, and a scan without other expressions "ExpressionAttributeNames can only be specified when using expressions". table.query(...).project("text").count() failed the same way. A count now reads without the projection.
  • scan().after(cursor).segments(n).count() applied one segment's cursor to every segment and returned a wrong number (35 for 40 items). It now raises TypeError, as iterating such a scan already does.
  • query() (and so count()) refused sort keys that repeat a field of the partition key: with pk="ORG#{org_id}" and sk="MEMBER#{org_id}#{user_id}", Membership.get(client, org_id="o1", user_id="u1") worked but Membership.query(client, org_id="o1", user_id="u1") raised ValueError: ... unexpected arguments user_id, because the partition key had consumed org_id; the same for index keys such as "STATUS#{status}" and "{status}#{placed_at}". The sort key now takes its fields from all the arguments, when at least one of them is not the partition key's, so query(org_id="o1") still reads the whole partition.

Verified with integration tests on the in-memory backend and MiniStack, which fail without the fix: model and table queries and scans with .project(...) count, a parallel scan after a cursor raises, and table and index queries whose sort key repeats a partition key field return and count the selected items. make check passes.

Fixes #85

Checklist

  • Tests cover the change (in-memory backend and MiniStack)
  • Docs updated (reading and single-table guides, changelog)
  • make check passes locally (lint, types, clippy, consistency, tests)
  • Breaking change? No

fctl session


Note

Low risk. It fixes read paths in the Python query layer (count() and the sort key selection of query()), which only accept more calls than before; the one new failure is a TypeError for a parallel scan count that used to return a wrong number.

What it does. count() of a projected query or scan no longer sends the projection's attribute names without a projection expression, so it stops failing with a ValidationException; a count simply ignores the projection. query() now builds the sort key from all the given arguments when at least one of them is not a partition key field, so a sort key template that repeats a partition key field (such as MEMBER#{org_id}#{user_id} after ORG#{org_id}) can be selected, for the table and for indexes. Integration tests, guides and the changelog are updated.

New TypeError. scan().segments(n).after(cursor).count() now raises TypeError, as iterating such a scan already does, instead of applying one segment's cursor to every segment and returning a wrong number.

fctl review's first look at ef958e8 · 6 files, +83 −10 · Review agent settings

fctl-sh Bot and others added 18 commits October 31, 2026 00:34
…s with their defaults

Pydantic reads getattr(cls, name) for every field while it builds a
class, inherited ones included, and took the base's FieldPath (the class
attribute of each field) as the default of the inherited field. Required
inherited fields became optional, create() failed with "expected int,
got FieldPath", to_item() returned paths, and items without an inherited
attribute could not be read. Redeclaring an inherited field warned that
it "shadows an attribute in parent".

PydanticModel now uses a subclass of pydantic's metaclass that hides the
paths from class access while pydantic builds a class, so pydantic
copies the base's fields, as it does for plain models.

Fixes #114

Co-authored-by: Carl Oscar Aaro <[email protected]>
… field stores them

FieldPath.contains built a Path whose encoder was the element codec,
and Path.contains took that codec's element() again, which is None for
datetimes, dates, UUIDs, timedeltas, plain enums and documents. The
value went into the expression unencoded, and every request with it
failed with "cannot store a value of type datetime" before any I/O.

contains() now validates and encodes the value with the element codec,
as comparisons do with the field's codec.

Fixes #112

Co-authored-by: Carl Oscar Aaro <[email protected]>
The binding deduplicated number sets with Vec::contains for each
element, so set(range(60_000)) took 3 s to convert, with the GIL held
on the event loop's thread. The core's duplicate check of sets, set
equality and the ADD and DELETE of set elements in the in-memory
DynamoDB were quadratic too: a put of that set took 10 s on the memory
backend, an ADD 3 s and a DELETE 4.6 s.

Number is canonical and hashable, so all of them now use hash sets:
13 ms for the conversion, 40 ms for the put, about 20 ms for ADD and
DELETE.

Fixes #94

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

Python merged 59_999.0 with 59_999 and Decimal(0) with 0 before the
conversion, so the 60,000-element set never reached the deduplication
with a duplicate. Floats and Decimals of the same tenths stay apart in
Python and are one number in DynamoDB.

Co-authored-by: Carl Oscar Aaro <[email protected]>
…metrics they ask for

batch_write_item and transact_write_items accept
return_item_collection_metrics=True, the core asks for and parses the
metrics, and the in-memory DynamoDB computes them, but the binding built
the output dicts without them and the stub's TypedDicts left the key
out. Both outputs now carry item_collection_metrics, a list of metrics
per table, as put_item, update_item and delete_item carry theirs.

Fixes #95

Co-authored-by: Carl Oscar Aaro <[email protected]>
DynamoDB applies nothing of a request it refuses. The in-memory backend
set the billing mode, and created and backfilled a new global index,
before validating the rest of an UpdateTable request, so a later error
(an enabled stream enabled again, an unknown index) left those changes
applied. billing_mode=PROVISIONED without throughput left the table
provisioned without capacity, and every later UpdateTable failed the
same way. TagResource added the tags before checking the 50-tag limit.

Both now validate the whole request before they change the table.

Fixes #92

Co-authored-by: Carl Oscar Aaro <[email protected]>
SELECT pages of the in-memory backend continued at an offset into the
list of results (NextToken "offset:N"), so rows deleted before the
position made the next page skip rows and rows inserted before it were
returned again: a "select a page, delete it, continue" loop missed
items. LastEvaluatedKey was never set either.

NextToken now encodes the key of the last item the page evaluated (the
table key, and the index key for index reads), the page returns it as
last_evaluated_key, and the next page continues after that position in
the read's order, ORDER BY included.

Fixes #91

Co-authored-by: Carl Oscar Aaro <[email protected]>
…ld fail later

RetryPolicy validated timedelta delays but kept them unconverted, so
base_delay=timedelta(...) raised TypeError and two timedelta delays
made every client using the policy fail to connect. It now stores
float seconds. max_attempts, batch_concurrency, batch_max_rounds and
event_buffer accepted floats, bools and strings that failed at the
first call: they must be ints now, and retry= a RetryPolicy.

Durations past what Duration and Instant arithmetic hold (timeout=1e20,
base_delay=1e300, wait_until_active(timeout=1e19)) panicked in the
core; the core caps durations at about 31 years, which means no limit.
wait_until_active() and wait_until_deleted() take a timedelta too.

Fixes #89

Co-authored-by: Carl Oscar Aaro <[email protected]>
close() set the closed flag and closed the core before it drained the
async hooks, so a hook that used the client (an operation.failed hook
that writes an audit item) got ShutdownError. drain() gathered every
hook task: a hook that called close() waited for itself and never
finished, and a hook pending on another, closed event loop made close()
raise "The future belongs to a different loop" after the core was
closed.

close() now delivers the buffered events and waits for the hooks of the
current event loop, except the calling task, until none is left, and
only then closes the core. events.pending() lists those tasks, and
drain() waits for them with asyncio.wait, which does not cancel hooks
when drain() is cancelled.

Fixes #88

Co-authored-by: Carl Oscar Aaro <[email protected]>
…eanwhile count as existing

sync_with compared the names of key attributes only, so a table whose
key attributes have other types than the models passed ensure_tables()
and every write failed later with "Type mismatch for key". It now
compares the types of the table's and its indexes' keys, which the
description's attribute definitions hold.

create_tables(exist_ok=True) and ensure_tables() checked that a table
exists and then sent CreateTable: a table that another process created
in between raised ResourceInUseError. They now wait for that table and
treat it as existing.

Fixes #86

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

count() popped the projection expression but kept the attribute names
it had registered, so every count() of a projected read failed with
"Value provided in ExpressionAttributeNames unused in expressions". It
now counts the read without its projection. A parallel scan's count()
applied one segment's cursor to every segment; it raises TypeError now,
as iterating it does.

query() consumed the fields of the partition key before it looked at
the sort key, so a sort key template that repeats one of them
("MEMBER#{org_id}#{user_id}" under "ORG#{org_id}") could not be
selected and the arguments were refused. The sort key now takes them
from all the arguments, as get() does.

Fixes #85

Co-authored-by: Carl Oscar Aaro <[email protected]>
Hooks of other event loops add and discard tasks from their own
threads, and the GIL can switch while the comprehension runs, so
iterating the live set could raise 'Set changed size during iteration'.

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

create_from() also enables TTL after CreateTable, and a
ResourceInUseError from UpdateTimeToLive (a table still CREATING with
wait=False) was taken for a lost race: create_tables(exist_ok=True)
skipped the table and never enabled TTL. The handlers now check that
the error came from CreateTable.

Co-authored-by: Carl Oscar Aaro <[email protected]>
Base automatically changed from issues-stack/9-ensure-tables-key-types to main October 31, 2026 01:34
@kalaspuff
kalaspuff merged commit a8dfcea into main Oct 31, 2026
22 checks passed
@kalaspuff
kalaspuff deleted the issues-stack/10-query-counts-and-shared-keys branch October 31, 2026 01:49
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.

Queries: count() of projected reads fails, and sort key fields shared with the partition key are refused

1 participant