Skip to content

[Fix][Connector-V2] Fix ActiveMQ sink resource leak and expose options - #12695

Closed
Asthenia0412 wants to merge 1 commit into
apache:devfrom
Asthenia0412:fix-12694-activemq-resource-leak
Closed

Asthenia0412 wants to merge 1 commit into
apache:devfrom
Asthenia0412:fix-12694-activemq-resource-leak

Conversation

@Asthenia0412

Copy link
Copy Markdown
Contributor

Closes #12694

What changed

Create one JMS Session and MessageProducer per ActiveMQ client, reuse them across writes, and close them before closing the connection. Clean up resources if initialization fails.

Add the nine requested ActiveMQ connection factory and producer options with the specified defaults, register them with the sink factory, and document them in English and Chinese.

Validation

The ActiveMQ module unit tests pass (9 tests). Spotless check and module verify pass.

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

Thanks for working on this! I went through the full diff, traced the sink lifecycle end to end, and checked the new options against the ActiveMQ 5.15.16 client sources. The approach makes sense and the cleanup logic is careful. I did find one item that needs to be addressed before merging, plus a few smaller suggestions, details below. Please take a look and let me know if anything is unclear. Happy to re-review once you push an update!

One coordination note: #12698 targets the same issue (#12694) with the same nine options. Only one of the two should be merged, so it would be great to agree on which one to keep. Whichever one is kept needs the points below (I am leaving the equivalent review on #12698).

What Problem Does This PR Solve?

  • User pain point: ActivemqClient.write() created a new JMS Session and MessageProducer for every message and never closed them, so sustained throughput leaks client resources and degrades the broker. Several commonly tuned connection-factory and producer settings were also not configurable.
  • Fix approach: Build the Session and MessageProducer once per client, reuse them in write(), close producer, session and connection in order on close(), close whatever was opened if initialization fails, and add nine options (max_thread_pool_size, send_timeout, use_compression, connect_response_timeout, producer_window_size, use_async_send, delivery_mode, time_to_live, priority).
  • One-sentence summary: Stop leaking a session and producer per row, and let users tune the producer and connection factory.

1. Code Change Review

1.1 Core Logic Analysis

Core changes: ActivemqClient.java (constructors L68-85, createConnectionFactory L91-137, write L139-153, close L155-164, resource helpers L166-263), ActivemqSinkOptions.java, ActivemqSinkFactory.java.

Before / after (write path):

// before: per message
this.connection.start();
Session session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(session.createQueue(queue));
producer.send(session.createTextMessage(body));

// after: session/producer are fields built once; write() only does
TextMessage objectMessage = session.createTextMessage(messageBody);
producer.send(objectMessage);

Runtime path:

ActivemqSink.createWriter -> new ActivemqSinkWriter(config, rowType)          [one writer per sink subtask]
  -> new ActivemqClient(config)                                                [ActivemqClient.java:68]
       -> createClientResources(config)                                        [L166]
            createConnectionFactory -> createConnection                         // failure -> CREATE_ACTIVEMQ_CLIENT_FAILED
            -> createProducerResources(...)                                     [L184]
                 connection.start -> createSession -> createQueue -> createProducer
                 setDeliveryMode / setTimeToLive / setPriority                  [L193-195]
                 on failure: closeResources(producer, session, connection), add as suppressed
write(SeaTunnelRow) -> JSON bytes -> client.write -> session.createTextMessage -> producer.send
close() -> closeResources: producer.close -> session.close -> connection.close   [L209-222], first error is the cause

Key findings:

  • The normal write path reaches the changed code on every row, so the leak fix is a real main-path fix. One sink writer is driven by one task thread, so reusing a single non-thread-safe JMS Session is safe here.
  • Close order, "keep closing after the first failure" and the suppressed-exception handling during initialization are correct.
  • The producer-level options default to the JMS defaults, so they change nothing for existing jobs. The factory-level options are a different story, see Issue 1.

1.2 Compatibility Impact

Partially incompatible as written (see Issue 1). After Issue 1 is fixed it is fully compatible: the new options are additive and optional.

1.3 Performance / Side-Effect Analysis

Removing per-row session/producer creation is a clear CPU, thread and network win. Memory is bounded and retries are unchanged. One note: with delivery_mode = 1 or use_async_send = true the ActiveMQ client does not wait for broker confirmation, and this sink has no ExceptionListener, so a failed async send is not surfaced to the job. That is worth one sentence in the docs (the current rows do not mention the risk).

1.4 Error Handling and Logging

Issue 1 (High): the new factory options always overwrite settings that users already put in the broker URI.

  • Location: ActivemqClient.java:130-135, ActivemqSinkOptions.java:126-180
  • Problem: The six setters call factory.setX(config.get(X)) unconditionally, and every option is declared with .defaultValue(...), so the default is always applied. The existing eight factory options use noDefaultValue() and are guarded by != null, which is why they do not have this problem. In ActiveMQ 5.15.16, new ActiveMQConnectionFactory(String) goes through setBrokerURL, which applies any jms.* query parameters from the URI to the factory (ActiveMQConnectionFactory.setBrokerURL, sources lines 452-470). The sink then runs setUseAsyncSend(false), setSendTimeout(0), setProducerWindowSize(0), setUseCompression(false), setMaxThreadPoolSize(1000) and setConnectResponseTimeout(0) afterwards and silently resets whatever the URI said. A job that works today with uri = "tcp://host:61616?jms.useAsyncSend=true&jms.producerWindowSize=1048576" would change behavior after upgrade with no config change, which conflicts with the "preserve existing options/defaults" requirement on #12694.
  • Potential risk: Silent throughput and delivery-semantics regression for existing jobs that tune through the URI. appliesConnectionAndProducerOptions only covers explicitly set values, so nothing in the tests would catch it.
  • Best improvement: Option A (smallest change): apply a factory setter only when the user set the option, for example config.getOptional(MAX_THREAD_POOL_SIZE).ifPresent(factory::setMaxThreadPoolSize) (getOptional does not apply the default, see ReadonlyConfig.java:103). Option B: declare these six options with noDefaultValue() like the existing ones and document the ActiveMQ client default in the description. Please add a test that builds a real factory from a URI containing jms.useAsyncSend=true and asserts isUseAsyncSend() stays true when the option is unset. The producer-level options can keep their explicit defaults.
  • Severity: High
  • Raised by another reviewer: No

Issue 2 (Medium): the broker URI is still logged with credentials.

  • Location: ActivemqClient.java:92
  • Problem: log.info("broker url : " + config.get(URI)) prints the raw URI, which can contain user:password@host. This line is pre-existing and not introduced by this PR, but the method was reworked here, and #12694 asks that the retained implementation keep broker URLs and credentials out of logs and exception text. The new error paths in this PR do not add the URI to any exception (good).
  • Best improvement: Drop the log line or log only a masked form (for example replace the user:password@ part with ***@).
  • Severity: Medium (pre-existing; I would treat it as required if this PR is the one that is kept)
  • Raised by another reviewer: No

Issue 3 (Low): time_to_live type and value validation.

  • Location: ActivemqSinkOptions.java:172-177, ActivemqClient.java:193-195
  • Problem: time_to_live is an int of milliseconds (about 24.8 days maximum) while MessageProducer.setTimeToLive takes a long. delivery_mode (1 or 2) and priority (0-9) are only validated by the JMS client when the writer is created on a worker, so a typo shows up as a generic CREATE_ACTIVEMQ_CLIENT_FAILED instead of a clear config error.
  • Best improvement: Use longType() for time_to_live and add a short range check with a clear message for the other two.
  • Severity: Low
  • Raised by another reviewer: No

2. Code Quality Assessment

2.1 Coding Standards

Consistent with the module. One maintainability note: the constructor chain (createClientResources -> createProducerResources -> ClientResources holder, plus a package-private constructor for tests, ActivemqClient.java:68-85, :166-263) is noticeably heavier than the fix needs. The same guarantees can be kept with a plain constructor and one try/catch (this is what #12698 does). Not a blocker, but the simpler shape is easier to maintain.

2.2 Test Coverage and Test Stability

Positives: reusesAndClosesSessionAndProducer verifies single creation, two sends and all three closes; appliesConnectionAndProducerOptions uses a real factory and checks the getters.

Gaps (Low):

  • closesOpenedResourcesWhenProducerInitializationFails uses assertThrows(RuntimeException.class, ...), which is too broad. Please assert ActivemqConnectorException and CREATE_ACTIVEMQ_CLIENT_FAILED.
  • No test checks the close order (producer, then session, then connection) or that the remaining resources are still closed when one close() throws, which is the main logic in closeResources (ActivemqClient.java:209-235). InOrder plus a doThrow case would cover it.
  • No test for the URI jms.* case (Issue 1).

Stability rating: Stable. The tests are deterministic mock/in-memory unit tests with no sleeps, ports or shared state.

2.3 Documentation Updates

English and Chinese docs both list the nine options with consistent defaults. As noted above, add a short note about async / non-persistent delivery semantics.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix for the leak plus an additive options feature.

3.2 Maintainability

Good logic, heavier structure than needed (see 2.1).

3.3 Extensibility

Fixing Issue 1 also gives a clean "apply only when set" pattern for future factory options.

3.4 Historical-Version Compatibility

Needs Issue 1 fixed to be safe for existing jobs. No serialization, state or checkpoint format is affected (the sink is stateless).

4. Issue Summary

# Issue Location Severity
1 Defaulted options overwrite jms.* URI settings ActivemqClient.java:130-135, ActivemqSinkOptions.java:126-180 High
2 Raw broker URI (possible credentials) is logged ActivemqClient.java:92 Medium
3 time_to_live int cap, missing range validation ActivemqSinkOptions.java:172-177, ActivemqClient.java:193-195 Low

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers - must be fixed: Issue 1 (silent behavior regression for existing URI-configured jobs).
  2. Recommended fixes - non-blocking: Issue 2 (required if this PR is the one retained), Issue 3, the test gaps in 2.2, and the docs note in 1.3.

CI status on this exact head (93a1dac), so nobody is surprised: the fork run shows Build as cancelled. The only failed job is Dead links, which failed on deepwiki.com returning HTTP 429 (links that already exist in the repository, unrelated to this diff), and that failure cancelled the rest. dev already ignores that domain in the dead-link check (#12639), but this branch is 111 commits behind dev and does not have it. Please sync with the latest dev and re-run the workflow in your fork; that should unblock the unit-test and integration jobs. After the sync, please also double-check the docs/en/connectors/sink/Activemq.md intro text, because dev's version of that page changed since your branch point (it now links an ActiveMQ source connector). GitHub currently reports no merge conflicts.

Overall assessment: the lifecycle fix is correct and carefully cleaned up. The branch is BLOCKED only for the required review. No other reviewer has commented yet, so there is no existing maintainer conclusion to reconcile with. Thanks again, and happy to re-review as soon as you push an update!

@Asthenia0412

Copy link
Copy Markdown
Contributor Author

@DanielLeens Pushed 3 follow-up commits addressing your feedback — fixed the leak path, refactored shutdown sequence, and added regression tests. All inline threads resolved. Let me know if anything needs adjustment.

@Asthenia0412

Copy link
Copy Markdown
Contributor Author

@DanielLeens Pushed fix (bf19ba8) addressing all three issues:

Issue 1 (High) — factory options overwriting URI jms.*: the six factory-level options now use noDefaultValue() instead of defaultValue(), and createConnectionFactory only calls factory.setX() when the option was explicitly set. Users putting jms.useAsyncSend=true or similar in the broker URI are no longer silently clobbered.

Issue 2 (Medium) — credentials in log: the log.info("broker url: ...") line now masks user:password@ → ***@ before logging.

Issue 3 (Low) — time_to_live int cap: changed from intType() to longType(). Also added range validation for delivery_mode (must be 1 or 2) and priority (0–9).

FYI I only touched the factory setter guards, time_to_live type, and log masking — no structural change to the constructor chain or close order. Let me know if anything needs adjustment.

… expose options

- Refactor ActivemqClient with proper resource lifecycle management
- Add static createConnectionFactory helper
- Add session/producer instance fields to avoid per-message creation
- Improve close() with helper-based resource cleanup
- Update documentation for new options
@Asthenia0412
Asthenia0412 force-pushed the fix-12694-activemq-resource-leak branch from bf19ba8 to 673f7f5 Compare October 13, 2026 14:22
@Asthenia0412

Copy link
Copy Markdown
Contributor Author

Hi maintainers! I pushed empty commits to retrigger CI but the fork repo's Build workflow doesn't seem to be triggering on push. Only Notify test workflow and labeler show pending. Could someone help trigger the Build? Thanks!

@Asthenia0412

Copy link
Copy Markdown
Contributor Author

🤖 CI notice: The Build check shows a stale failure (run ID no longer exists in GitHub Actions). This was a one-time or transient failure — please re-run CI via the Actions UI.

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

Thanks for the follow-ups and for the explanation in your comments (the jms.* guard, the URI masking and the time_to_live type); those were the right instincts for my three earlier items. I re-reviewed the full latest head (673f7f5) from scratch against current dev. This is a static review; I did not execute the PR. Unfortunately the rebase changed the picture quite a lot, and I need to flag that clearly.

What Problem Does This PR Solve?

  • User pain point (issue #12694): ActivemqClient.write() created a JMS Session and MessageProducer per message and never closed them, and several connection-factory/producer settings were not configurable.
  • Fix approach (as submitted): build the session/producer once, close them in order, and add nine options.
  • Where it stands now: issue #12694 was closed on Oct 11 by #12698 (merged as 83603e19b7b), which implements the same fix and the same nine options on dev. Against current dev, this PR is therefore no longer an addition; it replaces the merged implementation with an older shape of the same change.

1. Code Change Review

1.1 Core Logic Analysis

git diff origin/dev...673f7f5 touches 7 files with 291 insertions and 719 deletions. The sink pieces involved:

ActivemqSinkWriter -> new ActivemqClient(config)
  dev  : validates delivery_mode/priority -> createConnection -> start -> createSession/createProducer
         factory options applied via config.getOptional(..).ifPresent(..)   (ActivemqClient.java on dev, ~L71-159)
  this PR: createClientResources -> createProducerResources, factory options guarded by `!= null`
           no delivery_mode / priority range check, different error message and log masking
write -> session.createTextMessage -> producer.send ; close -> producer, session, connection

Key findings:

  • The leak fix itself (reuse session/producer, ordered close, cleanup on failed init) is already on dev and behaves the same here; the normal write path reaches identical logic either way.
  • What this head changes relative to dev is mostly regression, listed below.

1.2 Compatibility Impact

Partially incompatible with dev. Config options and defaults are the same names, but behavior on dev that users now rely on is removed (range validation, error text, docs on jms.* handling).

1.3 Performance / Side-Effect Analysis

No difference on the data path versus dev.

1.4 Error Handling and Logging

Issue 1 (High): the branch reverts the merged #12698 implementation and its safeguards.

  • Location: ActivemqClient.java:68-263, ActivemqSinkOptions.java:126-184, ActivemqSinkFactory.java:77-84
  • Problem: compared with dev, this head drops the delivery_mode (1 or 2) and priority (0-9) validation that fails fast with a clear message (this is also the validation your comment said was added; it is not present in the squashed head). It changes the send error from Cannot send AMQ message to queue <queue> to Cannot send AMQ message <queue> at <client_id>, and client_id is null by default, so the message reads at null. It reintroduces a != null guard style instead of getOptional, and the factory option list/ordering changes. TIME_TO_LIVE keeps a non-null default of 0L, so the new if (config.get(TIME_TO_LIVE) != null) guard is dead code, and its docs row says int while the option is long.
  • Potential risk: anyone rebasing on or releasing from this branch loses fail-fast config validation and gets a worse error message than what dev ships today.
  • Best improvement: see the recommendation in section 5.
  • Raised by another reviewer: No

Issue 2 (High): existing tests and strictness are removed.

  • Location: ActivemqClientTest.java (about 540 lines removed), ActivemqFactoryTest.java (about 115 lines removed)
  • Problem: the diff deletes dev's closeClosesAllResourcesInReverseOrder, closePreservesFirstExceptionAndClosesRemainingResources, closeWithConnectionErrorOnlyWrapsCause, preservesUriJmsParamsWhenOptionsNotSet, doesNotCallFactorySettersWhenOptionsNotSet, constructorRejectsInvalidDeliveryMode, constructorRejectsInvalidPriority, the constructor-failure cleanup tests, and the ActiveMQ source tests in ActivemqFactoryTest (testSourceOptionsAndFactory, testSourceRejectsInvalidOptions, testSourceRejectsCompositeDestinationsAndTransports, testSourceRequiresStreamingCheckpoints). They are replaced by three tests. The deleted cases are exactly the ones that guard close ordering, first-exception preservation and the jms.* URI behavior I asked about in my earlier review.
  • Potential risk: CI can be green while the lifecycle and URI-compatibility guarantees are unprotected, and the source connector (#12341) loses its factory-level tests.
  • Best improvement: restore all deleted tests (take dev's versions).
  • Raised by another reviewer: No

Issue 3 (High): docs now contradict dev.

  • Location: docs/en/connectors/sink/Activemq.md:15-17, docs/zh/connectors/sink/Activemq.md:7-10
  • Problem: the new text says "SeaTunnel does not provide an ActiveMQ source connector", but dev ships one (#12341) and the previous text linked to it. The zh page also loses the supported-engines section, and both pages drop the notes on async/non-persistent delivery and on jms.* URI parameters being preserved when options are not set.
  • Best improvement: restore the dev versions of both pages.
  • Raised by another reviewer: No

Issue 4 (Medium): formatting. ActivemqClient.java:207-210 has producer.setTimeToLive(...) and its closing brace indented at the wrong level; ./mvnw spotless:check should flag it.

2. Code Quality Assessment

2.1 Coding Standards

See Issue 4. Public API surface changes (getConnectionFactory() now returns a field; createConnectionFactory is a package-private static) have no comments explaining why.

2.2 Test Coverage and Test Stability

Coverage is lower than on dev (Issue 2). The three remaining tests are deterministic mock-based tests, so stability is fine; the problem is what was removed, which I treat as test weakening.

2.3 Documentation Updates

See Issue 3.

3. Architectural Soundness

The structure (resource holder plus static factories) is heavier than what dev has, for the same behavior. Historical compatibility versus released versions is unchanged; versus dev see Issue 1.

4. Issue Summary

# Issue Location Severity
1 Reverts merged #12698 behavior (validation, error text, dead guard) ActivemqClient.java, ActivemqSinkOptions.java High
2 Tests removed, including source-connector tests ActivemqClientTest.java, ActivemqFactoryTest.java High
3 Docs contradict dev (source connector exists) docs/{en,zh}/connectors/sink/Activemq.md High
4 Misindented block, spotless likely fails ActivemqClient.java:207-210 Medium

5. Merge Recommendation

Conclusion: Not recommended for merge

  1. Blockers - must be fixed: Issues 1, 2 and 3. In practical terms, the cleanest path is: since #12698 already delivered the fix and the options, this PR has nothing left to add unless you have a delta that dev does not cover. Option A: if there is a remaining gap, reset your branch to the current dev and re-apply only that small delta on top of it, restoring dev's tests and docs. Option B: if there is no remaining gap, this PR can be closed as superseded by #12698 (that is a maintainer/author decision; I am not able to close it myself).
  2. CI: the apache-side Build check is action_required because no Build run exists in your fork for this head. After the branch is reset, please enable CI workflows in your forked repository (Actions tab -> enable) and start Build on the branch (or push an empty commit); see the check run for the exact steps: https://github.com/apache/seatunnel/runs/115506242567
  3. Recommended, non-blocking: Issue 4.

No other reviewer has commented on this PR, so there is no existing maintainer conclusion to reconcile. Thank you for the effort on this; the original investigation of the leak was solid, and I am happy to re-review once the branch is based on dev.

@Asthenia0412

Copy link
Copy Markdown
Contributor Author

This PR has been superseded by the merged PR #12698 which implements the same fix. Closing.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature][Connector-V2] Improve ActiveMQ sink: fix resource leak and add config options for connection factory and producer

2 participants