allthingssecurity opened a new pull request, #30763:
URL: https://github.com/apache/camel/pull/30763

   # Description
   
   [CAMEL-27415](https://issues.apache.org/jira/browse/CAMEL-27415)
   
   The change streams consumer keeps only the token of the last event whose 
exchange completed (`MongoDbChangeStreamsThread`, `resumeToken`). On a 
collection that sees few changes while the rest of the replica set is written, 
the change stream keeps reading the oplog, but that token falls out of the 
oplog window. Then:
   
   - after a failure that the driver cannot resume itself (the server cannot be 
reached for longer than the server selection timeout, or a slow failover), the 
consumer opens the change stream again with `resumeAfter` that token. MongoDB 
answers ChangeStreamHistoryLost (286). Only InvalidResumeToken (260) is 
handled, so the error goes back to the run loop, which tries the same token 
after `cursorRegenerationDelay` for as long as the route runs. Changes made 
afterwards are still in the oplog but are never routed;
   - with `changeStreamTokenRepository`, every start of the route reads that 
token and fails with `FailedToStartRouteException ... error 286`. The only way 
out is to delete the stored token by hand.
   
   The same happens when every event since the stored token failed, and the 
oplog rolls past it.
   
   We already noted the 286 retry loop as a follow-up in the PR of CAMEL-26992 
(#30136).
   
   Changes, in `MongoDbChangeStreamsThread`:
   
   - The loop reads with `tryNext()` instead of `hasNext()`/`next()`. 
`hasNext()` waits for the next event across the getMores that return none, and 
the cursor's resume token is only refreshed by `tryNext()` after an empty 
getMore (MongoDB Java driver 5.14, `MongoChangeStreamCursorImpl.tryNext` sets 
it to `getPostBatchResumeToken()` when the batch is empty; read with javap). A 
getMore without an event still waits on the server for up to its maxAwaitTime 
(1 second by default), so the loop does not spin.
   - After a `tryNext()` that returns null, the consumer takes 
`getResumeToken()`, the post batch resume token, as the token to resume after, 
and commits it when it differs from the current one. It does so only when the 
exchange of the last event this cursor returned completed: an event whose 
exchange failed is still read again by a new cursor, as before, unless a later 
event completed (as before, the token of that event, committed when its 
exchange completed, already passes the failed one).
   - `tryNext()` returns null without a getMore once the server closed the 
cursor (after an invalidate event; `CommandCursor.tryHasNext` only sends a 
getMore while the server cursor is open). The loop then checks 
`getServerCursor()` and ends, where `hasNext()` returned false, so the 
invalidate handling of CAMEL-25946 (`startAfter`) is unchanged.
   - A token that the oplog no longer has (286, or 280 and 40576 of MongoDB 
4.2, the same codes the start time of CAMEL-26992 uses), on `resumeAfter` or on 
the `startAfter` that follows an invalidate token, is dropped with a WARN, and 
the change stream is opened at the current time through the same path as a 
start without a token (ping, then no resume option). This is the fallback the 
consumer already uses for a start time that the oplog no longer has. The stored 
token is replaced by the next one the consumer commits, which is the post batch 
resume token of the first empty getMore.
   - A commit of the post batch resume token that fails goes to the exception 
handler of the consumer, as a failed commit of an event token does.
   
   Behaviour visible to users (upgrade guide entry for 4.24, and a paragraph in 
the "Change Streams Resume" section of the component page):
   
   - With `changeStreamTokenRepository`, the repository is also written while 
no change arrives: once per getMore whose post batch resume token differs from 
the stored one, so at most about once a second (on an idle replica set the 
token moves about every 10 seconds, with the periodic no-op writes of the 
primary). A `FileStateRepository` appends a line each time (it truncates at 
`maxFileStoreSize`).
   - A route started again after a quiet period resumes after the stored post 
batch resume token, so changes made while the route was stopped are routed. 
Before, a route that had not consumed any change since its start had nothing 
stored and started at the current time.
   - A token that the oplog no longer has no longer fails the route start, and 
is no longer tried for ever: the consumer logs the WARN and starts at the 
current time, so the changes since that token are not consumed. This applies to 
an explicit `changeStreamToken` too, which is read on every start.
   - The post batch resume token is not passed to a resume strategy 
(`resumable()`): it gets the tokens of the exchanges (the `CamelOffset` header) 
as before. A route that uses only a resume strategy still resumes from the last 
event token after a restart, and gets the WARN fallback if that token left the 
oplog.
   
   Lead, not changed: the start time fallback of CAMEL-26992 still skips 
changes that the oplog holds when it falls back to the current time. With this 
change it is only used until the first getMore of the change stream returned, 
since the post batch resume token replaces it after that; the fallback itself 
and its test (`startNoLongerInTheOplogStartsAtTheCurrentTime`) are unchanged.
   
   Not changed: a slow write of the token store can still finish after `stop()` 
gave up waiting for the consumer thread (it waits only while an exchange is 
routed), and move the stored token back once the route was started again. This 
needs a write slower than the shutdown timeout; it is a separate change to 
`stop()`.
   
   Model: found with a TLA+ model of the consumer thread, its run loop, the 
commit manager and the oplog (2 route starts, a thread that outlives a stop, 4 
writes of this and other collections, 2 truncations of the oplog, failed 
getMores, failed opens, failed routes and commits). I adapted it to the fix 
(`Fixed` switch). On main the liveness property "while the route is started 
every change is routed or skipped by an announced fallback" is violated (the 
consumer retries the lost token for ever; everystate, 1,360,458 distinct states 
with a consumer that is caught up). With the fix it holds (8,418,062 distinct 
states), and so does the safety property that a committed token never passes a 
change that was neither routed nor skipped by design or by an announced 
fallback (19,709,751 distinct states with every failure enabled). A further 
property, that a committed post batch resume token never passes a change whose 
exchange failed and never completed (unless a later change completed, or a ch
 ange stream opened at the current time skipped it), holds with the fix 
(1,366,122) and fails for a version that takes the post batch resume token also 
after a failed exchange. TLC gives the same counts on the smaller 
configurations (1,366,122 and 410,923; liveness with 3 writes: main violated, 
fix 1,489,316).
   
   Tests:
   
   - New `MongoDbChangeStreamsPostBatchResumeTokenTest`, with a fake change 
stream over an oplog of this and other collections that answers like the driver 
5.14 cursor (comment on the fake): `hasNext()` waits across empty getMores 
without changing the resume token, `tryNext()` sends one getMore (50 ms here) 
and then gives the post batch resume token, the token after `next()` is the one 
of the event (the fake has one event per batch; with several, the driver gives 
the post batch resume token already after the last event of a batch, which the 
consumer does not read), `getServerCursor()` is null once the server closed the 
cursor, `resumeAfter` a position the oplog no longer has fails with 286, 
`resumeAfter` an invalidate token fails with 260 before the oplog is read.
     - 
`cursorOpenedAgainOnAQuietCollectionResumesAfterThePostBatchResumeToken`: on 
main `[now 2, resumeAfter 2 -> 286]`, the consumer retries the lost token;
     - 
`routeStartedAgainAfterAQuietPeriodResumesAfterTheStoredPostBatchResumeToken`: 
on main `FailedToStartRouteException ... error 286`; with the fix the change 
made while the route was stopped is routed;
     - `storedTokenNoLongerInTheOplogStartsAtTheCurrentTime` and 
`storedInvalidateTokenNoLongerInTheOplogStartsAtTheCurrentTime`: on main the 
route does not start (286); with the fix one WARN, the change stream starts at 
the current time, and the stored token is replaced;
     - 
`tokenNoLongerInTheOplogWhenTheCursorIsOpenedAgainStartsAtTheCurrentTime` 
(every event after the stored one failed): on main the consumer retries the 
lost token for ever;
     - `postBatchResumeTokenDoesNotPassAnEventWhoseExchangeFailed`: control, 
passes on main too: the failed event is read again by the new cursor.
   - On main 5 of the 6 fail (the control passes). Two mutants were checked: 
taking the post batch resume token also after a failed exchange fails the 
control and the "every event failed" test; keeping it only in memory (not 
committed) fails the restart test.
   - The other change stream tests and the DST world now stub `tryNext()` and 
`getServerCursor()` instead of `hasNext()` (a Mockito cursor without stubs 
returns null for both, which ends the loop as `hasNext()` returning false did). 
`FakeMongo` of the DST world answers `tryNext()` and `getServerCursor()` like 
the driver; its post batch resume token is the token of the last event the 
cursor returned (an assumption written in its Javadoc: the world writes no 
other collection and has no filter, so this is the same position), so the world 
does not exercise the new commits, only the new loop.
   - camel-mongodb unit tests: 1122 run (the 1000 seeds of the DST world among 
them), 0 failures. The change stream tests 
(`MongoDbChangeStreamsPostBatchResumeTokenTest`, 
`MongoDbChangeStreamsReopenTest`, `MongoDbChangeStreamsInvalidateTest`, 
`MongoDbConsumerCursorRegenerationTest`, `MongoDbConsumerStopTest`) 20 times in 
one JVM: 480 run, 0 failures. The ITs need a MongoDB container and were not run 
locally (CI runs them). Built offline with the cached MongoDB driver 5.14.0.
   
   Backport: this builds on CAMEL-26992, CAMEL-25946 and CAMEL-25679, which are 
on main only. camel-4.18.x also resumes only after the last event token 
(`resumeAfter`, and `hasNext()` in the loop), so a lost token fails the open 
there too, but its run loop is older (a failed open there ends the consumer 
thread); a backport would be a separate patch. I did not run anything on 4.18.x.
   
   # Target
   
   - [x] I checked that the commit is targeting the correct branch (Camel 4 
uses the `main` branch)
   
   # Tracking
   - [x] If this is a large change, bug fix, or code improvement, I checked 
there is a [JIRA issue](https://issues.apache.org/jira/browse/CAMEL) filed for 
the change (usually before you start working on it): 
[CAMEL-27415](https://issues.apache.org/jira/browse/CAMEL-27415).
   
   # Apache Camel coding standards and style
   
   - [x] I checked that each commit in the pull request has a meaningful 
subject line and body.
   - [ ] I have run `mvn clean install -DskipTests` locally from root folder 
and I have committed all auto-generated changes.
     (I built and tested the affected module, including the formatter and 
import-sort plugins, and copied the component page to the catalog. I did not 
run the full root build.)
   
   # AI-assisted contributions
   
   - [x] If this PR includes AI-generated code, commits have proper 
co-authorship attribution (e.g., `Co-authored-by` trailers) and the PR 
description identifies the AI tool used.
     This PR was prepared with Claude Code (Claude Opus 5.5). The commits carry 
a `Co-Authored-By` trailer.
   
   _Claude Code on behalf of allthingssecurity_
   
   🤖 Generated with [Claude Code](https://claude.com/claude-code)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to