Skip to content

fix(reindex): stop the mapping guard from permanently killing content indexing (#37038) - #37041

Merged
wezell merged 5 commits into
mainfrom
issue-37038-reindex-mapping-permit-leak
Aug 14, 2026
Merged

wezell merged 5 commits into
mainfrom
issue-37038-reindex-mapping-permit-leak

Conversation

@fabrizzio-dotCMS

@fabrizzio-dotCMS fabrizzio-dotCMS commented Aug 12, 2026 •

Copy link
Copy Markdown
Member

What

Fixes #37038 — a regression shipped in 26.07.13-01 by PR #36499 (the fix for #36498).

The reindex mapping guard leaks its semaphore permits permanently. After 8 abandoned mapping tasks, a node stops indexing content until it is restarted, and every entry rejected in the meantime is charged a retry until it parks at priority 505 — past the priority <= 400 the queue loader reads. The net effect was worse than the bug it fixed: #36498 froze indexing with the queue intact and recovered on restart; this froze indexing and destroyed the backlog.

Confirmed on a customer's staging and production environments: 315,030 journal entries in terminal ERROR state across 6 days, 303,282 distinct contentlets never indexed, 99.3% of them ordinary content saves.

Root cause

inFlight.release() lived inside the finally of the submitted task — which is exactly the code a task that never runs can never reach:

executor.submit(() -> {
    try {
        return task.call();
    } finally {
        inFlight.release();   // never reached if the body never runs
    }
});

That placement was not sloppiness, it was forced. Tasks ran on virtual threads, and file I/O does not unmount a virtual thread from its carrier. The carrier pool is availableProcessors() — 2–4 in a container, shared with every other virtual thread in the JVM — so an abandoned task keeps consuming a globally scarce resource. The cap therefore had to count abandoned work, which forced its release into the task body, which is the leak. And with maxThreads at 8 over 2–4 carriers, the cap sat above the point at which the carrier pool was already fully pinned, so it could never bind before starvation did.

The four changes

1. Two counters, and platform threads to make that safe

Counter Released by Bounds
Concurrency (REINDEX_CONTENTLET_MAPPING_MAX_THREADS, 8) the caller, in a finally that always runs how many mappings run at once
Abandonment (REINDEX_CONTENTLET_MAPPING_MAX_ABANDONED, 32) only a task that actually finishes how many are stuck; the ceiling opens a circuit breaker

Moving the tasks to platform threads is what makes caller-side release safe: an abandoned platform thread costs only its own stack (~1MB) and steals nothing from anyone else, so releasing the concurrency permit on timeout cannot let a wedge go unaccounted for. Both counters are bounded, so the worst-case live thread count is maxConcurrent + maxAbandoned. Threads are daemons, so a thread wedged in native I/O can never hold up JVM shutdown.

Not keeping virtual threads was deliberate. The original argument for them — abandoning one is free, and a hung native stat ignores interrupt() so abandoning is the only move — is real, but it buys little once the cap is 8 anyway, and it costs a shared carrier pool. See docs/backend/VIRTUAL_THREADS.md (#36900) for the socket-vs-file rule.

Because the abandonment counter heals when a stuck task eventually returns, recovery no longer requires a restart.

2. A pool rejection is never charged to the entry

ReindexPoolExhaustedException (infrastructure) is now distinct from ReindexMappingTimeoutException (this entry's own mapping overran). Only the latter reaches markAsFailed. A rejected entry is left byte-for-byte untouched — same priority, no failure cause — so it is retried later instead of marching toward Priority.ERROR.

A momentarily saturated pool defers just that entry; an open circuit aborts the batch so the loop can back off.

3. The failure is now visible and self-limiting

  • New reindex-mapping health check (MONITOR_MODE by default, not a liveness check since the guard self-heals) reporting abandonedMappings / indexingStalled.
  • An open circuit makes the reindex thread sleep REINDEX_THREAD_SLEEP_WHEN_DEGRADED (30s) instead of spinning the journal at SLEEP_ON_ERROR (500ms) speed.
  • The exhaustion log is throttled to once a minute — it used to emit 40–50K identical lines an hour — and no longer asserts "the underlying storage may be down" unconditionally, which misdirected the on-call path when the real cause was carrier starvation.

4. The index enqueue moved out of the guarded region

BulkProcessor.add() blocks on the client's in-flight semaphore (REINDEX_THREAD_CONCURRENT_REQUESTS defaults to 1) and its backoff budget is 20s × 10 = 200s — greater than the 120s mapping timeout. Elasticsearch slowness alone was sufficient to trigger the guard, with no storage fault at all.

Mapping now returns MappedDocuments (the storage-touching half) and enqueueMappedDocuments runs on the caller thread, outside the timeout.

Tests

71 unit tests green (ReindexMappingRunnerTest, ContentletIndexAPIImplMappingTimeoutTest, ReindexThreadUnitTest, and the rest of the ContentletIndexAPIImpl*Test family).

New coverage for the regression specifically:

  • moreTimeoutsThanTheConcurrencyCapDoesNotDisableTheRunner — cap + 3 timeouts, then a healthy task must still succeed. This is the test that fails on the old code.
  • abandonmentCeilingOpensTheCircuit / circuitClosesWhenAbandonedTasksReturn — the ceiling trips, then heals with no restart.
  • interruptibleSlowTaskIsFreedAndNotCountedAsAbandoned — merely-slow work is not booked as abandoned.
  • asyncTaskRunsOnNamedPlatformThread — asserts not virtual, so a future well-meaning swap back is caught.
  • poolRejectionNeverFailsTheJournalEntry, poolRecoversWhenAbandonedTaskFinishes — wiring level.
  • ContentletIndexAPIImplMappingTimeoutIT#poolRejectionLeavesTheJournalRowUntouched — the data-loss half against real SQL: priority unchanged, index_val null. Registered in MainSuite2b.

Deploying to an already-affected instance

This PR removes the need for the workaround, but it does not clean up rows already parked by it. Any instance that ran 26.07.13-01 or later still needs the requeue:

SELECT count(*) FROM dist_reindex_journal WHERE priority >= 400;   -- exposure

UPDATE dist_reindex_journal
   SET priority = priority - 400 - (priority % 100),
       index_val = NULL,
       serverid = NULL
 WHERE priority >= 400;

DOT_REINDEX_CONTENTLET_MAPPING_TIMEOUT_SECONDS=0 remains a full off switch (runs the mapping inline, no executor, no semaphore) and still works with an open circuit, so it stays available as a mitigation.

New configuration

Property Default Purpose
REINDEX_CONTENTLET_MAPPING_MAX_ABANDONED 32 abandoned-task ceiling that opens the circuit
REINDEX_THREAD_SLEEP_WHEN_DEGRADED 30000 back-off while the guard is refusing work

Not included

Recovering parked rows through a maintenance action rather than manual SQL. It is in the issue's acceptance criteria and is worth doing, but it is a UI/maintenance-portlet change rather than part of this defect's mechanism.

🤖 Generated with Claude Code

This PR fixes: #37038

… indexing (#37038)

PR #36499 bounded per-entry reindex mapping so a hung `stat(2)` on network-backed
storage could not wedge the reindex thread (#36498). The bound leaks: the
semaphore permit is released inside the submitted task's `finally`, which is
exactly the code a task that never runs can never reach. The cap is therefore
cumulative rather than concurrent — 8 abandoned tasks over the life of the JVM
killed content indexing until the node was restarted, while every subsequent
entry was charged a retry until it parked at priority 505, past the
`priority <= 400` the queue loader reads. Net effect was worse than the bug it
fixed: that one froze indexing with the queue intact; this one destroyed the
backlog.

Four changes:

1. Split the accounting in two and move the tasks to platform threads.
   Concurrency is now a real concurrency cap whose permit the *caller* releases
   in a `finally` that always executes; abandonment is a separate counter, only
   decremented by a task that actually finishes, whose ceiling opens a circuit
   breaker. Platform threads are what make this safe: an abandoned virtual
   thread keeps pinning a carrier from a JVM-wide pool of
   `availableProcessors()` (file I/O does not unmount), which is what forced the
   release into the task body in the first place. An abandoned platform thread
   costs only its own stack and steals nothing, and both counters are bounded, so
   worst-case thread count is `maxConcurrent + maxAbandoned`.

2. Never charge a retry for a pool rejection. `ReindexPoolExhaustedException`
   distinguishes "the pool is unavailable" from `ReindexMappingTimeoutException`
   ("this entry's own mapping overran"), and only the latter reaches
   `markAsFailed`. A rejected entry is left byte-for-byte untouched.

3. Fail loudly instead of silently. A new `reindex-mapping` health check reports
   stalled indexing, and an open circuit makes the reindex thread back off
   (`REINDEX_THREAD_SLEEP_WHEN_DEGRADED`, default 30s) rather than spinning the
   journal at `SLEEP_ON_ERROR` speed. The exhaustion log is throttled and no
   longer asserts that storage is down unconditionally.

4. Move the index bulk enqueue out of the guarded region. `BulkProcessor.add()`
   blocks on the client's in-flight semaphore (`REINDEX_THREAD_CONCURRENT_REQUESTS`
   defaults to 1) and its backoff budget is 20s x 10 = 200s, greater than the
   120s mapping timeout — so index slowness alone could trigger the guard with
   no storage fault at all. Mapping now returns `MappedDocument`s and the enqueue
   happens outside the timeout.

Because the abandonment counter heals when a stuck task eventually returns,
recovery no longer needs a restart.

New config: `REINDEX_CONTENTLET_MAPPING_MAX_ABANDONED` (32),
`REINDEX_THREAD_SLEEP_WHEN_DEGRADED` (30000).
`REINDEX_CONTENTLET_MAPPING_TIMEOUT_SECONDS=0` still disables the guard entirely.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@claude

claude Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @wezell's task in 4m 48s —— View job


Reindex mapping guard fix — review

I traced the full changed set (10 files) against origin/main, focusing on the concurrency accounting, the exception split, the enqueue extraction, and the health-check wiring.

Verified correct:

  • Permit accounting is now leak-free. concurrency is acquired/released by the caller in a finally that always runs (ReindexMappingRunner.run L112–121); the abandonment counter is a separate AtomicInteger only decremented by a task that actually returns. The STATE_RUNNING → ABANDONED/FINISHED CAS dance correctly handles the timeout-vs-finish race in both orderings, so the counter can never be double-charged or stranded.
  • Exception split is wired end-to-end. ReindexPoolExhaustedException (infra) is rethrown untouched from appendBulkRequestToProcessor and propagates through appendToBulkProcessorEntry (unchecked, extends DotRuntimeException) up to ReindexThread L249, which backs off. ReindexMappingTimeoutException and mapping failures fall to catch (Exception) → markAsFailed. Catch ordering is correct (ReindexPoolExhaustedException before Exception). The rejected-entry path never touches markAsFailed, which is the core data-loss fix.
  • Enqueue extraction preserves behavior. The old HashSet "dedup" in addBulkRequestToProcessor was a no-op (it was only ever called with single-element List.of(contentlet)), so removing it changes nothing. id/mapping/isWorking/isLive computation and the working/live × reindex index-target matrix are byte-for-byte preserved in enqueueMappedDocuments; markAsReindexed() still fires after enqueue.
  • Health check is safe. MONITOR_MODE converts DOWN → DEGRADED (HealthCheckBase.applySafetyMode), so a stalled-indexing state is reported but does not fail readiness and pull the node out of rotation — which matches the PR's own reasoning that pages keep rendering. sharedMappingRunner() and the instance mappingRunner() resolve the same Lazy, so the check reports on the live runner.
  • Constructor signature change (+maxAbandoned) is reflected in all test call sites; no stale callers of the old 3-arg ctor or mapEntryForProcessor/addBulkRequestToProcessor.

New Issues

  • 🟡 Medium: dotCMS/src/main/java/com/dotmarketing/common/reindex/ReindexThread.java:216 — throttle interval 10*60*10000 is 6,000,000 ms (100 min), almost certainly a typo for 10*60*1000 (10 min). Impact is negligible because the break on the next line exits the loop immediately after this single log line, so the throttle window is effectively never consulted — worth correcting for clarity but not blocking. Fix this →

Note (non-blocking, no action needed)

  • enqueueMappedDocuments now runs on the reindex thread outside the guard, so a fully-down index endpoint can block that thread on BulkProcessor.add() for the client's backoff budget (~200s) before the entry is failed. This is deliberate and documented in the PR, and it self-limits (the enqueue eventually returns/throws rather than wedging forever like ReindexThread: single hung filesystem stat on network storage silently halts all content indexing #36498), so it is not a defect — flagging only so it's on record as the accepted tradeoff.

No critical or high-severity issues. The design is sound and the accounting is provably leak-free.

· branch issue-37038-reindex-mapping-permit-leak

…y simulates dead storage

`poolRejectionLeavesTheJournalRowUntouched` failed 4/4 in MainSuite 2b. The
production guard was correct — the log shows the circuit opening as designed
("1 of 1 abandoned slots now in use") — but the test's simulated hang let
`InterruptedException` escape `CountDownLatch.await`.

The timeout path calls `future.cancel(true)`, so the interrupt ended the task,
its `finally` ran, and the abandoned counter went straight back to 0. The circuit
closed between the two entries and the second one mapped normally instead of
being rejected.

That is the right behavior for interruptible work — a task that answers an
interrupt is slow, not wedged, and must return its slot (covered by
`interruptibleSlowTaskIsFreedAndNotCountedAsAbandoned`). The test was simulating
slow storage while asserting the consequences of dead storage.

Swallow the interrupt, matching the unit-test helper and a real uninterruptible
native stat(2). Also strengthens the pre-existing
`hungMappingFailsItsJournalEntryAndTheBatchContinues`, which was passing while
only ever simulating an interruptible stall.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@fabrizzio-dotCMS fabrizzio-dotCMS added the PR: docker image Build & push a per-PR test image to dotcms/dotcms-test label Aug 13, 2026
@github-actions

github-actions Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

🐳 PR Docker test image

Latest build for commit 1e471ec pushed to dotcms/dotcms-test:

docker pull dotcms/dotcms-test:pr-37041-issue-37038-reindex-mapping-permit-leak
docker pull dotcms/dotcms-test:pr-37041-issue-37038-reindex-mapping-permit-leak_1e471ec

Ref #37038. The reindex loop logged "Shutdown detected, stopping reindex
operations" via Logger.info on every iteration while draining, spamming
the log during shutdown. Switched to Logger.infoEvery to throttle it.

@wezell wezell 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.

Tested against 400,000 contentlets. 3 legitimately failed, as they should have. Looks good. Added a logging change to prevent log span.

@wezell
wezell enabled auto-merge August 14, 2026 17:07
@wezell
wezell added this pull request to the merge queue Aug 14, 2026
Merged via the queue into main with commit 18468a4 Aug 14, 2026
67 checks passed
@wezell
wezell deleted the issue-37038-reindex-mapping-permit-leak branch August 14, 2026 18:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Area : Backend PR changes Java/Maven backend code PR: docker image Build & push a per-PR test image to dotcms/dotcms-test

Projects

Status: No status

2 participants