Skip to content

fix(api): page the public anchor listing on (created_at, id), not created_at alone - #9733

Merged
JSONbored merged 1 commit into
JSONbored:mainfrom
shin-core:fix/ledger-anchor-cursor-keyset-9715
Jul 29, 2026
Merged

fix(api): page the public anchor listing on (created_at, id), not created_at alone#9733
JSONbored merged 1 commit into
JSONbored:mainfrom
shin-core:fix/ledger-anchor-cursor-keyset-9715

Conversation

@shin-core

Copy link
Copy Markdown
Contributor

What & why

Closes #9715.

GET /v1/public/decision-ledger/anchors is the public listing that makes anchoring's own health a
publicly checkable fact. But loadPublicLedgerAnchors's keyset cursor didn't match its sort key: it
filtered WHERE created_at < ? while ordering BY created_at DESC, id DESC. Because the ORDER BY
tiebreaks on id but the WHERE filtered on created_at alone, any group of rows sharing one
created_at that straddled a page boundary was silently skipped — the next page started strictly
before that timestamp, so the tied remainder was never returned on any page.

Ties are real, not hypothetical: recordLedgerAnchorAttempt defaults createdAt to nowIso()
(millisecond precision) and one scheduler tick records an attempt per backend, so several rows land on
the same created_at. An attempt — including a failure, the row this endpoint exists to surface —
could be permanently unreachable through the paginated API while sitting in the table.

Change

  • WHERE becomes the standard row-comparison keyset predicate:
    (created_at < ? OR (created_at = ? AND id < ?)), preserving ORDER BY created_at DESC, id DESC.
  • nextBefore now encodes both (created_at, id) as one opaque created_at|id string. The field
    stays a single string | null, so the route and published response shape are unchanged for a caller
    that only round-trips the value.
  • An unparseable before is treated as "no cursor" (first page), never throws — this is an
    unauthenticated public route.
  • The LedgerAnchorListFilter.before doc comment is updated (it no longer means "strictly older than
    this ISO timestamp").
  • The single prepared statement and the fetch-one-extra-row limit + 1 technique are unchanged, per
    the issue's required pattern.

Validation

  • Regression test: four rows sharing one created_at, paged in 2s — asserts all four are
    reachable across page boundaries (was silently dropping the tied remainder before).
  • Unparseable/|-malformed before values fall back to the first page rather than throwing.
  • Existing newest-first pagination + cursor-advance tests still pass unchanged.
  • Bug-catch verified: reverting the predicate to created_at < ? fails the tie regression test.
  • 100% patch coverage on every changed line and branch.

…ated_at alone

loadPublicLedgerAnchors's keyset cursor filtered `WHERE created_at < ?` while
ordering `BY created_at DESC, id DESC`. Because the ORDER BY tiebreaks on id but
the WHERE filtered on created_at alone, any group of rows sharing one created_at
that straddled a page boundary was silently skipped -- the next page started
strictly before that timestamp, so the tied remainder was unreachable on any page.

Ties are real: recordLedgerAnchorAttempt defaults createdAt to nowIso()
(millisecond precision) and one scheduler tick records an attempt per backend, so
several rows land on the same created_at. An attempt -- including a failure, the
row this public health endpoint exists to make observable -- could therefore be
permanently unreachable through the paginated API while sitting in the table.

Make the cursor match the sort key: the WHERE clause becomes the standard
row-comparison form `(created_at < ? OR (created_at = ? AND id < ?))`, and
nextBefore now encodes both (created_at, id) as one opaque `created_at|id` string.
The field stays `string | null`, so the route and published response shape are
unchanged for a caller that only round-trips the value. An unparseable `before`
falls back to the first page rather than throwing, since this is a public route.
The single prepared statement and the fetch-one-extra-row limit+1 technique are
unchanged.

Closes JSONbored#9715
@shin-core
shin-core requested a review from JSONbored as a code owner July 29, 2026 05:20
@superagent-security superagent-security Bot added the contributor:flagged Contributor flagged for review by trust analysis. label Jul 29, 2026
@superagent-security

Copy link
Copy Markdown
Contributor

🚨 Contributor flagged. Click here for more info: Superagent Dashboard

@loopover-orb

loopover-orb Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Warning

⏸️ LoopOver review result - manual review recommended

Review updated: 2026-07-29 05:30:25 UTC

2 files · 1 AI reviewer · no blockers · CI green · unstable

⏸️ Suggested Action - Manual Review

Review summary
This PR fixes a real keyset-pagination bug: `loadPublicLedgerAnchors` ordered by `(created_at DESC, id DESC)` but filtered only on `created_at < ?`, so rows sharing a `created_at` that straddled a page boundary were silently unreachable — exactly the scenario `recordLedgerAnchorAttempt`'s millisecond-precision `nowIso()` default produces when several backends are recorded in one scheduler tick. The fix switches to the standard row-comparison predicate `(created_at < ? OR (created_at = ? AND id < ?))` matching the ORDER BY, encodes both fields into the opaque `nextBefore` cursor, and treats an unparseable `before` as first-page rather than throwing on this unauthenticated route. `parseAnchorCursor`'s malformed-input handling (leading/trailing `|`, missing separator) is correct, and the regression test with four tied rows paged in twos is a real exercise of the previously-broken path, not a fabricated scenario.

Nits — 4 non-blocking
  • The composite predicate `(created_at < ? OR (created_at = ? AND id < ?))` can be harder for some query planners to use an index on efficiently than a tuple comparison; worth confirming (e.g. via EXPLAIN QUERY PLAN) that this still hits an index on `(created_at, id)` at the row counts this table will reach.
  • src/review/ledger-anchor-persistence.ts: the `id` component of the cursor is assumed never to contain `|` because it's a UUID — this is safe today but is an implicit invariant on `crypto.randomUUID()` worth a one-line assertion or at least a code comment pointer if the id generation ever changes.
  • Consider adding a test where the cursor's `id` portion doesn't correspond to any real row (e.g. cursor from a row that was since deleted) to confirm the predicate still behaves as a pure keyset comparison rather than requiring the cursor row to exist.
  • The CI 'Contributor trust' check failure has no detail attached and this branch is 1 commit behind the default branch — worth a rebase to rule out an unrelated pre-existing failure before merging.

Decision drivers

  • ✅ Code review — No blockers (1 reviewer)
  • ✅ Gate result — Passing (No configured blocker found.)
Context & advisory signals — never blocks the verdict
Signal Result Evidence
Linked issue ✅ Linked #9715
Related work ✅ No active overlap found No same-issue or scoped active PR overlap found.
Change scope ✅ 20/20 Low review scope from cached public metadata (1 linked issue).
Validation posture ❌ 5/25 Preflight is holding this PR: the review lane is unavailable, so it is not ready for automated review.
Contributor workload ✅ 10/10 Author activity: 38 registered-repo PR(s), 26 merged, 0 issue(s).
Contributor context ✅ Confirmed Gittensor contributor shin-core; Gittensor profile; 38 PR(s), 0 issue(s).
Improvement ✅ Minor risk: clean · value: minor
Linked issue satisfaction

Partially addressed
The core fix is solid — the cursor now encodes (created_at, id), the WHERE clause uses the correct row-comparison predicate, and a malformed `before` falls back to the first page — but the issue's explicit requirement of a test with five tied rows is not met (the diff's regression test uses only four), and there is no route-level test exercising `GET /v1/public/decision-ledger/anchors?before=<garb

Review context
  • Author: shin-core
  • Role context: outside_contributor
  • Public audience mode: oss maintainer
  • Lane context: Repository is registered but has no active allocation in the current snapshot.
  • Public profile languages: TypeScript, JavaScript, Solidity, Dart, Python, CSS, PHP, Rust
  • Official Gittensor activity: 38 PR(s), 0 issue(s).
  • PR-specific overlap: none found.
Contributor next steps
  • Start here: Await review-lane availability.
  • Then work through the remaining 1 step in the Signals table above.
Signal definitions
  • Related work = same linked issue, overlapping active PRs, or title/path similarity.
  • Change scope = cached public metadata such as size labels, draft state, and review-burden hints.
  • Validation posture = whether the PR provides enough public validation/test evidence for maintainer review.
  • Contributor workload = public contributor activity and cleanup pressure, not a repo-wide quality failure.
  • Contributor context = public GitHub/Gittensor identity context; non-Gittensor status is not a blocker.
🧪 Chat with LoopOver

Ask LoopOver a question about this PR directly in a comment — grounded only in the same cached, public-safe facts shown above, never a new claim.

  • @loopover ask &lt;question&gt; answers contribution-quality Q&A with source citations and freshness.
  • @loopover chat &lt;question&gt; answers in natural prose from cached decision-pack facts via local inference (maintainer/collaborator; read-only).
  • A plain-language @loopover mention with a real question is routed to the closest matching read-only command automatically — no exact syntax required.

Full command reference: https://loopover.ai/docs/loopover-commands

🧪 Experimental — new and may change.

Decision record
  • action: hold · clause: success
  • config: 99ca10c96b60fdd0e60d33ce4d2441d65a95cf6d30650d390d8a856ea7576afa · pack: oss-anti-slop · ci: passed
  • record: cbb01e74d57f65fd0b27dacc2ce450234c0720878333eb912075cf65d7ff14dd (schema v5, head 5a4d971)

🟩 Safe / merged · 🟦 Advisory · 🟨 Held for review · 🟥 Blocked / closed


💰 Earn for open-source contributions like this. Gittensor lets GitHub contributors earn for the work they already do — register to start earning →.

Checked by LoopOver, a quiet PR intelligence layer for OSS maintainers.

  • Re-run LoopOver review

@superagent-security

Copy link
Copy Markdown
Contributor

Superagent didn't find any vulnerabilities or security issues in this PR.

@codecov

codecov Bot commented Jul 29, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 76.53%. Comparing base (edf0883) to head (5a4d971).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #9733      +/-   ##
==========================================
+ Coverage   76.51%   76.53%   +0.01%     
==========================================
  Files         282      283       +1     
  Lines       59378    59421      +43     
  Branches     6542     6556      +14     
==========================================
+ Hits        45435    45478      +43     
  Misses      13661    13661              
  Partials      282      282              
Flag Coverage Δ
backend 100.00% <100.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/review/ledger-anchor-persistence.ts 100.00% <100.00%> (ø)

@loopover-orb loopover-orb Bot added the gittensor:bug Gittensor-scored bug fix — scores a 0.05x multiplier. label Jul 29, 2026
@loopover-orb

loopover-orb Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Held for manual review: the gate and required CI are green, but GitHub reports this pull request's mergeable state as unstable because a non-required check or status is not passing, so LoopOver will not auto-merge. A maintainer can resolve the failing check or review and merge manually. This is an automated maintenance action.

@loopover-orb loopover-orb Bot added the manual-review Gittensor contributor context label Jul 29, 2026
@JSONbored
JSONbored merged commit 0c67c5e into JSONbored:main Jul 29, 2026
7 of 8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

contributor:flagged Contributor flagged for review by trust analysis. gittensor:bug Gittensor-scored bug fix — scores a 0.05x multiplier. manual-review Gittensor contributor context

Projects

None yet

Development

Successfully merging this pull request may close these issues.

api(ledger): the public anchor listing's cursor drops rows that share a created_at

2 participants