Skip to content

fix(audit): sort every ClickHouse find by a total order - #14635

Merged
abnegate merged 2 commits into
mainfrom
fix/audit-cursor-order
Oct 18, 2026
Merged

abnegate merged 2 commits into
mainfrom
fix/audit-cursor-order

Conversation

@abnegate

@abnegate abnegate commented Oct 18, 2026 •

Copy link
Copy Markdown
Member

What

Cursor paging through the ClickHouse audit adapter (/v1/activities/events on Cloud) skipped and repeated rows.

find() only emitted an ORDER BY when the caller passed one, and only appended the id tiebreak when a cursor was present:

  • No explicit order: page 1 had no ORDER BY at all (ClickHouse part-read order), page 2 filtered and sorted on id DESC. Page 2 was not "the rows after page 1".
  • orderDesc('time'): page 1 broke ties on time arbitrarily, the cursor page broke them on id, so rows sharing a timestamp were skipped or repeated.

find() now resolves a single total order for every non-random query, cursor or not: time DESC when none is given, always ending in id in the direction of the last column. That is the table's sort key (tenant, time, id), so ClickHouse can still read in order. orderRandom is unchanged. Every ordered column is also projected, so a row from a slim Query::select() can still be the next cursor.

total=false (the other half of the QA report) is not in this PR: the adapter has no notion of totals, and Cloud already honours total=false on /v1/activities/events since appwrite-labs/cloud#6595 (E2E testListEventsSkipsTheCountWhenTotalIsFalse).

Tests

Fixing layer (packages/audit):

Test Tier Before (origin/main) After
testCursorAfterWithoutOrderVisitsEveryLogOnce E2E (ClickHouse) FAIL: cursor-unordered-02, -00 returned twice PASS
testCursorAfterOnTiedOrderVisitsEveryLogOnce E2E (ClickHouse) FAIL: cursor-tied-08, -10 never returned PASS
testCursorBeforeWithoutOrderReturnsThePreviousPage E2E (ClickHouse) FAIL: back page 07,06,05 instead of 01,03,05 PASS
testFindWithoutOrderReturnsNewestFirst E2E (ClickHouse) FAIL: older, newer PASS
testFindWithoutOrderSortsNewestFirstWithIdTiebreak unit (SQL) FAIL: no ORDER BY PASS
testFindAppendsIdTiebreakToTheRequestedOrder unit (SQL) FAIL: ORDER BY time ASC only PASS
testFindCursorPageSortsByTheColumnsItComparesOn unit (SQL) FAIL: compares/sorts on id only PASS
testFindCursorBeforeFlipsTheDefaultOrder unit (SQL) FAIL PASS
testCursorFromASlimProjectionPagesWithoutAnOrder E2E (ClickHouse) FAIL on 405a72d: Cursor is missing required attribute 'time' (review finding) PASS
testFindProjectsTheOrderColumnsASlimSelectLeavesOut unit (SQL) FAIL on 405a72d PASS
testFindKeepsAnExplicitIdOrder, testFindRandomOrderHasNoTiebreak unit (SQL) PASS PASS (guards)

Local runs: unit 93/93, ClickHouse E2E 80/80, bin/monorepo check audit clean.

The API-level E2E of the symptom lives in Cloud (ListEventsCustomServerTest), which owns the only ClickHouse-backed list route; it lands with the Cloud bump.

🤖 Generated with Claude Code

Cursor paging over /v1/activities/events skipped and repeated rows. The
ClickHouse adapter only added an ORDER BY when the caller passed one, and
only appended the `id` tiebreak when a cursor was present. The first page of
an unordered list therefore came back in whatever order ClickHouse read the
parts, while the next page compared and sorted on `id DESC`; with an
explicit `orderDesc('time')` the first page broke ties on `time` arbitrarily
while the cursor page broke them on `id`. Either way the rows on page 2 were
not the rows after page 1.

find() now resolves one order for every non-random query, cursor or not:
newest first (`time DESC`) when none is given, always ending in `id` in the
direction of the last column. That matches the table's sort key
(tenant, time, id), so ClickHouse can still read in order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@luxor-code-review

luxor-code-review Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

Review complete. No issues found — approved ✅.


The change is purely additive test coverage for the audit ClickHouse adapter's cursor-based keyset pagination and ordering guarantees.

Files Change
packages/audit/src/Adapter/ClickHouse.php Unchanged; the tests verify its existing resolveOrder(), buildCursorWhere() and random-order contracts.
packages/audit/tests/Adapter/ClickHouseTest.php Adds unit tests asserting the generated SQL for cursor WHERE clauses, ORDER BY construction (including the id tiebreaker), and ORDER BY rand() behavior.
packages/audit/tests/E2E/Adapter/ClickHouseTest.php Adds e2e tests walking cursor pagination against real ClickHouse, covering forward/backward cursors and default time DESC ordering.

Reviewed commit: 405a72d

@ghost

ghost commented Oct 18, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The incremental projection change preserves the sort keys needed for cursor paging, and I found no defects in the new changes.

ClickHouse audit find() now uses a deterministic total order for every non-random query, defaulting to newest-first and appending an ID tiebreaker where needed. The adapter also includes sort columns in slim projections so returned rows remain usable as cursors, with SQL and ClickHouse pagination regression coverage.

Latest changes: The new commits add resolved sort columns to slim SELECT projections and add unit and E2E coverage for paging from those projected rows.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 3
File Change
packages/audit/src/Adapter/ClickHouse.php Resolves the effective order before building the projection and includes its columns in slim SELECT results.
packages/audit/tests/Adapter/ClickHouseTest.php Asserts that a slim projection includes the resolved ordering columns.
packages/audit/tests/E2E/Adapter/ClickHouseTest.php Covers cursor paging through a slim projection with no explicit order.

Reviewed the commits since 405a72d · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · See the inline comments. Summary

@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

19 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (12)
  • php.appwrite.secret-compare-timing (5)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@github-actions

github-actions Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/audit-cursor-order (after).

Metric Before After Change
🚀 Requests/sec 198.15 205.46 ⚪ +3.7%
⏱️ Latency P50 87.64 ms 85.11 ms ⚪ -2.9%
⏱️ Latency P95 202.88 ms 189.56 ms 🟢 -6.6%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 85.11 189.56 12,768 205.46 -13.31
Account 150.84 279.13 672 11.12 -17.92
TablesDB 82.71 152.84 6,944 113.25 -15.49
Storage 78.82 179.04 3,360 57.07 +7.01
Functions 114.98 227.69 1,792 31.31 -2.75

Top API waits (after)

API request Max wait (ms)
functions.create 505.69
functions.variables.create 497.2
account.name.update 405.96
account.prefs.update 363.78
storage.buckets.create 349.57

The default order now sorts on `time`, so a row from a slim projection such
as Query::select(['event']) carried `id` but not `time`, and passing it to
cursorAfter() failed with "Cursor is missing required attribute 'time'".
find() now projects every column it orders by alongside the forced `id` and
`tenant`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Tier S · Looks good to merge. Summary

@abnegate
abnegate merged commit 5e4ceda into main Oct 18, 2026
643 of 650 checks passed
@ChiragAgg5k ChiragAgg5k mentioned this pull request Oct 21, 2026
6 tasks
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