Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
711a5de
Address queued conflict replaces by requestIndex instead of array pos…
adhorodyski Sep 15, 2026
c150d11
Refuse conflict follow-ups that cannot be addressed by requestIndex
adhorodyski Sep 15, 2026
07e3f5b
Pin the refusal of a nextAction delete at runtime
adhorodyski Sep 15, 2026
0dc2cdc
Clear the lint error in the conflict test and cover the refusal witho…
adhorodyski Sep 15, 2026
cafe4ca
Merge branch 'Expensify:main' into fm/exfy-sq-conflict-index
adhorodyski Sep 15, 2026
38b8fa2
Naming and duplication cleanups in the conflict addressing
adhorodyski Sep 15, 2026
024495f
Merge branch 'fm/exfy-sq-conflict-index' of https://github.com/callst…
adhorodyski Sep 15, 2026
3061ba2
Mark the added conflict tests with Given/When/Then step comments
adhorodyski Sep 15, 2026
03f7031
Merge remote-tracking branch 'upstream/main' into fm/exfy-101207-gwt
adhorodyski Sep 15, 2026
82057c9
Merge the conflict follow-up refusal guards and drop the identity on …
adhorodyski Sep 16, 2026
1edc99e
Collapse the two conflict follow-up refusal tests into one it.each
adhorodyski Sep 16, 2026
3ade22c
Remove the comments this change added and let the code speak
adhorodyski Sep 16, 2026
f694f35
Revert "Remove the comments this change added and let the code speak"
adhorodyski Sep 16, 2026
b742bf9
Refuse an ambiguous requestIndex and alert when an update drops
adhorodyski Sep 17, 2026
5ba5b2d
Address the top-level conflict replace by identity as well
adhorodyski Sep 17, 2026
39b257c
Say what the conflict tests cover and prove the edit reaches the wire
adhorodyski Sep 17, 2026
b2d0f30
Name the tests that guard the queue coupling in its guide
adhorodyski Sep 17, 2026
d105af5
Drop a test comment that restated the fixture under it
adhorodyski Sep 17, 2026
53a7e01
Say in code what the queue comments said
adhorodyski Sep 18, 2026
98a32b5
Shorten the queue guide's replace-addressing notes to the contracts
adhorodyski Sep 18, 2026
944528b
Merge branch 'Expensify:main' into fm/exfy-sq-conflict-index
adhorodyski Sep 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions contributingGuides/SEQUENTIAL_QUEUE.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ async push() (online · idle · no conflict)
| Promote head → ongoing | `processNextRequest()` | both (atomic `multiSet`) | No, fire-and-forget |
| Success / non-retryable drop | `endRequestAndRemoveFromQueue()` | both (atomic `multiSet`) | No, fire-and-forget |
| Retryable failure | `rollbackOngoingRequest()` | both (atomic `multiSet`) | No, fire-and-forget |
| Conflict REPLACE | `update()` | `PERSISTED_REQUESTS` | **Yes**, `handleConflictActions` awaits it |
| Conflict REPLACE | `update()` | `PERSISTED_REQUESTS`, or **nothing** on a skipped replace | **Yes**, `handleConflictActions` awaits it |
| Conflict DELETE | `deleteRequestsByIndices()` | `PERSISTED_REQUESTS` | **Yes**, `handleConflictActions` awaits it |
| In-flight update (e.g. reauth) | `updateOngoingRequest()` | `PERSISTED_ONGOING_REQUESTS` | No |

Expand Down Expand Up @@ -444,7 +444,7 @@ That hold has two consequences for the machinery above. A refused advance is ind
1. **In `prepareRequest` (read-only)** against `getAll()`, solely to decide whether to suppress optimistic data (`conflictAction.type === 'noAction'`). The rest of the action is ignored here.
2. **In `push` (authoritative)** against the live persisted requests. The resolver function is deleted off the request (to keep it serializable), and the `conflictAction` is applied via `handleConflictActions`, which performs the queue mutations. The four action shapes:
- **push**: append the new request.
- **replace**: overwrite the request at a computed index.
- **replace**: overwrite a queued request, by array position at the top level and by `requestIndex` in a `nextAction` (see **Index fragility** below).
- **delete**: remove requests at computed indices, optionally push a new request and/or recurse into a `nextAction` (`pushNewRequest` is a required boolean on the type; the optionality is behavioral).
- **noAction**: ignore the new request.

Expand All @@ -454,6 +454,10 @@ An incoming `OpenApp` (wired via `writeWithNoDuplicatesOpenAppConflictAction`) h

**Sharp edges.**
- **Index fragility.** `replace`/`delete` carry **numeric indices** computed by the resolver at `push` time, but `handleConflictActions` applies them **asynchronously** (awaiting between positional operations). Meanwhile `processNextRequest` (`slice(1)`), `endRequestAndRemoveFromQueue` (splice), and cross-tab merges can shift indices. An index computed against one snapshot may point at a different request by the time it is applied.
- **`nextAction` replace addressing.** A `nextAction` is applied by `handleFollowUpConflictAction`, which takes only a `replace` addressed by `requestIndex` and refuses anything else with a `Log.alert`.
- **Skipped replaces are never appended.** `update()` resolves `requestIndex` against the live queue at apply time, and a `replace` whose target is no longer queued is skipped, never appended.
- **The in-place mutation is part of the contract.** The skip is lossless only because `resolveEditCommentWithNewAddCommentRequest` mutates the queued request in place, so the mutation and the skip cannot be changed independently.
- **Ambiguous identity.** When more than one live request carries the same `requestIndex`, `update()` skips the update and raises a `Log.alert`.
- **The generic conflict check sees only the queue, never the in-flight `ongoingRequest`.** A new write cannot dedupe against a request that is already being sent. The two exceptions are the resolvers above, which consult the ongoing request for an incoming `ReconnectApp` and an incoming `OpenApp`; every other command still dedupes against the waiting queue alone.
- The resolver is expected to be pure, but production resolvers are not: `resolveCommentDeletionConflicts` performs an `Onyx.update`, and because `prepareRequest` invokes the **same** closure, the side effect fires on **both** evaluations (twice per write; an idempotent merge today). `resolveEditCommentWithNewAddCommentRequest` goes further and mutates the queued request's `data` in place during evaluation.

Expand All @@ -466,9 +470,9 @@ Tests are useful here as evidence of the **intended contract**: what the team as
| Suite | What it pins as contract |
|---|---|
| `tests/unit/APITest.ts` | Offline-persist, online-flush, persisted-until-backend-response, retry/backoff for 5xx + Auth-down (asserts ~3 fetches with throttle waits), reauthentication + ordering, WRITE-blocks-READ, pause/unpause, no-duplicates + enable-feature conflict collapsing, supportal-411 no-retry + `failureData` |
| `tests/unit/SequentialQueueTest.ts` | Push/persist counts, conflict resolution (replace/push/noAction, incl. replace-while-ongoing, `async`/awaited to match `push`'s async signature), move-to-ongoing persistence, startup hydration of the ongoing request, `queueFlushedData` lifecycle, `ALREADY_CREATED` treated as success without retry, the persist-before-fire edges (`waitForIdle` resolves without flushing when the network goes offline during persist; a disk-write failure during persist does not strand `isReadyPromise` or block the queue), **and the reconnect coverage collapse wired through the queue: an identical reconnect mid-flight is dropped, a wider one runs after, an incoming incremental does not clobber a waiting full reconnect, the spinner (`IS_LOADING_REPORT_DATA`) still clears after a drop, and an incoming `OpenApp` still runs during an in-flight reconnect, while one that lands during an in-flight `OpenApp` is dropped**, plus the pause-watchdog contract: force-unpause after a stuck window, re-arm on applied-update progress, unpause only after the escalation settles, unpause anyway past the escalation cap or on escalation rejection, and a normal unpause disarms it |
| `tests/unit/PersistedRequests.ts` | Save/remove/processNext/update/updateOngoing, File/Blob handling, cross-tab follower reconciliation; the `Issue 3a`/`3c` cases assert the **durable** ongoing-request behavior (`processNextRequest` always persists via `multiSet`); a legacy test title references the vestigial `persistWhenOngoing` flag |
| `tests/unit/RequestConflictUtilsTest.ts` | Pure push/replace/delete/noAction resolver logic, including the reconnect coverage table (`resolveReconnectDuplicationConflictAction`): full/incremental drop-vs-keep against an in-flight or queued reconnect, with a live `OpenApp` counting as covering an incoming reconnect, plus `resolveOpenAppDuplicationConflictAction`: drop an incoming `OpenApp` behind an in-flight one, keep it when the caller opted out of the dedupe or when only a reconnect is live, replace a queued one |
| `tests/unit/SequentialQueueTest.ts` | Push/persist counts, conflict resolution (replace/push/noAction, incl. replace-while-ongoing, `async`/awaited to match `push`'s async signature), move-to-ongoing persistence, startup hydration of the ongoing request, `queueFlushedData` lifecycle, `ALREADY_CREATED` treated as success without retry, the persist-before-fire edges (`waitForIdle` resolves without flushing when the network goes offline during persist; a disk-write failure during persist does not strand `isReadyPromise` or block the queue), **and the reconnect coverage collapse wired through the queue: an identical reconnect mid-flight is dropped, a wider one runs after, an incoming incremental does not clobber a waiting full reconnect, the spinner (`IS_LOADING_REPORT_DATA`) still clears after a drop, and an incoming `OpenApp` still runs during an in-flight reconnect, while one that lands during an in-flight `OpenApp` is dropped**, plus the pause-watchdog contract: force-unpause after a stuck window, re-arm on applied-update progress, unpause only after the escalation settles, unpause anyway past the escalation cap or on escalation rejection, and a normal unpause disarms it, plus conflict replace addressing by `requestIndex`, refusal of a follow-up whose `requestIndex` is missing, and the promoted-target skip |
| `tests/unit/PersistedRequests.ts` | Save/remove/processNext/update/updateOngoing, File/Blob handling, cross-tab follower reconciliation; the `Issue 3a`/`3c` cases assert the **durable** ongoing-request behavior (`processNextRequest` always persists via `multiSet`); a legacy test title references the vestigial `persistWhenOngoing` flag; `update` addressed by `requestIndex`, skipped rather than appended when the target is gone, refused when more than one request carries the same `requestIndex` |
| `tests/unit/RequestConflictUtilsTest.ts` | Pure push/replace/delete/noAction resolver logic, including the reconnect coverage table (`resolveReconnectDuplicationConflictAction`): full/incremental drop-vs-keep against an in-flight or queued reconnect, with a live `OpenApp` counting as covering an incoming reconnect, plus `resolveOpenAppDuplicationConflictAction`: drop an incoming `OpenApp` behind an in-flight one, keep it when the caller opted out of the dedupe or when only a reconnect is live, replace a queued one, and the edit-comment resolver stamping `requestIndex` onto its replace, plus the not-found add comment index |
| `tests/actions/QueuedOnyxUpdatesTest.ts` | Account-scoped update filtering on flush |
| `tests/unit/MiddlewareTest.ts` | `SaveResponseInOnyx` and `HandleUnusedOptimisticID` |
| `tests/unit/ReconnectTest.ts` | The offline→online transition flushes the queue exactly once |
Expand Down
17 changes: 15 additions & 2 deletions src/libs/Network/SequentialQueue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -769,6 +769,19 @@ onPersistedRequestsInitialization(flush);
// Flush the queue when another tab enqueues new requests
onPersistedRequestsCrossTabMerge(flush);

async function handleFollowUpConflictAction<TKey extends OnyxKey>(nextAction: ConflictData, newRequest: OnyxRequest<TKey>): Promise<void> {
if (nextAction.type !== 'replace' || nextAction.requestIndex === undefined) {
Log.alert('[SequentialQueue] Refusing a conflict follow-up that cannot be addressed by requestIndex', {
command: newRequest.command,
nextActionType: nextAction.type,
staleIndex: nextAction.type === 'replace' ? nextAction.index : undefined,
});
return;
}

await updatePersistedRequest(nextAction.index, nextAction.request ?? (newRequest as AnyRequest), nextAction.requestIndex);
}

async function handleConflictActions<TKey extends OnyxKey>(conflictAction: ConflictData, newRequest: OnyxRequest<TKey>): Promise<void> {
Log.info('[SequentialQueue] handleConflictActions', false, {
conflictType: conflictAction.type,
Expand All @@ -787,7 +800,7 @@ async function handleConflictActions<TKey extends OnyxKey>(conflictAction: Confl
replaceIndex: conflictAction.index,
replacementRequest: conflictAction.request?.command ?? newRequest.command,
});
await updatePersistedRequest(conflictAction.index, conflictAction.request ?? (newRequest as AnyRequest));
await updatePersistedRequest(conflictAction.index, conflictAction.request ?? (newRequest as AnyRequest), conflictAction.requestIndex);
} else if (conflictAction.type === 'delete') {
Log.info('[SequentialQueue] Conflict resolution: DELETE', false, {
command: newRequest.command,
Expand All @@ -807,7 +820,7 @@ async function handleConflictActions<TKey extends OnyxKey>(conflictAction: Confl
command: newRequest.command,
nextActionType: conflictAction.nextAction.type,
});
await handleConflictActions(conflictAction.nextAction, newRequest);
await handleFollowUpConflictAction(conflictAction.nextAction, newRequest);
}
} else {
Log.info('[SequentialQueue] No action performed, request ignored', false, {
Expand Down
44 changes: 40 additions & 4 deletions src/libs/actions/PersistedRequests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -353,11 +353,46 @@ function deleteRequestsByIndices(indices: number[]): Promise<void> {
});
}

function update<TKey extends OnyxKey>(oldRequestIndex: number, newRequest: Request<TKey>): Promise<void> {
/**
* Replace one queued request with newRequest. With requestIndexToReplace the target is that identity, looked up in the
* live queue, and oldRequestIndex is only the caller's now-stale guess (logged as staleIndex); without it, the target
* is oldRequestIndex itself, which must be in range. A target that cannot be resolved — absent, out of range, or carried
* by more than one request — is skipped, never appended.
*/
function update<TKey extends OnyxKey>(oldRequestIndex: number, newRequest: Request<TKey>, requestIndexToReplace?: number): Promise<void> {
const requests = [...persistedRequests];
const oldRequest = requests.at(oldRequestIndex);
Log.info('[PersistedRequests] Updating a request', false, {oldRequest: sanitizeLogParams(oldRequest), newRequest: sanitizeLogParams(newRequest), oldRequestIndex});
requests.splice(oldRequestIndex, 1, newRequest as AnyRequest);
const carriesTargetIdentity = (persistedRequest: AnyRequest) => requestIndexToReplace !== undefined && getClientRequestIndex(persistedRequest) === requestIndexToReplace;
const indexToReplace = requestIndexToReplace === undefined ? oldRequestIndex : requests.findIndex(carriesTargetIdentity);
const targetIdentityIsAmbiguous = requests.filter(carriesTargetIdentity).length > 1;
const targetIsMissingFromQueue = indexToReplace === -1 || indexToReplace >= requests.length;
const skippedLogParams = {command: newRequest.command, requestIndexToReplace, staleIndex: oldRequestIndex, queueLength: requests.length};

if (targetIdentityIsAmbiguous) {
Log.alert('[PersistedRequests] Refusing to update a request whose requestIndex is carried by more than one queued request', skippedLogParams);
return Promise.resolve();
}

if (targetIsMissingFromQueue) {
const ongoing = getOngoingRequest();
const targetIsTheOngoingRequest = requestIndexToReplace !== undefined && ongoing !== null && getClientRequestIndex(ongoing) === requestIndexToReplace;

if (targetIsTheOngoingRequest) {
Log.info('[PersistedRequests] Update target has been promoted to the ongoing request, which carries the update already, skipping it', false, skippedLogParams);
} else {
Log.alert('[PersistedRequests] Update target is in neither the queue nor the ongoing request, so the update is dropped', skippedLogParams);
}
return Promise.resolve();
}

const oldRequest = requests.at(indexToReplace);
Log.info('[PersistedRequests] Updating a request', false, {
oldRequest: sanitizeLogParams(oldRequest),
newRequest: sanitizeLogParams(newRequest),
oldRequestIndex,
resolvedIndex: indexToReplace,
requestIndexToReplace,
});
requests.splice(indexToReplace, 1, newRequest as AnyRequest);
persistedRequests = requests;
const requestIndex = getClientRequestIndex(newRequest as AnyRequest);
if (requestIndex != null) {
Expand Down Expand Up @@ -544,6 +579,7 @@ export {
save,
getAll,
getCommands,
getClientRequestIndex,
endRequestAndRemoveFromQueue,
update,
getLength,
Expand Down
6 changes: 5 additions & 1 deletion src/libs/actions/RequestConflictUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import type {TupleToUnion} from 'type-fest';

import Onyx from 'react-native-onyx';

import {getClientRequestIndex} from './PersistedRequests';

type AnyRequestMatcher = (request: AnyRequest) => boolean;

const addNewMessage = new Set<string>([WRITE_COMMANDS.ADD_COMMENT, WRITE_COMMANDS.ADD_ATTACHMENT, WRITE_COMMANDS.ADD_TEXT_AND_ATTACHMENT]);
Expand Down Expand Up @@ -290,7 +292,8 @@ function resolveEditCommentWithNewAddCommentRequest<TKey extends OnyxKey>(
indicesToDelete.push(index);
}

const currentAddComment = persistedRequests.at(addCommentIndex);
const addCommentIsLocated = addCommentIndex >= 0;
const currentAddComment = addCommentIsLocated ? persistedRequests.at(addCommentIndex) : undefined;
let nextAction = null;
if (currentAddComment) {
currentAddComment.data = {...currentAddComment.data, ...parameters};
Expand All @@ -305,6 +308,7 @@ function resolveEditCommentWithNewAddCommentRequest<TKey extends OnyxKey>(
nextAction = {
type: 'replace',
index: addCommentIndex,
requestIndex: getClientRequestIndex(currentAddComment),
request: currentAddComment,
};

Expand Down
7 changes: 6 additions & 1 deletion src/types/onyx/Request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,11 @@ type ConflictRequestReplace = {
*/
index: number;

/**
* The requestIndex of the queued request this replace targets.
*/
requestIndex?: number;

/**
* The new request to replace the existing request in the queue.
*/
Expand Down Expand Up @@ -162,7 +167,7 @@ type ConflictRequestDelete = {
/**
* The next action to execute after the current conflict is resolved.
*/
nextAction?: ConflictData;
nextAction?: ConflictRequestReplace;
};

/**
Expand Down
Loading
Loading