Skip to content

[FIX] Improved concurrency handling - #3485

Open
chibenwa wants to merge 15 commits into
apache:masterfrom
chibenwa:fix-races
Open

chibenwa wants to merge 15 commits into
apache:masterfrom
chibenwa:fix-races

Conversation

@chibenwa

Copy link
Copy Markdown
Contributor

No description provided.

@chibenwa
chibenwa marked this pull request as ready for review November 30, 2026 07:51
chibenwa and others added 15 commits December 1, 2026 09:16
… slot frees up

throttle() counted a request before adding it to the queue. A request
completing in between released its slot and polled a still empty queue:
the new request then waited in the queue while nothing ran, and nothing
would ever poll it again. With a low concurrency (or enough occurrences
under load) every IMAP command of the node ended up waiting forever.

Counting then queueing a request, and releasing a slot then polling the
queue, now happen under a single lock, so a request is either executed
right away or dispatched by the completion that frees its slot.

The jcstress test reproducing the lost wake-up is run by a JUnit test.
…are reported next time

Unsolicited responses copied the pending changes of the selected mailbox,
wrote them, then cleared everything, dropping what other sessions changed
in between.

Now only what was reported is forgotten:
 - an EXPUNGE received while responses are written is reported (EXPUNGE or
   VANISHED) in the next response, and its UID leaves the MSN map then,
 - the size change is consumed when read, so a message added meanwhile gets
   its EXISTS in the next response,
 - only the flag updates that were fetched are cleared, the others get their
   FETCH FLAGS in the next response,
 - new applicable flags are acknowledged before the FLAGS response is built,
   so a keyword created meanwhile is announced next time.
A change delivered to the IDLE listener while DONE was handled could still
be pushed after the tagged OK of IDLE: the EXPUNGE then arrived with no
command in progress, and the MSNs shifted under the command pipelined after
DONE, which could act on another message than the one the client meant.

The listener now pushes the changes on the event loop of the connection,
where DONE is handled, and only while IDLE is still active: either the
changes are written before the tagged OK, or they are left to the next
command, which reports them in its own unsolicited responses. Responses
pushed from the event loop are written right away, in order with the
handling of the next client line.
…e handle of the next one

When a request completes, the heartbeat handler is removed and the
in-flight handle cleared before the linearizer slot is released, under
its lock. A request read on the event loop right after the release thus
keeps its heartbeat and its in-flight handle, so that it can still be
cancelled upon disconnection.
…nnections of an IP

When several connections of an IP without a counter yet became active at
once, only the one creating the counter was meant to skip the limit check,
but the others incremented that counter without comparing it with the
limit, so they all stayed open.

The counter is now obtained with computeIfAbsent, then incremented and
checked against the limit for every connection.
… being emitted

ClientContext.clean() completed the push sink without the lock that
StateChangeListener holds while emitting. A close (user disconnection,
push disable, end of the WebSocket) racing with a push in progress threw
EmissionException, so the sink was not completed, the context stayed in
the connected users and the disconnection of the user's other
connections was aborted.

The completion now takes the sink lock and waits for the push in
progress, and never throws. The EventSource ping is emitted under the
same lock, so it no longer collides with a push.
…nd no longer leaks its listener

KeyRegistrationHandler.register added the listener to the local registry when
the Mono was assembled, but handed out the Registration (the only way to remove
it) only once the RabbitMQ bind completed. A caller cancelling in between (IMAP
disconnect during SELECT, WebSocket closed during push enable) or a bind failing
after its retries left the listener registered forever, and as later listeners
of the key were not "first", the key was never bound again on this node.

The listener is now added on subscription, and removed (with the unbind if it
was the last one) when the caller does not get the registration: on cancel or
on error. Either the caller gets the registration, or the listener is removed.
…e last one unbinds

When the last listener of a key unregistered, KeyRegistrationHandler scheduled
the RabbitMQ unbind on its own. A listener registering the same key meanwhile
was "first" again and scheduled its bind independently, so the broker could get
the bind before the unbind and end with the key unbound while a listener is
registered: that node then missed the events of the key published by the other
nodes, for as long as any listener of the key remained.

Once the unbind is acknowledged, the registry is checked again and the key is
bound again if a listener registered in between. Bindings are idempotent, so
the extra bind is harmless when the new listener's own bind came after.
…nning after dispose

restart() read the current runner, installed a new one and disposed the
one it had read, without any lock. Two concurrent restarts (RabbitMQ
consumers health check, reconnection handler, WebAdmin/JMX) could both
dispose the same previous runner: one of the two new runners was then
referenced by nobody, kept consuming the spool above the configured
concurrency and was not stopped by dispose() at shutdown.

restart() and dispose() are now serialized and the runner is safely
published, so each restart disposes the runner it replaces and
dispose() stops the last one.
…ted task

The task details projection handled each event by loading the details,
applying the event and saving the whole details back. A progress update
(AdditionalInformationUpdated) handled while the task completed could
save the IN_PROGRESS details it had loaded over the COMPLETED ones, so
the task was reported as running for good. The same held for a cancel
request racing with the completion.

The projection now saves the updated details only if the stored status
is still the loaded one (computeIfPresent in memory, a conditional
UPDATE for PostgreSQL), and applies the event again to the fresh
details otherwise. An event that does not apply to the loaded status
is no longer written back.

Cassandra has no such conditional write: there a progress update only
writes the additional information column (along with the immutable
type and submission columns), never the status nor the dates, so it
can no longer revert a status. Status transitions are still written
unconditionally on Cassandra: a cancel request racing with the
completion can still leave the task as CANCEL_REQUESTED, and a progress
update racing with the completion can replace the final additional
information with the progress one.
…reply

VacationMailet checked the notification registry, sent the reply and only
then registered the notification, so two mails from the same sender handled
at the same time by two spooler threads each got a reply.

The notification registry now offers registerIfAbsent, which registers the
notification unless an unexpired one exists and tells whether the caller won.
VacationMailet registers first and sends the reply only when the registration
won. The reply period, expiry and flush on vacation update are unchanged.

registerIfAbsent is atomic in memory, and in Postgres through an
INSERT ... ON CONFLICT that replaces only an expired row. Cassandra keeps
the default implementation, a check followed by a registration: two mails
handled at the very same time can still both get a reply there, the window
being narrowed to the time between the check and the registration instead
of including the sending of the reply.
…identity

IdentityRepository.update read the custom identity, patched it and wrote
it back whole with an unconditional upsert: a destroy landing between the
read and the write was undone and the identity reappeared.

The update of an existing custom identity now goes through
CustomIdentityDAO.update, which only writes a row that still exists: a
plain UPDATE checking the affected row count in Postgres, a locked
read-modify-write on a synchronized table in memory. An identity
destroyed in the meantime is reported as not found. Creating the override
of a server-set identity is unchanged.

Cassandra keeps its read then write update: a destroy landing between the
read and the write of the DAO can still bring the identity back there,
the window being narrowed to the DAO update itself.
… was in flight

The sid -> tokens index only knows a token once the IdP answered. A
logout landing in between evicted nothing, and the token kept
authenticating JMAP requests until the cache expiration. With Caffeine,
an expired token reloaded before the asynchronous removal listener of
the expired entry ran also ended up cached but unindexed, so a later
logout missed it.

invalidate(sid) now records the session as logged out for the cache
expiration before reading the index, and a token of that session is
refused (LoggedOutSessionException, answered 401 by the OIDC
authentication strategy) and evicted:
- Caffeine checks the mark on every lookup (a local read), which covers
  both the in-flight validation and the reloaded, unindexed token;
- Redis writes a separate <token prefix>logged_out_sid_<sid> key
  (SET EX) and checks it with EXISTS after caching a resolved token.
  Existing token and sid keys are unchanged. Each command touches one
  key and is awaited before the next, so this holds on Redis Cluster.

The Redis Sentinel test extension now authenticates its FLUSHALL, so
the tests no longer share state through a logged-out mark.
ImapConfiguration.DEFAULT_CONCURRENT_REQUESTS is 128, the documentation
said 20.
Raise sizeChanged only after the added UIDs are recorded in the
UID/MSN converter and recent set. Otherwise a concurrent
unsolicitedResponses call could reset the flag and send the old
counts.

Keep a pending applicable-flags update when a later event brings no
new user flag, so the FLAGS/PERMANENTFLAGS response is not dropped
before the client is told.

@Arsnael Arsnael left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'm good with this :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants