Skip to content
Source
Sign inSign up
TanStack/db

fix(db): includes orderBy ignored after optimistic update on child collection #1496

Closedcomet08(GitHub profile, opens in a new tab)wants to merge 2 commits intomain fromrefs/pull/1496/headopened

Closes #1444

🎯 Changes

When a child collection item is updated, the D2 graph emits a (-1, +1) pair. If the delete (-1) message arrives first, an accumulator entry is created with the old orderByIndex. The subsequent insert (+1) message updated value correctly but never updated orderByIndex — so the child collection's comparator kept using the stale positional index.

This caused incorrect sort order immediately after optimistic updates on child collections, with ordering only correcting itself after server confirmation.

The parent pipeline (accumulateChanges) already handled this correctly. This fix applies the same orderByIndex update logic to the child pipeline accumulator and the nested pipeline accumulator for consistency.

✅ Checklist

  • I have tested this code locally with pnpm test.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset.
  • This change is docs/CI/dev-only (no release).

Summary by CodeRabbit

  • Bug Fixes

    • Preserved orderBy sorting for included child collections when child rows are updated, preventing ordering from being lost or overwritten during aggregation.
  • Tests

    • Added coverage to verify included child ordering remains correct after both optimistic client-side changes and server-backed sync confirmation.
    1. Review Change Stack

      No actionable comments were generated in the recent review. 🎉

      ℹ️ Recent review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro

      Run ID: e3458caa-bc93-47eb-a1df-d76399cd1271

      📥 Commits

      Reviewing files that changed from the base of the PR and between b3952649acdeb83a5e4f708d4a05d8edbd91c47f and a455d493028513dd7ef6f91a0a0e79eb7183b395.

      📒 Files selected for processing (1)
      • packages/db/src/query/live/collection-config-builder.ts
      🚧 Files skipped from review as they are similar to previous changes (1)
      • packages/db/src/query/live/collection-config-builder.ts

      📝 Walkthrough

      Walkthrough

      This patch fixes a bug where orderBy is lost in included child collections during optimistic updates. It preserves orderByIndex during direct and nested include aggregation, adds a test covering optimistic and server-confirmed updates, and records the fix in a changeset.

      Changes

      OrderBy Preservation in Included Collections

      Layer / File(s)Summary
      OrderByIndex conditional assignment in includes
      packages/db/src/query/live/collection-config-builder.ts
      Keeps existing.orderByIndex when _orderByIndex is undefined in both includes output accumulation and nested includes buffer accumulation.
      OrderBy ordering validation test
      packages/db/tests/query/includes.test.ts, .changeset/twelve-jars-lead.md
      Adds a test that verifies included child ordering through optimistic updates and server confirmation, and documents the patch release and fix note.

      Estimated code review effort

      🎯 2 (Simple) | ⏱️ ~12 minutes

      Suggested reviewers

      • samwillis

      Poem

      🐰 I hopped through rows of tasky light, Where order hid then came to sight. A tiny guard kept ranks in line, Now child lists sort just fine. 🥕

      🚥 Pre-merge checks | ✅ 5
      ✅ Passed checks (5 passed)
      Check nameStatusExplanation
      Title check✅ PassedThe title clearly matches the bug fix for includes orderBy after optimistic child updates.
      Description check✅ PassedThe description includes the required Changes, Checklist, and Release Impact sections and is specific to the fix.
      Linked Issues check✅ PassedThe code and test changes address #1444 by preserving orderBy behavior for optimistic child and nested includes updates.
      Out of Scope Changes check✅ PassedThe PR stays focused on the bug fix, its regression test, and the required changeset with no unrelated changes.
      Docstring Coverage✅ PassedDocstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      ❤️ Share
      Comment `@coderabbitai help` to get the list of available commands.
    2. 🧹 Nitpick comments (1)
      packages/db/tests/query/includes.test.ts (1)

      5372-5451: ⚡ Quick win

      Add a nested-includes regression for the second modified path.

      This suite covers the direct child include flow, but it never exercises the nested buffer path changed in setupNestedPipelines(). A status -> tasks -> subtasks optimistic reorder case would close the gap and protect the second branch touched in this PR. As per coding guidelines, Always add unit tests that reproduce a bug before fixing it to ensure the bug is fixed and prevent regression and Test corner cases including: ... async race conditions.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/db/tests/query/includes.test.ts` around lines 5372 - 5451, The test
      suite exercises optimistic reorders for a single child include but doesn't hit
      the nested buffer path in setupNestedPipelines(); add a new spec that mirrors
      the existing `orderBy in includes after child collection update` test but with a
      nested include (status -> tasks -> subtasks) to exercise the second branch:
      create mockSyncCollectionOptions and createCollection for statuses, tasks, and
      subtasks, build a live query via createLiveQueryCollection that selects statuses
      with tasks which in turn include subtasks ordered by position, preload the live
      query, perform an optimistic swap of subtask positions using
      subtasks.update(...), assert the in-memory order changes immediately, then use
      the tasks/subtasksOptions.utils.begin/write/commit flow to simulate server
      confirmation and finally assert the order remains correct; ensure test names and
      helper functions mirror existing patterns (e.g., getSubtaskOrder analogous to
      getTaskOrder) so setupNestedPipelines()’s nested pipeline path is exercised.

      Source: Coding guidelines

      🤖 Prompt for all review comments with AI agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      Nitpick comments:
      In `@packages/db/tests/query/includes.test.ts`:
      - Around line 5372-5451: The test suite exercises optimistic reorders for a
      single child include but doesn't hit the nested buffer path in
      setupNestedPipelines(); add a new spec that mirrors the existing `orderBy in
      includes after child collection update` test but with a nested include (status
      -> tasks -> subtasks) to exercise the second branch: create
      mockSyncCollectionOptions and createCollection for statuses, tasks, and
      subtasks, build a live query via createLiveQueryCollection that selects statuses
      with tasks which in turn include subtasks ordered by position, preload the live
      query, perform an optimistic swap of subtask positions using
      subtasks.update(...), assert the in-memory order changes immediately, then use
      the tasks/subtasksOptions.utils.begin/write/commit flow to simulate server
      confirmation and finally assert the order remains correct; ensure test names and
      helper functions mirror existing patterns (e.g., getSubtaskOrder analogous to
      getTaskOrder) so setupNestedPipelines()’s nested pipeline path is exercised.

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro

      Run ID: 26dee569-e9b0-41fa-9ee8-e20d3607d68d

      📥 Commits

      Reviewing files that changed from the base of the PR and between 4d1abded3e5bdec16457deb7486e28b6a228c670 and b3952649acdeb83a5e4f708d4a05d8edbd91c47f.

      📒 Files selected for processing (3)
      • .changeset/twelve-jars-lead.md
      • packages/db/src/query/live/collection-config-builder.ts
      • packages/db/tests/query/includes.test.ts
    3. The reported optimistic child-reorder bug no longer reproduces on current main. Its exact regression is green and retained in packages/db/tests/query/includes-oracle.property.test.ts, so this fix PR is no longer needed. Closing as superseded by the current implementation.

Sign in to join this conversation.