project-pegaprox icon indicating copy to clipboard operation
project-pegaprox copied to clipboard

[Bug] Late REST responses overwrite node, VM and cluster detail data after navigation

Open Frisch12 opened this issue 2 months ago • 2 comments

Describe the bug

When switching between nodes, VMs and cluster-specific views, the selection and the displayed detail data can refer to different entities. There are two distinct symptoms:

  1. Data from the previous entity remains visible while the newly selected entity is loading.
  2. The new entity's correct data is already visible, but a delayed response for the previous selection subsequently overwrites it.

The second sequence is particularly misleading because the view appears to have finished loading correctly before becoming wrong again:

Select A → request A starts
Select B → request B starts
Response B arrives → B's data is displayed correctly
Response A arrives → A's data is applied to the same view
B is still selected

These labels illustrate response ordering, not captured production timings. The response for A does not need to contain an incorrect or cached server payload: it can be entirely correct for A and still be wrong to apply to B's view.

The source contains several concrete paths that allow this. Some replace an entire data slot; others combine fields from different entities or let an obsolete request change the current error/loading state. The result can therefore be a mixture of current and incorrect information rather than an obvious complete switch back to A.

Inspected upstream revisions

The references below are pinned to these source revisions:

The investigation covers relevant paths in web/src/dashboard.js, web/src/node_modals.js, web/src/vm_modals.js and web/src/cloud.js. This is not a claim that every asynchronous path in those files, or every view in the product, has been audited. Source inspection and isolated callback checks are distinguished below from full browser reproduction.

1. Corporate node detail: an old response is merged into the new node's state

In CorporateNodeDetailView.loadTabData(), web/src/node_modals.js:4844–4919, the request URLs use the clusterId and node captured when the loader is called. After await Promise.all(...), the results are written into the shared data state without checking whether that node or request context is still current:

const results = await Promise.all(
    urls.map(u => authFetch(u)
        .then(r => r && r.ok ? r.json() : null)
        .catch(() => null))
);
setData(prev => {
    const newData = { ...prev };
    if (tab === 'summary') newData.summary = results[0];
    // Other branches assign performance, tasks, network, system,
    // sensors, disks, repositories, subscription and Ceph data.
    return newData;
});

This excerpt is shortened; the comment summarises the other branches. The full loader has neither a current-selection check nor a request-generation check. Its final setLoading(false) is also unconditional.

The node-change effect does clear data and load the new summary:

useEffect(() => {
    setData({});
    setConfigSubTab('network');
    setMonitorSubTab('performance');
    setActiveDetailTab('summary');
    loadTabData('summary');
}, [node]);

However, clearing state does not invalidate requests that are already running. The effect returns no cleanup to prevent their subsequent writes. The functional setData(prev => ...) does not provide that protection either: it uses the newest state as its starting point, then inserts results captured for the old node.

This permits a mixed state:

A/network starts and remains pending
Switch to B → data is cleared; B/summary starts
B/summary completes → data.summary belongs to B
A/network completes → data.network belongs to A

Current node: B
Summary:      B
Network:      A

The stale network value can persist rather than simply flash. The tab-loading effect at lines 4936–4951 requests network data only when !data.network. Once A's late response has filled that field, opening B's Network tab does not satisfy the condition for loading B's network data.

A late non-OK response is also a write: the loader converts it to null and can replace an already loaded B summary with null.

The dashboard render path does not give CorporateNodeDetailView a node-specific React key. Its surrounding content is keyed by cluster ID. Switching between two nodes in the same cluster therefore does not change that outer key and can reuse the component with different node props. The reproduction does not depend on the component surviving a cross-cluster remount.

The reset effect also depends only on [node], rather than the full clusterId + node identity. That deserves attention when fixing the loader, but it is not necessary to demonstrate the same-cluster race above.

2. Corporate VM detail: a correctly keyed cache does not protect the visible state

The guest-info effect in CorporateVmDetailView, web/src/vm_modals.js uses a per-VM cache key, but applies the result to component state without a validity check:

useEffect(() => {
    const gkey = `${clusterId}:${vm.vmid}`;
    if (!(isQemu || vm.type === 'lxc') || vm.status !== 'running') {
        delete _guestInfoCache[gkey];
        setGuestInfo(null);
        return;
    }
    authFetch(`${API_URL}/clusters/${clusterId}/vms/${vm.node}/${vm.type}/${vm.vmid}/guest-info`)
        .then(r => r && r.ok ? r.json() : null)
        .then(data => {
            if (data && (data.agent_running || data.is_lxc)) {
                _guestInfoCache[gkey] = data;
                setGuestInfo(data);
            } else {
                setGuestInfo(_guestInfoCache[gkey] || null);
            }
        })
        .catch(() => setGuestInfo(_guestInfoCache[gkey] || null));
}, [vm.vmid, vm.status, clusterId]);

The excerpt preserves the effect's logic with expanded formatting and comments omitted.

When navigating from running VM A to running VM B, this path does not first reset or replace guestInfo with B's own cached value. A's existing guest information can remain visible while B loads.

For overlapping requests, A's late response is stored under the correct cache key for A, but setGuestInfo(data) still writes it into the component now showing B. B's cache entry can remain completely correct while the visible guest information is wrong.

The fallback is affected as well: a delayed unsuccessful request for A can apply A's cached value, or null, after B has loaded. This is why checking cache keys alone would miss the display bug.

The adjacent guest-fsinfo effect writes setFsInfo(d || null) without cleanup or a current-context check. fetchSnapshots() and fetchMetrics() likewise apply results and loading-state changes without a navigation/request-generation check. Snapshot state is cleared on VM change, but the outstanding snapshot requests are not invalidated. These are additional source findings, not separate claims of browser reproduction for every loader.

The dashboard call site at lines 15688–15713 gives CorporateVmDetailView new vm props without a VM-specific key. Switching directly between VMs in the same cluster can therefore preserve the state setters used by those older requests.

3. Cloud: useCloudData(path) accepts obsolete successes, errors and loading completions

The shared hook in web/src/cloud.js:1260–1275 contains:

const reload = React.useCallback(() => {
    if (!path) { setLoading(false); return; }
    setLoading(true); setErr(null);
    fetch(path, { headers: getAuthHeaders() })
        .then(r => r.ok ? r.json() : Promise.reject(new Error('HTTP ' + r.status)))
        .then(d => { setData(d); setLoading(false); })
        .catch(e => { setErr(String(e && e.message || e)); setLoading(false); });
}, [path]);
React.useEffect(() => { reload(); }, [reload]);

Changing path creates a new callback and starts the new request. It does not invalidate the previous promise chain. There is no cleanup, abort signal or validity check before any of the state updates.

This produces three separate failure sequences:

  • A succeeds after B: A replaces B's successfully loaded data.
  • A fails after B: A sets err even though B succeeded. The adjacent CloudSectionState renders the error state before the actual content, so correct B data can be hidden without being overwritten.
  • A finishes while B is pending: A sets loading=false, although the current request for B has not finished.

The hook has reachable consumers with changing cluster-specific URLs, including Cloud Backups and Cloud Firewall. The Cloud section render path passes the current cluster ID without giving those section components their own cluster-specific keys. The content wrapper renders {body} without such a key as well.

The entire cloud.js file has the same blob SHA, ebc9fdd778b58f57bafe49b9ea95d2549e19df82, in the inspected Testing revision and the inspected main revision. This hook finding is not confined to one of those branches.

4. Cluster task list: the initial-fetch exception bypasses the existing stale check

fetchTasks(), web/src/dashboard.js:10617–10681 captures the initial-fetch flag before awaiting the response:

const fetchStartTime = Date.now();
const isInitialFetch = initialTaskFetchPending.current;

The later timestamp check only runs for a non-initial fetch:

if (!isInitialFetch && fetchStartTime < taskUpdateTimestamp.current) {
    console.log('Skipping stale task fetch response');
    return;
}

On cluster change, the effect resets taskUpdateTimestamp.current to 0, sets initialTaskFetchPending.current = true, clears the task list, and starts a new fetch. It does not invalidate outstanding requests.

An initial fetch already started for A retains its captured isInitialFetch=true even after B's initial fetch has completed. Its late response therefore bypasses the timestamp check and is merged into the current task list through the UPID map. A further cluster/navigation-context check is missing at this write site.

The resulting list can contain tasks from both clusters while B remains selected. This is not a request to change the intended task merge or discard valid updates; it is a missing ownership check before that merge.

Existing safeguards show why only parts of a view become wrong

There are already useful protections in neighbouring paths. In dashboard.js, fetchClusterMetrics, fetchClusterResources, fetchClusterPools and fetchClusterDatastores update the correctly keyed sidebar cache and compare selectedClusterRef.current?.id with clusterId before updating the active cluster state. The SSE handlers for tasks, metrics and resources also check the current cluster ID.

Those checks should be preserved. They do not cover the unguarded detail loaders above, which explains how one part of a view can remain correct while another is replaced by a stale response. A cluster-ID comparison also does not, by itself, distinguish two different visits to A in an A → B → A sequence or two out-of-order refreshes of the same query.

Related upstream context

#813 — Show QEMU VM descriptions in the Corporate summary explicitly discusses clearing old configuration during a VM switch. In the discussion, the same stale-response pattern is noted as having been addressed in PBS panels. That is related context, but #813 concerns the description feature rather than these node, guest-info, Cloud and task-list paths.

#782 — UI request amplification concerns repeated polling and excessive overlapping requests. Reducing the number of requests does not by itself prevent a superseded response from updating the current view. This report is about data ownership and correctness, not reopening that performance issue.

Steps to Reproduce

Use entities with clearly distinguishable values. For the node and VM cases, use two entities in the same cluster so the dashboard's outer cluster key does not change.

A. Previous VM data remains visible

  1. Open running VM A in the Corporate layout and wait for its guest information to appear.
  2. Select another running VM B directly in the sidebar.
  3. Observe the guest-information fields before B's response arrives.
  4. The displayed information can still belong to A while the selection and heading already identify B.

B. A delayed response overwrites the current selection

  1. Open A and leave one of its detail requests pending.
  2. Select B before A's request completes.
  3. Let B's corresponding request complete first and verify that B's data is visible.
  4. Let A's request complete afterwards.
  5. The old callback can update the current component even though B remains selected.

For deterministic browser regression coverage, intercept and delay A's response, let B complete, then release A. Repeat with A returning an HTTP error or a network failure, and with A finishing while B is still pending. This is the proposed browser test setup, not a claim that a full browser run is already attached.

C. Node data becomes mixed and prevents the correct lazy load

  1. Open node A's Network tab and hold its network response.
  2. Switch directly to node B in the same cluster.
  3. Allow B's Summary response to complete.
  4. Release A's Network response.
  5. Open B's Network tab.
  6. Check both the displayed interfaces and whether a network request for B is issued. A's response can have filled data.network, defeating the !data.network load condition.

The Cloud and task-list variants use the same A → B / response B → response A ordering, applied respectively to a cluster-specific Cloud section and to initial cluster task requests.

Expected behavior

The current selection and request context determine which data may be displayed. Completion order must not determine which entity the view represents.

On navigation, stop presenting A's data as B's data. A valid cache entry belonging to B may be reused; keeping A's data visible in B's context is a different case. Normal background refreshes of the same entity do not need to blank the view unnecessarily.

Every asynchronous write needs the same ownership protection: success data, non-OK responses, exception handlers, negative cache fallbacks and loading completion. An obsolete response must not populate a lazy-load cache slot for the newly selected entity or end its loading state.

Suggested fix direction

Bind the affected loaders to a complete entity/navigation context and invalidate that context on navigation or unmount. Also distinguish newer and older requests for the same data slot, including manual reloads and query/timeframe changes.

A navigation generation combined with a sequence per query/data slot is one possible approach. A single global request counter for every parallel detail request would be inappropriate: legitimate requests for different parts of the same current view must not invalidate each other.

Cancellation can reduce unnecessary work, but validity should also be checked immediately before applying results, including after asynchronous response-body parsing. Clearing the state on navigation alone does not stop a late write; memoising a callback alone does not invalidate work it has already started.

The scope is the concrete paths described above: Corporate node details, the affected Corporate VM loaders, useCloudData, and the initial cluster task fetch. Existing correctly scoped caches, SSE filtering and task merging should remain intact. This does not require a new data-fetching library, a general frontend rewrite or blocking navigation until all requests finish.

Regression coverage

  1. A → B, response B → response A: B's data, errors and loading state remain correct after A's late success, non-OK response or failure.
  2. A → B → A: the first visit's response cannot overwrite a newer result from the second visit merely because the entity ID matches again. Cover out-of-order reloads and delayed JSON parsing too.
  3. Node tab mixing: an old response cannot populate another node's data slots or suppress that node's lazy fetch. Valid parallel loads for different slots still work.
  4. Complete identities: identical VMIDs or node names in different clusters do not mix. Include VM type and the relevant node/query context where those affect the request.
  5. Lifecycle and normal operation: obsolete completions after cleanup have no effect; valid same-entity refreshes, sidebar cache updates, SSE filtering and task merging continue to work.

These cases should ultimately be checked against the rendered, built UI with controlled response ordering, not only by looking for a guard in source code. Source changes belong in web/src/*; the generated web/index.html should be rebuilt through web/Dev/build.sh, rather than edited directly.

Environment

  • PegaProx Version: v1.1.1
  • Installation Method: manual
  • OS: Ubuntu 26.04
  • Browser: Chrome 152.0.7977.65
  • Behind Reverse Proxy? No
  • UI? Corporate

Logs / isolated verification

The relevant callback sequences were exercised locally using controllable response promises and a minimal hook-lifecycle shim under Node.js v22.16.0. Seven isolated checks on the upstream-derived Cloud, node and task-loader excerpts confirm these outcomes:

Path Isolated result
Cloud: late A success B's loaded data is replaced with A.
Cloud: late A failure B's data remains in state, but A's error is set.
Cloud: A finishes while B is pending loading becomes false before B completes.
Corporate node: late A summary B's loaded summary is replaced with A.
Corporate node: late A network B's summary and A's network coexist; !data.network is false.
Corporate node: late A non-OK response B's loaded summary becomes null.
Tasks: late initial A fetch A's task is merged into the list already containing B's task.

Representative isolated node result:

selection:                        B
summary:                          B
network:                          A-only-interface
condition_for_lazy_network_fetch: false

No production HAR capture is attached. The investigation does not establish that management operations were sent to the wrong entity or that data was lost. The demonstrated issue is the application of obsolete read results to the current view.

Screenshots

No screen recording is attached yet. For the out-of-order case, a recording should show the current selection, B's correct data, and the later replacement without another navigation action. For the node case, pair this with the intercepted request identities to show the mixed Summary/Network state.

Checklist

  • [x] I have searched existing issues to make sure this is not a duplicate.
  • [x] I have included pinned upstream source references and distinguished source findings from executed checks.
  • [x] I am using the latest version of PegaProx.

We would be happy to open a focused PR against Testing to address these paths.

– Dennis

Frisch12 avatar Sep 16 '26 07:09 Frisch12

Checked loadTabData() and you're right. No request-generation check anywhere in it, and setLoading(false) runs unconditionally too, so a late response also clears the spinner for a load that's still in flight. The only thing resembling a guard is a comment about stale closures, which is a different problem.

What makes this easy to accept: the pattern we should be using is already in our own tree. dashboard.js and vm_modals.js both drive an AbortController per request; node_modals.js never got it. So it's not a design question, it's three files that missed a convention.

Thanks for pinning the revisions - and for splitting this out instead of stacking it onto the VirtIO tickets. Taking it.

Marcus

mkellermann97 avatar Sep 16 '26 13:09 mkellermann97

The detail loaders for nodes, guests, the Cloud sections and the cluster task list now tag every request with the object it was made for. They drop any answer that arrives after you have moved on, and that covers errors and the loading state too. A late response for the previous node or VM can no longer overwrite the one you are looking at or get mixed into it. This ships in 1.3.0, and thanks for the very thorough write-up.

Marcus

mkellermann97 avatar Oct 07 '26 04:10 mkellermann97