mirror of
https://github.com/comfyanonymous/ComfyUI.git
synced 2026-06-12 01:07:30 +08:00
* spec(assets): add cursor pagination params to GET /api/assets
Add 'after' query param and 'next_cursor' response field for keyset
pagination. Matches the cloud Go implementation (BE-893) so frontend
sees a unified contract across runtimes. Offset/limit remain as a
deprecated fallback.
* feat(assets): add cursor encode/decode helpers for keyset pagination
Port of cloud common/pagination/cursor.go. Wire format is base64url of
{"s", "v", "id"} JSON; times are Unix microseconds UTC to match
PostgreSQL timestamp precision.
Includes a byte-identity fixture pinned against the cloud Go wire
format so cross-runtime FE pagination can't silently drift.
* feat(assets): thread cursor through schemas, service, and query layer
list_assets_page accepts an opaque 'after' cursor and returns
next_cursor when more pages are available. The query applies a keyset
WHERE clause and a secondary ORDER BY id for deterministic tiebreak.
Cursor sort field is validated against the request sort, and a
last_access_time sort (OSS-only) falls back to offset/limit. Offset is
ignored whenever a cursor is supplied.
* feat(assets): wire cursor pagination through GET /api/assets handler
Adds integration tests for: full cursor walk, invalid-cursor 400,
sort/cursor mismatch 400, cursor-wins-over-offset, absent next_cursor
when no more results, and pagination stability across deletes.
* fix(assets): address cursor-review verified findings
- Mint next_cursor on every cursor-supported sort, not only when 'after'
was supplied. A first request (no 'after') previously returned
next_cursor=None, leaving cursor mode unreachable from a clean start.
- Over-fetch limit+1 so an exactly-full terminal page doesn't mint a
spurious cursor pointing at a phantom next page.
- Map crafted out-of-range microsecond cursors (OverflowError / OSError
in datetime construction) to 400 INVALID_CURSOR instead of leaking 500.
- Bump MAX_CURSOR_VALUE_LENGTH 256 -> 512 to match the AssetReference
name column max; without this, a long-named asset minted a cursor the
same server then refused on the next request. Cross-runtime byte
identity with cloud is unaffected because no cloud cursor ever carries
a value > 256 (cloud schema doesn't permit it).
- Return None from _encode_next_cursor when the boundary row carries a
NULL sort value (e.g. an Asset without size_bytes backfilled), instead
of silently encoding 0 and mis-positioning the keyset.
- Fix schemas_in.py comment so it matches actual handler behavior
(last_access_time + 'after' raises 400, does not fall back).
- Add AssetsApiError schema + 400 response to GET /api/assets in
openapi.yaml so generated clients know the INVALID_CURSOR envelope.
- Extend integration coverage: first-page mint, exact-multiple terminal
page, cursor walks for created_at/updated_at/size sorts, datetime
overflow surfaces as 400 not 500.
- Add unit coverage for datetime overflow and 512-char round-trip.
* feat(assets): bind cursor to sort order + Go-compat JSON escaping
Address three needs-judgment items from the cursor-review judge synthesis:
1. Cursor wire format now includes an "o" key carrying the sort
direction ("asc" / "desc") it was minted under. A request that
replays the cursor with a flipped `order` parameter is rejected
with 400 INVALID_CURSOR instead of silently walking the wrong
direction. Legacy cursors without "o" still decode (the binding
is best-effort until cloud mirrors the field — follow-up filed
separately).
2. JSON serialization now escapes `<`, `>`, `&`, U+2028, U+2029
to mirror Go's default `json.Marshal` behavior. Without this, an
asset name containing those characters produced different bytes on
Python vs cloud Go. The escaped form is what both runtimes emit.
3. Add direct query-layer tests for the keyset tiebreaker — the secondary
ORDER BY id branch was previously unexercised. Two scenarios: all
rows share a primary sort value, and mixed ties straddle page
boundaries. Both assert no row is dropped or duplicated across the
walk.
Wire-format note: Python cursors now differ from current cloud cursors
by exactly the "o" key. Cloud follow-up will bring the two back into
byte alignment.
* fix(assets): address bot review comments
- Soften offset param prose: it's not deprecated, just not preferred for
sequential walks. Random-access UIs (jump-to-page, item count displays)
legitimately still want offset, so dropping the 'deprecated' framing
rather than promoting it to a machine-readable deprecated:true flag.
- Add explicit HTTP status assertions before every json() / next_cursor
read in test_list_cursor.py so a failing request surfaces as an HTTP
error instead of a confusing KeyError on a 4xx/5xx body.
* feat(assets): require cursor o field, drop legacy permissive path
Cursor pagination hasn't shipped on either runtime yet — this PR is
still draft and cloud's mirror is just behind it — so there are no
legacy no-o cursors in the wild. Make o mandatory from day one
rather than landing permissive and tightening later.
decode_cursor now rejects any payload without o (or with a non-string
o) as malformed. CursorPayload.order becomes a required str. Tests
that constructed CursorPayload directly now pass order="desc";
test_legacy_cursor_without_order_accepted flips to
test_cursor_without_order_rejected.
* chore(assets): drop cross-repo prose from cursor comments
Strip prose references to sibling Go implementations and external
ticket IDs from cursor.py, the cursor tests, the keyset integration
tests, asset_management's sort-field comment, and the legacy
prompt_id alias comment. Pure docstring/comment scrub — no behavior
or wire-format changes. x-runtime: [cloud] field annotations in
openapi.yaml are unchanged; those are the spec's structural
cross-runtime convention, not internal references.
* test(assets): include 'o' in microsecond-boundary cursor payload
The boundary test was building a cursor without the required `o` key, so
decode failed on the missing-order branch before reaching the µs-overflow
path the test is asserting. Both paths return 400 INVALID_CURSOR so the
assertion passed for the wrong reason. Add `o` to the payload and matching
`order=` to the request so the decode reaches the intended branch.
* fix(assets): address ultrareview findings on cursor pagination
Six fact-checked findings from the multi-model review pass:
- Encoder/decoder length asymmetry: encode_cursor now rejects empty id,
oversized id (>128), oversized value (>512), and invalid order tokens
symmetrically with decode_cursor. Prevents the same server from minting
a cursor it then 400s on the next request (e.g. a filesystem-scanned
asset name >512 chars). The bad-order path now raises InvalidCursorError
(still subclasses ValueError) so route-layer handling stays uniform.
- Raw U+2028/U+2029 in cursor.py source: ripgrep treated those lines as
line-terminators, confirming the bytes were the actual separators. Any
editor save / autoformat / git tooling that normalizes invisibles would
silently break the encoder. Replaced with explicit
/
Python escape sequences.
- set(seen) == set(names) hid ordering regressions: a cursor walk that
dropped a row at a page boundary or returned duplicates could pass.
Reworked the assertion to (1) reject duplicates, (2) require full
coverage, and (3) assert strict positional order for size sort, the
only field with a clock-independent ordering.
- Flaky time.sleep(0.05) between inserts: Windows CI clock resolution is
~15ms, so back-to-back inserts under load could collide and exercise
the tiebreaker instead of the documented path. Removed the sleep and
let the strengthened assertion above carry coverage / no-duplicates,
with size sort carrying strict order.
- Cursor error envelope diverged from the rest of routes.py: cursor 400s
emitted {error: {code, message}} while every other 400 in the file
emits {error: {code, message, details}} via _build_error_response.
Switched to _build_error_response and added the details field to the
AssetsApiError schema in openapi.yaml.
- "Byte-identity fixtures" only checked substring containment, defeating
the test class's stated purpose of pinning the wire format. Switched
to exact-bytes equality against an inline expected payload string per
fixture, so any whitespace / key-order / escape drift fails loudly.
Also dropped Go / json.Marshal references from docstrings — the byte
format is the contract, not the runtime that mints it.
* fix(assets): cap cursors by encoded wire size, not just char count
Char-count guards on value/id can still let multibyte or escape-heavy
inputs blow past MAX_ENCODED_CURSOR_LENGTH once UTF-8 + escape expansion
+ base64url runs. A 512-character name of 'é' (2 bytes UTF-8) or '<'
(serializes to the 6-byte '<' escape) passes the char check, mints
a ~1500-byte cursor, then 400s when handed back on the next request.
Compute the final encoded form and reject it before returning if it
exceeds the wire cap. Adds regression tests for both inflation paths.
* refactor(assets): extract cursor JSON escaping helper; size wire cap above per-field caps
Addresses review feedback on cursor.py:
- Extract the inline escape chain into _apply_wire_compatible_json_escapes()
with a comment pinning it to the wire format's escape set, so the parity
intent is explicit rather than reading as an ad-hoc transform.
- Raise MAX_ENCODED_CURSOR_LENGTH to 8192 (comfortably above the ~5.2KB
worst-case the per-field caps can produce) and drop the mint-time length
guard. Encoder/decoder symmetry now holds by construction: the encoder
can't produce a cursor the decode path rejects, so there is no confusing
user-visible 'cursor too long' failure at mint time.
- Rewrite the two over-wire-cap tests to assert worst-case multibyte and
escape-heavy values mint and round-trip, instead of being rejected.
* refactor(assets): drop cross-runtime cursor escaping; cursors are opaque
The custom JSON escaping of <, >, &, U+2028, and U+2029 existed only to
keep the encoded cursor byte-identical with the Cloud implementation of
the same payload format. Cursors are opaque tokens, so byte-level
compatibility across implementations is not needed — plain json.dumps
output is sufficient. Remove the escaping helper and the byte-identity
test fixtures that pinned the wire format; keep round-trip coverage for
the affected characters.
---------
Co-authored-by: guill <jacob.e.segal@gmail.com>
214 lines
8.5 KiB
Python
214 lines
8.5 KiB
Python
"""Opaque keyset-pagination cursor for /api/assets.
|
|
|
|
Payload JSON uses short keys to keep the encoded length small:
|
|
|
|
{"s": <sort_field>, "v": <value>, "id": <id>, "o": <order>}
|
|
|
|
The `o` key binds the cursor to the sort direction it was minted under,
|
|
so replaying a `desc` cursor against an `asc` request fails with
|
|
``INVALID_CURSOR`` rather than silently walking the wrong direction.
|
|
`o` is mandatory on every payload — a cursor without it is rejected as
|
|
malformed.
|
|
|
|
Encoding is base64url with no padding. Cursors are opaque tokens: the
|
|
payload format is internal to this server, and clients must treat a
|
|
cursor as a black box handed back via `next_cursor`. No byte-level
|
|
compatibility with any other implementation is required.
|
|
|
|
Time values are serialized as Unix microseconds (UTC) — microsecond
|
|
precision is sufficient to round-trip the timestamps stored by the
|
|
database without rounding rows in the same millisecond bucket.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import json
|
|
from dataclasses import dataclass
|
|
from datetime import datetime, timezone
|
|
from typing import Iterable, Optional
|
|
|
|
|
|
class InvalidCursorError(ValueError):
|
|
"""Raised on a malformed, oversized, or unsupported-sort-field cursor.
|
|
|
|
Map to a 400 response with code ``INVALID_CURSOR`` at the handler.
|
|
"""
|
|
|
|
|
|
# Wire-format length caps. Cursors are user-controlled, so caps protect the
|
|
# decode path from oversized allocations and downstream SQL predicates from
|
|
# unbounded strings.
|
|
#
|
|
# MAX_CURSOR_VALUE_LENGTH is 512 to fit the `AssetReference.name` column max
|
|
# (`String(512)`) — otherwise a long-named asset would mint a cursor the same
|
|
# server then refuses on the next request.
|
|
#
|
|
# MAX_ENCODED_CURSOR_LENGTH is the decode-path guard, sized comfortably above
|
|
# the largest cursor the per-field caps can produce. Worst case is value + id
|
|
# at their caps with every character JSON-escaping to the six-byte `\uXXXX`
|
|
# form (control characters), which is ~5.2 KB once base64url-encoded. At 8192
|
|
# the encoder can never mint a cursor that exceeds it, so a freshly minted
|
|
# cursor always decodes on the next request and there is no user-visible
|
|
# "cursor too long" failure.
|
|
MAX_ENCODED_CURSOR_LENGTH = 8192
|
|
MAX_CURSOR_VALUE_LENGTH = 512
|
|
MAX_CURSOR_ID_LENGTH = 128
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class CursorPayload:
|
|
sort_field: str
|
|
value: str
|
|
id: str
|
|
order: str
|
|
|
|
|
|
_VALID_ORDERS = ("asc", "desc")
|
|
|
|
|
|
def encode_cursor(sort_field: str, value: str, id: str, order: str = "desc") -> str:
|
|
"""Encode a cursor payload as a base64url (no-padding) string.
|
|
|
|
`order` binds the cursor to the sort direction it was minted under so a
|
|
later request with a flipped `order` query parameter is rejected with
|
|
``INVALID_CURSOR`` rather than silently walking the wrong direction.
|
|
"""
|
|
if order not in _VALID_ORDERS:
|
|
raise InvalidCursorError(f"order must be one of {_VALID_ORDERS}, got {order!r}")
|
|
# Symmetric input validation: the encoder must reject anything the
|
|
# decoder rejects, or the same server will mint cursors it then 400s on
|
|
# the next request.
|
|
if not id:
|
|
raise InvalidCursorError("id must be non-empty")
|
|
if len(id) > MAX_CURSOR_ID_LENGTH:
|
|
raise InvalidCursorError("id exceeds maximum length")
|
|
if len(value) > MAX_CURSOR_VALUE_LENGTH:
|
|
raise InvalidCursorError("value exceeds maximum length")
|
|
payload = {"s": sort_field, "v": value, "id": id, "o": order}
|
|
raw = json.dumps(payload, separators=(",", ":"), ensure_ascii=False)
|
|
# No mint-time length guard is needed: the per-field caps above bound the
|
|
# encoded length well below MAX_ENCODED_CURSOR_LENGTH (see its definition),
|
|
# so the encoder can never produce a cursor the decode path would reject.
|
|
return base64.urlsafe_b64encode(raw.encode("utf-8")).rstrip(b"=").decode("ascii")
|
|
|
|
|
|
def encode_cursor_from_time(sort_field: str, t: datetime, id: str, order: str = "desc") -> str:
|
|
"""Encode a time-typed cursor at Unix microsecond precision.
|
|
|
|
Accepts an aware datetime (any timezone) and normalizes to UTC. Naive
|
|
datetimes are rejected so callers can't accidentally encode the local
|
|
wall-clock value of a UTC-stored timestamp.
|
|
"""
|
|
if t.tzinfo is None:
|
|
raise ValueError("encode_cursor_from_time requires an aware datetime")
|
|
micros = _datetime_to_unix_micros(t.astimezone(timezone.utc))
|
|
return encode_cursor(sort_field, str(micros), id, order=order)
|
|
|
|
|
|
def decode_cursor(
|
|
cursor: str,
|
|
allowed_sort_fields: Iterable[str],
|
|
expected_order: str | None = None,
|
|
) -> CursorPayload:
|
|
"""Parse an opaque cursor.
|
|
|
|
``allowed_sort_fields`` is the endpoint's accepted sort-field list — a
|
|
cursor carrying a field outside this set is rejected so a cursor minted
|
|
for one column can't be replayed against another (e.g. a ``created_at``
|
|
timestamp string compared against a ``name`` column).
|
|
|
|
``expected_order`` (``"asc"``/``"desc"``), when supplied, must match the
|
|
payload's ``o`` field. ``o`` is required on every payload; a cursor
|
|
missing it is rejected as malformed.
|
|
|
|
Passing no allowed fields rejects every cursor.
|
|
"""
|
|
if len(cursor) > MAX_ENCODED_CURSOR_LENGTH:
|
|
raise InvalidCursorError("cursor exceeds maximum length")
|
|
|
|
try:
|
|
# urlsafe_b64decode requires correct padding; we strip on encode, so
|
|
# restore the trailing '=' pad here.
|
|
padding = "=" * (-len(cursor) % 4)
|
|
raw = base64.urlsafe_b64decode(cursor + padding)
|
|
except (ValueError, base64.binascii.Error) as e:
|
|
raise InvalidCursorError(f"encoding: {e}") from e
|
|
|
|
try:
|
|
decoded = json.loads(raw)
|
|
except (json.JSONDecodeError, UnicodeDecodeError) as e:
|
|
raise InvalidCursorError(f"payload: {e}") from e
|
|
|
|
if not isinstance(decoded, dict):
|
|
raise InvalidCursorError("payload: expected object")
|
|
|
|
sort_field = decoded.get("s")
|
|
value = decoded.get("v")
|
|
id = decoded.get("id")
|
|
order = decoded.get("o")
|
|
|
|
if not isinstance(sort_field, str) or not isinstance(value, str) or not isinstance(id, str):
|
|
raise InvalidCursorError("payload: missing or non-string s/v/id")
|
|
|
|
if id == "":
|
|
raise InvalidCursorError("missing id")
|
|
if len(id) > MAX_CURSOR_ID_LENGTH:
|
|
raise InvalidCursorError("id exceeds maximum length")
|
|
if len(value) > MAX_CURSOR_VALUE_LENGTH:
|
|
raise InvalidCursorError("value exceeds maximum length")
|
|
|
|
if sort_field not in allowed_sort_fields:
|
|
raise InvalidCursorError(f"unsupported sort field {sort_field!r}")
|
|
|
|
if not isinstance(order, str):
|
|
raise InvalidCursorError("missing or non-string o")
|
|
if order not in _VALID_ORDERS:
|
|
raise InvalidCursorError(f"unsupported order {order!r}")
|
|
if expected_order is not None and order != expected_order:
|
|
raise InvalidCursorError(
|
|
f"cursor order {order!r} does not match request order {expected_order!r}"
|
|
)
|
|
|
|
return CursorPayload(sort_field=sort_field, value=value, id=id, order=order)
|
|
|
|
|
|
def decode_cursor_time(payload: Optional[CursorPayload]) -> datetime:
|
|
"""Parse a time-typed cursor value as Unix microseconds, returning UTC."""
|
|
if payload is None:
|
|
raise InvalidCursorError("nil cursor payload")
|
|
try:
|
|
micros = int(payload.value)
|
|
except ValueError as e:
|
|
raise InvalidCursorError(f"value is not a valid timestamp: {e}") from e
|
|
try:
|
|
return _unix_micros_to_datetime(micros)
|
|
except (OverflowError, OSError, ValueError) as e:
|
|
# Crafted out-of-range microseconds (e.g. > datetime.MAX_YEAR) blow up
|
|
# in fromtimestamp / datetime construction. Map to 400, not 500.
|
|
raise InvalidCursorError(f"value is out of representable range: {e}") from e
|
|
|
|
|
|
def decode_cursor_int(payload: Optional[CursorPayload]) -> int:
|
|
"""Parse a cursor value as a base-10 integer."""
|
|
if payload is None:
|
|
raise InvalidCursorError("nil cursor payload")
|
|
try:
|
|
return int(payload.value)
|
|
except ValueError as e:
|
|
raise InvalidCursorError(f"value is not a valid integer: {e}") from e
|
|
|
|
|
|
_EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
|
|
|
|
|
|
def _datetime_to_unix_micros(t: datetime) -> int:
|
|
"""Convert an aware UTC datetime to Unix microseconds (integer math)."""
|
|
delta = t - _EPOCH
|
|
return (delta.days * 86_400 + delta.seconds) * 1_000_000 + delta.microseconds
|
|
|
|
|
|
def _unix_micros_to_datetime(micros: int) -> datetime:
|
|
"""Convert Unix microseconds to a UTC datetime, preserving precision."""
|
|
seconds, micro_remainder = divmod(micros, 1_000_000)
|
|
return datetime.fromtimestamp(seconds, tz=timezone.utc).replace(microsecond=micro_remainder)
|