Skip to content

Adds CouchbaseIO, a Java connector for Couchbase Server. Fixes #18381 - #40648

Open
nitinware wants to merge 29 commits into
apache:masterfrom
nitinware:couchbaseio
Open

nitinware wants to merge 29 commits into
apache:masterfrom
nitinware:couchbaseio

Conversation

@nitinware

@nitinware nitinware commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Adds CouchbaseIO, a Java connector for Couchbase Server. Fixes #18381.

Design discussion: https://lists.apache.org/thread/cvzpfnw717zbnf7z6slfkfbp6zg6604g

Design doc: https://docs.google.com/document/d/1ALlXaiVSa_Dn9jJxM9MsmhEhBLPW_FP8RswN8HG33iU

Implementation

The commits are organized by component to make the changes easier to review:

  1. Write: Concurrent, batched UPSERT operations using withIdFn and withContentFn, with bounded in-flight concurrency and flushing in @FinishBundle.
  2. JsonObjectCoder: UTF-8 JSON encoding for Couchbase SDK JsonObject values.
  3. Read: Bounded SQL++ query execution as a single unit of work, with an optional parsing function (defaulting to JsonObject), named/positional parameters, scan consistency, and opt-in withRedistribute() applied after parsing.
  4. Schema-aware reads: readRows(Schema) converts query results into Beam Row values using RowJson, respecting the supplied schema's nullability constraints.
  5. Documentation: Class Javadocs, CHANGES.md, and the connector documentation table.
  6. Review improvements: Display data, a build configuration comment, and an upsert idempotency test.

Testing

  • 39 unit tests across CouchbaseIOTest and JsonObjectCoderTest.
  • 15 Testcontainers integration tests across CouchbaseIOReadTest and CouchbaseIOWriteTest, using couchbase/server:enterprise-8.0.3.
  • Tests cover authentication failures (the password must not appear in errors, toString, or display data), type mismatches, missing required fields, and repeated UPSERT operations.
  • Local validation passes: ./gradlew :sdks:java:io:couchbase:build (Checkstyle, Javadoc, Checker Framework nullness validation, and dependency analysis).
  • checkJavaLinkage could not run locally because of a corporate repository proxy restriction; CI validation is pending.
  • TLS (couchbases://) is delegated to the Couchbase SDK but is not covered by an integration test.

Known limitations / follow-ups

  • Connection lifecycle: One Couchbase Cluster per DoFn instance. JVM-wide sharing may be considered after benchmarking.
  • Source parallelism: SQL++ reads execute as a single unit of work. Partitioned reads are deferred.
  • SchemaTransform / Managed I/O: Deferred pending further community feedback (design doc §12, question 2).
  • Additional capabilities: Advanced write modes, durability configuration, dead-letter handling, and DCP-based CDC are future work.

R: @kennknowles

Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:

  • If this contribution is large, please file an Apache Individual Contributor License Agreement.
  • Replace these instructions with a description of your change and why you have made it.
  • Mention the appropriate issue in your description (for example: addresses #123 or fixes #456).
  • Update CHANGES.md with noteworthy changes.

See CONTRIBUTING.md for more details.

Adds the sdks/java/io/couchbase module with ConnectionConfiguration and
CouchbaseIO.write(), which upserts each element as a JSON document in
batches, with bounded concurrency through the reactive API. Includes unit
tests, Testcontainers integration tests against Couchbase Server 8.0.3,
and a PreCommit workflow for the module.
Encodes a JsonObject as its JSON string, which is 2 to 3 times smaller
than the SerializableCoder Beam would otherwise infer. It will be the
default output coder for CouchbaseIO.read().
Adds CouchbaseIO.read(), which runs a SQL++ query through the reactive
API and streams the rows. Supports named and positional parameters, scan
consistency, a parsing function applied inside the read, an output coder,
and an optional redistribute after parsing. The default output is
JsonObject, encoded with JsonObjectCoder.
@nitinware nitinware changed the title Adds CouchbaseIO, a Java connector for Couchbase Server. Fixes #18381. Adds CouchbaseIO, a Java connector for Couchbase Server. Fixes #18381 [DonNotMerge] Oct 18, 2026
@nitinware nitinware changed the title Adds CouchbaseIO, a Java connector for Couchbase Server. Fixes #18381 [DonNotMerge] [DoNotMerge] Adds CouchbaseIO, a Java connector for Couchbase Server. Fixes #18381 [DonNotMerge] Oct 18, 2026
@kennknowles
kennknowles self-requested a review October 19, 2026 16:03
@github-actions github-actions Bot added the size/xl XL: >=1000 lines changed label Oct 24, 2026
@nitinware nitinware changed the title [DoNotMerge] Adds CouchbaseIO, a Java connector for Couchbase Server. Fixes #18381 [DonNotMerge] Adds CouchbaseIO, a Java connector for Couchbase Server. Fixes #18381 Oct 25, 2026
@nitinware
nitinware marked this pull request as ready for review October 25, 2026 22:48
@codecov

codecov Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 60.86%. Comparing base (d2a9085) to head (61bd00a).
⚠️ Report is 5 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master   #40648      +/-   ##
============================================
- Coverage     60.86%   60.86%   -0.01%     
+ Complexity    14589    14587       -2     
============================================
  Files          2614     2614              
  Lines        267627   267627              
  Branches      11795    11795              
============================================
- Hits         162897   162895       -2     
  Misses        98498    98498              
- Partials       6232     6234       +2     
Flag Coverage Δ
java 65.99% <ø> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@nitinware

Copy link
Copy Markdown
Contributor Author

@kennknowles just checking in on this PR, would appreciate your review whenever you have a chance. Thanks!

@nitinware

Copy link
Copy Markdown
Contributor Author

@kennknowles I’ve synced with master. Could you please approve the pending CI workflows and review the PR when you have a chance? Thanks!

@nitinware

Copy link
Copy Markdown
Contributor Author

@kennknowles, a gentle follow-up whenever you have a chance. I’d appreciate your review, or a suggestion for another reviewer if you’re busy. Thank you!

@nitinware

Copy link
Copy Markdown
Contributor Author

Hi @stankiewicz would you have some time to review this CouchbaseIO PR? I’d appreciate your feedback whenever you have a chance. Thanks!

@nitinware

Copy link
Copy Markdown
Contributor Author

assign to next reviewer

@stankiewicz
stankiewicz self-requested a review November 30, 2026 11:43
@stankiewicz

Copy link
Copy Markdown
Contributor

sure, will look into this!

Comment on lines +57 to +59
DEVELOCITY_ACCESS_KEY: ${{ secrets.DEVELOCITY_ACCESS_KEY }}
GRADLE_ENTERPRISE_CACHE_USERNAME: ${{ secrets.GE_CACHE_USERNAME }}
GRADLE_ENTERPRISE_CACHE_PASSWORD: ${{ secrets.GE_CACHE_PASSWORD }}

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.

#40551 removed gradle enterprise cache

@nitinware nitinware Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Removed the obsolete Gradle Enterprise cache settings

Comment thread sdks/java/io/couchbase/build.gradle Outdated
Comment on lines +29 to +30
implementation "io.projectreactor:reactor-core:3.6.9"
implementation "org.reactivestreams:reactive-streams:1.0.4"

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.

declare version in BeamModulePlugin.groovy. Centralizing those avoids version drift when couchbase_java_client is upgraded.

@nitinware nitinware Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Moved Reactor Core and Reactive Streams dependency declarations into BeamModulePlugin.groovy and updated the module to use the shared references.


/** Writes to a single-node Couchbase Server started by Testcontainers. */
@RunWith(JUnit4.class)
public class CouchbaseIOWriteTest {

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.

should be named IT test.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Renamed to CouchbaseIOWriteIT and updated CI to run the integration-test task. All 6 write integration tests passed locally against Docker.


/** Reads from a single-node Couchbase Server started by Testcontainers. */
@RunWith(JUnit4.class)
public class CouchbaseIOReadTest {

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.

Should be named IT test.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Renamed to CouchbaseIOReadIT and updated CI to run the integration-test task. All 9 read integration tests passed locally against Docker.

Comment on lines +706 to +710
Flux.fromIterable(buffer)
.flatMap(kv -> target.upsert(kv.getKey(), kv.getValue()), maxConcurrency)
.then()
.block();
buffer.clear();

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.

If two elements in the same batch map to the same document ID (e.g., (id1, v1) then (id1, v2)), Flux.flatMap issues both upserts concurrently with no ordering guarantee, so v1 can overwrite v2. Either document that Write requires unique IDs per bundle/batch, deduplicate within buffer (keeping the last value per key), or serialize same-key writes.

@nitinware nitinware Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks @stankiewicz , good catch. Fixed, now each buffered batch is deduplicated by document ID, retaining the last encountered value before issuing concurrent upserts for distinct IDs. The batch-size threshold still counts input elements. Javadoc now clarifies that this does not provide ordering or latest-value guarantees across batches or workers, and the retry wording has been qualified accordingly. Added unit coverage and a Docker integration test for duplicate IDs in full and partial batches. Formatting/Checkstyle, all 41 unit tests, and all 16 integration tests passed locally.

@nitinware

Copy link
Copy Markdown
Contributor Author

Hi @stankiewicz, thanks for the review! I’ve addressed all your comments, and all local checks pass. When you have a chance, could you please take another look and approve if everything looks good? Thank you!

Comment on lines +726 to +732
static Map<String, JsonObject> deduplicateBatch(List<KV<String, JsonObject>> buffer) {
Map<String, JsonObject> documents = new LinkedHashMap<>();
for (KV<String, JsonObject> document : buffer) {
documents.put(document.getKey(), document.getValue());
}
return documents;
}

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.

You can make a buffer a Map< > and just replace the items, this way you will always keep the latest, and when flushing you get all the entries.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Changed the buffer to a map, retaining the last encountered value per document ID. A separate input counter preserves the batch-size threshold. Added coverage for duplicate-only batches and counter resets.

* .withScope("inventory")
* .withCollection("airline"))
* .withIdFn(airline -> airline.getId())
* .withContentFn(airline -> JsonObject.create().put("name", airline.getName())));

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.

withFormatFunction may be better name, aligned with other IOs.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Renamed withContentFn() to withFormatFunction() and updated the implementation, examples, and tests.


abstract Builder<T> setScanConsistency(QueryScanConsistency scanConsistency);

abstract Builder<T> setParseFn(SerializableFunction<JsonObject, T> parseFn);

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.

setRowMapper maybe is better function name.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Renamed the read mapping API to withRowMapper(), with corresponding rowMapper and setRowMapper() names internally. Updated the examples and tests.

* for the previous output type.
*/
public <OutputT> Read<OutputT> withParseFn(SerializableFunction<JsonObject, OutputT> parseFn) {
return new AutoValue_CouchbaseIO_Read.Builder<OutputT>()

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.

toBuilder().set..

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@stankiewicz withRowMapper() can change the output type for example, from Read to Read. toBuilder() returns Builder, so it cannot accept a mapper returning a different type without an unchecked cast. Creating Builder keeps this type-safe and deliberately resets the old coder, which may no longer match the output type. All other configuration is preserved.

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.

@SuppressWarnings("unchecked")
public <OutputT> Read<OutputT> withRowMapper(
    SerializableFunction<JsonObject, OutputT> rowMapper) {
  Builder<OutputT> builder = (Builder<OutputT>) toBuilder();
  return builder.setRowMapper(rowMapper).build();
}

maybe?

Why - if you add new parameters, you don't need to remember to add it to withRowMapper.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Updated to use toBuilder() as suggested. The existing coder is cleared because the mapper may change the output type. Added a test verifying configuration preservation.

}

/** Sets the function that returns the document ID for an element. */
public Write<T> withIdFn(SerializableFunction<T, String> idFn) {

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 curious if we could mimic BigQuery's
withRowMutationInformationFn so eventually this write can also support Delete in the future.
RowMutationInformation would contain op type (upsert today) and ID.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@stankiewicz Adopted withRowMutationInformationFn() with a Couchbase-specific RowMutationInformation containing the document ID and operation. V1 supports UPSERT only, leaving room for future delete support. Updated the examples and tests; all local checks pass.

@nitinware

Copy link
Copy Markdown
Contributor Author

Hi @stankiewicz, thanks for the thorough review! I’ve addressed all your comments, and all local checks pass. Could you please take another look when you have a chance and approve if everything looks good? Thanks!


@Setup
public void setup() {
cluster = config.connect();

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.

maybe connected.bucket(bucket).waitUntilReady(...) when config.bucket() != null

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added a readiness wait when a bucket is configured, using a 30-second timeout. Bucket-free reads remain supported, and the connection is closed if readiness fails.

checkArgument(
mutation.getMutationType() == RowMutationInformation.MutationType.UPSERT,
"Only UPSERT mutations are supported");
buffer.put(mutation.getDocumentId(), formatFunction.apply(element));

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.

make sure formatFunction returns non-null element.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added a non-null check before buffering the formatted document. Added a unit test verifying that null output fails with a clear message and is not buffered.

@stankiewicz

Copy link
Copy Markdown
Contributor

@nitinware overall looks good, few more fixes and it will be ok to merge.

@nitinware

Copy link
Copy Markdown
Contributor Author

Thanks @stankiewicz! I really appreciate your thorough review and helpful suggestions. I’ve addressed the remaining fixes, and all local checks pass. Could you please take another look and approve if everything looks good?

@stankiewicz

Copy link
Copy Markdown
Contributor

Gradle Test Run :sdks:java:io:couchbase:integrationTest > Gradle Test Executor 7 > CouchbaseIOReadIT > classMethod FAILED
    com.couchbase.client.core.error.InternalServerFailureException: Internal Couchbase Server error {"completed":true,"coreId":"0x19732b600000001","errors":[{"code":5000,"message":"GSI CreatePrimaryIndex() - cause: Index creation for index #primary, bucket beam, scope _default, collection _default cannot start. Reason: Create index or Alter replica cannot proceed due to rebalance in progress..","reason":{"_level":"exception","caller":"secondary_index:459","cause":{"error":"Index creation for index #primary, bucket beam, scope _default, collection _default cannot start.","reason":"Create index or Alter replica cannot proceed due to rebalance in progress..","source":"CreatePrimaryIndex()"},"code":4350,"key":"indexing.error","message":"GSI error"},"retry":false}],"httpStatus":500,"idempotent":false,"lastChannelId":"019732B600000001/000000001E48851D","lastDispatchedFrom":"127.0.0.1:36810","lastDispatchedTo":"localhost:32776","requestId":12,"requestType":"QueryRequest","retried":0,"service":{"operationId":"null","statement":"CREATE PRIMARY INDEX ON `beam`.`_default`.`_default`","type":"query"},"timeoutMs":75000,"timings":{"dispatchMicros":243098,"totalDispatchMicros":243098,"totalMicros":315958}}

please run IT tests several times, make sure we don't introduce flakes.

@nitinware

nitinware commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @stankiewicz for the approval and thorough review! Fixed the index-creation race during startup rebalance with a bounded retry. All 17 integration tests passed five fresh-container runs locally, 85 test executions passed. The merge conflict is also resolved.
The latest PreCommit Java Couchbase IO Direct run is awaiting approval. Could you please approve it and merge once checks pass? Thanks!

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.

Add CouchbaseIO

3 participants