Skip to content

Wait for the page's background JavaScript before tests read the Request Run form - #192

Open
shuseng8 wants to merge 2 commits into
jenkinsci:mainfrom
shuseng8:fix-189-wait-for-page-scripts
Open

shuseng8 wants to merge 2 commits into
jenkinsci:mainfrom
shuseng8:fix-189-wait-for-page-scripts

Conversation

@shuseng8

Copy link
Copy Markdown

What this changes

Tests that read the Request Run form now wait for the page's background JavaScript to finish, and for nothing to be left that could run later, before they query the DOM. Only src/test changes.

Cause. HtmlUnit runs setTimeout callbacks and fetch/XMLHttpRequest callbacks as jobs on its own thread, the client's JavaScript executor. The test reads the DOM on the test thread, and nothing locks the DOM between the two threads. The job pages these fixtures open include core's Builds card (jsbundles/pages/project/builds-card.js). It fetches the builds list when the page loads, then again every 5 seconds (updateBuildsRefreshInterval = 5000), and each time it replaces its contents with innerHTML. If an XPath walk (DOM2DTM) is running when that subtree is replaced, it reaches a removed node and fails with node is null. This is the error in the issue. I checked the queue right after requestRunForm loads the page: it holds a setTimeout(…, 1) (the first fetch's continuation) and the setTimeout(() => load(), 5000) refresh. The refresh re-arms itself, so wc.waitForBackgroundJavaScript(5000) in submit never saw an empty queue. It always waited the full 5 seconds and returned just as the next refresh started. That explains the second failure in the issue (RequestPrefillGapTest:199, setFile on the page that submit returned).

What the wait waits for. The new PageScriptFixtures.settled(page) / settle(webClient) loops over the client's windows and, for each job manager that still has jobs:

  1. runs to the end every job that is due now (within 1 s), plus any job those jobs start, such as a fetch and its continuation (waitForJobsStartingBefore);
  2. cancels the timers that are left, i.e. the Builds card's next refresh (removeAllJobs);
  3. checks again, and returns only once every job manager reports getJobCount() == 0.

Why that is always enough. JavaScriptJobManagerImpl takes a job off its queue and marks it as the running job inside a single synchronized block, and getJobCount() counts queued plus running jobs under the same lock. A count of 0 therefore means that nothing is queued and nothing is running. Jobs are created only by JavaScript, so after that point a job can start only if the test thread itself runs a script (a click, or a value change that fires onchange). No background script can change the DOM while the test reads it. The guarantee comes from that state, not from timing, so a slow machine does not break it. The bound (60 s) only matters for a page that never stops scheduling short timers, and then the test fails with the job dump instead of hanging or racing.

Where it is used.

  • TypedParameterFixtures.requestRunForm: after loading the Request Run page.
  • TypedParameterFixtures.parameterBlock, the XPath entry point of setFile, setValue and valueOf: before every query. This covers forms that a test loaded by itself (for example RefusedBuildPrefillTest and the core build form in CredentialsParameterTest/RunParameterTest) and scripts started by the last change to a control. On a page that has already settled it returns at once.
  • TypedParameterFixtures.submit: replaces waitForBackgroundJavaScript(5000). This covers RequestPrefillGapTest:199, which reads the refused page that submit returns.
  • RerunFallbackFixtures.openForm and notices: the rerun fallback form, also used by RequestPrefillGapTest.
  • DialogFixtures.openDialog: after the job page loads and after the fragment is inserted (it waited 5 s before, with the same race).
  • Tests that submit the Request Run form themselves and then waited 5 s before reading the answer: RequestScreenGuardTest, RequestFormEncodingTest, RequestFormControlsTest, MultiApproverTest, ApproverIdStrategyTest.
  • Test helpers that load a JavaScript-enabled page and query it with XPath right away: TypedParameterIntegrityTest.assertFieldRefusal, JobRunSidebarEntryTest (submitParameters and the landing page), and DialogTypedParameterTest.fileControls.

I left the approval-page and dialog-confirmation waits alone (DecisionAreaFixtures, RejectConfirmationTest, RevertPlacementTest, the naginator Retry click in RefusedRerunAuditTest, and the Cancel click in RequestFormControlsTest). They do not read a Request Run form, and some of them wait for a dialog script on purpose.

Side effect: each form submission no longer sleeps 5 s, so these classes run faster.

Anchor

Testing done

  • mvn -ntp test -DforkCount=6 -Dtest=TypedParameterValuesTest,RequestPrefillGapTest,DialogTypedParameterTest,CredentialsParameterTest,RunParameterTest,RequestScreenGuardTest,RequestFormEncodingTest,TypedParameterIntegrityTest,JobRunSidebarEntryTest,MultiApproverTest,ApproverIdStrategyTest,RequestFormControlsTest,RefusedBuildPrefillTest,IncidentRerunGapTest (JDK 21.0.13, Maven 3.9.9): 102 tests, 0 failures, 0 errors.
  • mvn -ntp clean verify -DforkCount=6: stopped after 66 test classes / 355 tests had finished (0 failures, 0 errors) because the whole suite would take several hours on this machine. Then mvn -ntp verify -DskipTests: BugInstance size is 0, spotless:check passed, BUILD SUCCESS.
  • I checked the root cause with a throwaway probe test (not committed). It loaded job/<name>/batch-control/ with the fixtures' browser(...) client and dumped the job queue every 200 ms for 60 s. A setTimeout(() => load(), 5000) re-armed every 5 s for the whole run, and each refresh came with a setTimeout(…, 1) continuation.
  • As the issue says, rerunning cannot prove the race is gone. The argument for the fix is the state described above, not a pass rate.

Checks

  • The pull request title represents the desired changelog entry.
  • Opened from a topic branch, not from the main branch of your fork.
  • The build workflow passed on that branch in your fork before this pull request was opened. Not run: workflows are not enabled on my fork. Local results are above.
  • mvn clean verify passed locally: partial run, see above (0 failures in the 355 tests that ran; SpotBugs BugInstance size is 0).
  • This PR does not disclose a security vulnerability.

…st Run form

Fixes jenkinsci#189. HtmlUnit runs timers and fetch/XHR callbacks on its own thread
while the test reads the DOM. The Builds card on the job pages these
fixtures open fetches the builds list on load and every 5 seconds and
replaces its contents, so an XPath walk could meet a removed node
(DOM2DTM NPE). waitForBackgroundJavaScript(5000) never saw an empty queue
because that refresh re-arms itself, so it returned when the next refresh
started.

PageScriptFixtures.settled runs every job due now to the end, cancels the
remaining timers and returns when no job is queued or running; from then on
only the test thread can start a script. The Request Run form, rerun
fallback form and dialog fixtures, parameterBlock, submit, and the tests
that submitted the form and slept 5 seconds use it. src/test only.

Signed-off-by: Shubham <[email protected]>
@shuseng8
shuseng8 requested a review from a team as a code owner November 28, 2026 05:15

@YongGoose YongGoose left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @shuseng8. The root-cause write-up is excellent: the Builds card's 5-second refresh explains both failures in #189, and it explains why waitForBackgroundJavaScript(5000) never came back empty. Waiting for a state rather than a time is the right idea, and ci.jenkins.io ran the whole suite green on e267b5d.

One thing to change, inline. The GitHub Actions workflows (Build, Windows tests, E2E) are waiting for approval on this PR. I'll get them running after your next push. The Windows run matters here, because #173's flake came from a slow Windows runner.

jobs.waitForJobsStartingBefore(DUE_NOW_MS);
// Cancel the timers that are left (the Builds card's next refresh). A job that
// started in the meantime keeps the count above 0, so the loop checks again.
jobs.removeAllJobs();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

waitForJobsStartingBefore(DUE_NOW_MS) fixes its deadline when it is called: now + 1 s. A job that starts before the deadline but runs past it, such as a request on a slow runner (in #173 a Windows runner took about 16 s to load a page), can then schedule its continuation (setTimeout(…, 1), as you found for the Builds card) after the deadline. That continuation is not waited for, and removeAllJobs() on the next line drops it. So this can cancel more than the far-off refresh:

  • whatever that continuation renders never appears. If it is the CRED list fill, T-05-105/106 fail after their 30 s wait;
  • a check that something does not change later passes vacuously, because the later change was cancelled.

Could you cancel only what is not due soon? Keep calling waitForJobsStartingBefore(DUE_NOW_MS) until nothing is running and getEarliestJob() is either null or has a getTargetExecutionTime() more than DUE_NOW_MS ahead. Only then call removeAllJobs(). The state argument still holds when it returns (count 0), and a job that was due within the window can never be cancelled, however slow the runner is.

@shuseng8

Copy link
Copy Markdown
Author

Thanks @YongGoose, good catch. settle now keeps calling waitForJobsStartingBefore(DUE_NOW_MS) until nothing is running and the earliest queued job is null or more than DUE_NOW_MS ahead, and only then calls removeAllJobs(). A job that is due soon can no longer be cancelled, however slow the runner is. The test suite passes locally with the change. Pushed in the latest commit, so the workflows should be ready for approval.

@YongGoose YongGoose left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @shuseng8, this is exactly the change I asked for. I read isDueSoon against HtmlUnit's job manager:

  • A continuation that a slow job schedules after the deadline is now waited for, because it is queued and due within DUE_NOW_MS. Only timers further out are cancelled.
  • If a job is still running while only a far-off timer is queued, removeAllJobs() cancels just that timer. The running job and anything it schedules afterwards keep the count above 0, so the outer loop waits for them.
  • If the deadline passes while a job is still due soon, nothing is cancelled and the test fails with the job dump. That is the loud failure the class comment promises.

The RequestPrefillGapTest place from #189 is covered too: line 199 reads a page that TypedParameterFixtures.submit now settles.

Every check on 7c1cfdb is green, including the seven Windows groups and ci.jenkins.io's windows-21 build.

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.

Flaky JenkinsRule tests: HtmlUnit XPath fails while the page's JavaScript still changes the form

2 participants