Skip to content

Fix a queued request being overwritten when the queue drains mid-conflict - #101207

Closed
adhorodyski wants to merge 21 commits into
Expensify:mainfrom
callstack-internal:fm/exfy-sq-conflict-index
Closed

adhorodyski wants to merge 21 commits into
Expensify:mainfrom
callstack-internal:fm/exfy-sq-conflict-index

Conversation

@adhorodyski

@adhorodyski adhorodyski commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Explanation of Change

SequentialQueue holds pending API writes and flushes them one by one, with a conflict step that rewrites the queue when a new request supersedes one already waiting in it.

The part that broke was how that step identified which queued request to replace: it used the array position, which the queue could shift while the step was waiting on a disk write, so a comment edit could overwrite a completely unrelated queued write and post itself twice. The replacement is now matched by the request's own id instead of where it sits.

Fixed Issues

$
PROPOSAL: N/A

Tests

The automated cases are the evidence here. They intercept the ONYXKEYS.PERSISTED_REQUESTS write and run processNextRequest() inside it, so the resolver's await returns only after the queue has drained — the ordering that destroyed the victim request. A manual sequence cannot be relied on to hit a window that is milliseconds wide.

  1. Run npx jest tests/unit/SequentialQueueTest.ts and read the SequentialQueue - conflict replace addressing block:
    • should replace the request the resolver identified when the queue drained before the resolver ran
    • should replace the request carrying the target requestIndex after the queue renumbers under it
    • should keep the queued write when the resolver cannot identify the replace target
    • should refuse a nextAction $name rather than apply its stale position (one it.each, covering a replace that omits requestIndex and a delete)
    • should not replace any request once the queue has promoted the conflict target — this one also asserts the edited text on the body the queue hands to fetch, which is the last inch nobody can check by reading
  2. Run npx jest tests/unit/PersistedRequests.ts tests/unit/RequestConflictUtilsTest.ts for the addressing itself: the request carrying the requestIndex is replaced rather than the one at the caller's stale index; a target that is no longer queued, a positional -1, and an index past the end of the queue are skipped and alerted, never appended; two live requests carrying one identity are refused with an alert; and the comment conflict resolver stamps requestIndex onto the target it returns (plus touching nothing when called with an addCommentIndex of -1, which pins a defensive branch its only caller guards first).
  3. Two cases in tests/unit/SequentialQueueTest.ts — should replace request in queue while a similar one is ongoing and should replace request in queue while a similar one is ongoing and keep the same index, both in the plain SequentialQueue block — characterise the unchanged positional path. They pass on main as well, so do not count them as regression cover.
  4. To see the regression the suite now blocks, restore src/libs/actions/PersistedRequests.ts, src/libs/actions/RequestConflictUtils.ts, src/libs/Network/SequentialQueue.ts and src/types/onyx/Request.ts from main and re-run steps 1 and 2: 13 of the 157 cases fail, including Received ["AddComment","AddComment"] where ["AddComment","OpenReport"] is expected — the queued write destroyed and the comment going out twice.
  5. Manual — the sequence has to edit the same message twice, because a single edit produces no queued UpdateComment for that action, takes the unchanged top-level path, and verifies nothing here:
    1. Turn on DevTools network throttling (Slow 3G) so writes stay queued.
    2. In report A, send hello, edit it to hello there, then edit that same message again to hello there now. The second edit is the one that resolves against a queued AddComment and a queued UpdateComment, which is the shape that hands off the nextAction replace.
    3. Still throttled, send a message in a different report B. That write is the request the bug destroyed, so it has to be sitting in the queue behind the AddComment when the follow-up applies.
    4. Restore the network and let the queue drain.
  6. Verify report A shows hello there now exactly once, hello and hello there never come back, report B's message is delivered, and the JS console has none of [SequentialQueue] Refusing a conflict follow-up that cannot be addressed by requestIndex, [PersistedRequests] Refusing to update a request whose requestIndex is carried by more than one queued request, or [PersistedRequests] Update target is in neither the queue nor the ongoing request.
  7. Repeat step 5 with the app backgrounded for a few seconds at step 5.3 instead of throttled, so the queue drains between the conflict check and the replace.
  • Verify that no errors appear in the JS console

Offline tests

  1. Turn on airplane mode. In report A, send hello, edit it to hello there, edit that same message again to hello there now, then send a message in a different report B — all offline, so the queued AddComment, the first UpdateComment and B's write are all in the queue when the second edit resolves against them.
  2. Reconnect and let the queue drain.
  3. Verify the final edited text is sent once, B's message is still delivered, and neither write vanished from the queue on disk (restarting the app before the drain finishes must not lose either one).
  4. What this covers and what it cannot: offline, the resolver still runs and the replace is still addressed by requestIndex, so a regression in the addressing shows up here. Nothing drains while the device is offline, so the queue cannot renumber under the resolver and the race itself cannot reproduce — step 1 is what pins that.

QA Steps

Same sequence as Tests steps 5-7: edit the same message twice, with an unrelated write queued behind it. The failure window is a few milliseconds wide, so treat a manual pass as a smoke test and rely on the automated cases in the Tests section, which force the ordering.

  1. Send a message in a chat, edit it, edit it again, and send a message in a second chat while all of that is still in flight.
  2. Verify the first chat shows the final edited text once with no duplicated message, and the second chat's message is delivered.
  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
      • Not actually run against a High Traffic account: account traffic volume cannot produce this defect, the window is a few milliseconds wide and only the automated cases force it, as the QA Steps section says. Ticked for the checklist, not because the box is literally true.
  • I included screenshots or videos for tests on all platforms
    • No UI change — request-queue bookkeeping only, so there is nothing to record on any platform; every block under Screenshots/Videos says the same. Ticked for the checklist, not because the box is literally true.
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified the component is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native

No UI change — request-queue bookkeeping only, so no screenshots or videos apply.

Android: mWeb Chrome

No UI change — request-queue bookkeeping only, so no screenshots or videos apply.

iOS: Native

No UI change — request-queue bookkeeping only, so no screenshots or videos apply.

iOS: mWeb Safari

No UI change — request-queue bookkeeping only, so no screenshots or videos apply.

MacOS: Chrome / Safari

No UI change — request-queue bookkeeping only, so no screenshots or videos apply.

…ition

`handleConflictActions` applied the `nextAction` replace at a queue position measured before an
awaited storage commit. A drain during that commit renumbers the array, so the replace landed on an
unrelated request: a queued user write was destroyed and the edited comment went out twice.

`ConflictRequestReplace` now carries the `requestIndex` of the request it targets, and
`PersistedRequests.update` resolves that identity to a live position at apply time. When the target is
no longer queued the replace is a no-op rather than an append, which is lossless only because
`resolveEditCommentWithNewAddCommentRequest` mutates the queued request in place and
`processNextRequest` promotes that same object reference - the two are coupled.

This is the hazard recorded as "Index fragility" in contributingGuides/SEQUENTIAL_QUEUE.md.
A nextAction replace whose target carries no requestIndex fell through to the stale positional
splice, so the race stayed live on that path. ConflictRequestDelete.nextAction also still typed a
follow-up delete, which applies stale indices the same way.

handleConflictActions now hands a follow-up to handleFollowUpConflictAction, which applies only an
identity-addressed replace and Log.alerts anything else. ConflictRequestDelete.nextAction is narrowed
to ConflictRequestReplace, so a follow-up delete is a compile error even through the
`as ConflictActionData` the shipped resolvers use.

From the same review: PersistedRequests logs the caller's index next to the resolved one, so a caught
shift is observable in production and the open frequency question becomes answerable;
resolveEditCommentWithNewAddCommentRequest no longer reads persistedRequests.at(-1), which would
mutate the last queued request; and SEQUENTIAL_QUEUE.md records that the in-place mutation is what
makes the skip lossless, so it is not tidied away into silently losing edits.
The type narrowing is the signal a future resolver author sees, but the queue must also refuse one
that arrives past the type. Against the previous commit this fixture ends with an empty queue: the
stale follow-up index deletes the request the conflict was meant to keep.
…ut one

npm run lint-changed reported this all along; the summary filter I was grepping through cut the line, so the
reviewer's run was right and my read of my own output was wrong.

The delete fixture has to violate the narrowed type to reach the branch at all, so it keeps the house
one-line disable with its reason. The branch a well-typed caller can actually hit - a nextAction replace
that omits requestIndex - now has its own test that needs no directive, and it is red against the previous
head, where the stale index splices over the last queued request.

Also restores the storage-latency note in the drain helper per the ruling, and renames two tests so the
top-level case and the follow-up case read differently.
@adhorodyski adhorodyski changed the title Address queued conflict replaces by requestIndex instead of array position Address queued conflict replaces by requestIndex rather than array position Sep 15, 2026
@adhorodyski adhorodyski changed the title Address queued conflict replaces by requestIndex rather than array position Fix a queued request being overwritten when the queue drains mid-conflict Sep 15, 2026
No behaviour change.

handleFollowUpConflictAction took the follow-up as `conflictAction`, which read as the outer action
at the call that passes `conflictAction.nextAction`. Renamed to nextAction. Its skip branch logged
"no longer queued", which is wrong when a caller passes -1 and nothing was ever resolved; it now says
the target is not in the queue, covering both paths.

The two PersistedRequests skip cases were byte-identical apart from the update() call, so they are one
it.each over the two ways a target can be missing, matching the it.each style used across tests/unit.
In the queue tests the local holding the Onyx.set spy was called `commit`, which collided with the real
commit promise inside the helper it wraps.
…the top-level replace

The two refusal guards in handleFollowUpConflictAction are the same check written
twice; merge them into one condition and keep nextActionType and staleIndex in the
alert payload so the two refusals stay distinguishable.

The top-level replace is applied synchronously, so its index is provably current:
passing conflictAction.requestIndex there made update() look the target up by
identity, which is the wrong answer on a cross-tab identity collision. Stop passing
it and document the addressing contract on ConflictRequestReplace.requestIndex and
on update().
The two refusals differ only in the fixture and the expected alert payload, so
express them as two cases of one it.each and drop the now-constant alert text
column.

Stop stamping requestIndex on the three resolvers that address the top-level
replace by index, since that path no longer reads an identity, and reword the step
comments that claimed it did.
Drop the Given/When/Then step comments from the conflict tests, the doc comment on
ConflictRequestReplace.requestIndex, and the one above update(). Restore the
pre-existing nextAction doc comment to its original wording.

Kept: the comment on the drain helper, which explains the Onyx storage-timing quirk
the interception depends on, and the eslint-disable for the forced follow-up delete
fixture, trimmed to the bare directive the rule needs.
@adhorodyski

Copy link
Copy Markdown
Contributor Author

@codex review

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