Repository navigation
Expand file tree
/
Copy pathWorkerConcurrencyTest.java
More file actions
646 lines (612 loc) · 36.2 KB
/
Copy pathWorkerConcurrencyTest.java
File metadata and controls
646 lines (612 loc) · 36.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
package dev.jinhyeon.notificationlab.worker;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.dockerjava.api.model.PortBinding;
import com.github.dockerjava.api.model.Ports;
import dev.jinhyeon.notificationlab.NotificationLabApplication;
import dev.jinhyeon.notificationlabtest.OffsetCommitPolicy;
import dev.jinhyeon.notificationlab.provider.HttpPushProvider;
import dev.jinhyeon.notificationlab.provider.PushProvider;
import dev.jinhyeon.notificationlab.provider.PushRequest;
import dev.jinhyeon.notificationlab.provider.PushResult;
import dev.jinhyeon.notificationmock.MockPushEndpoint;
import dev.jinhyeon.notificationmock.MockServerApplication;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.apache.kafka.clients.admin.Admin;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.springframework.kafka.config.KafkaListenerEndpointRegistry;
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer;
import org.springframework.kafka.core.KafkaTemplate;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.ConsumerGroupState;
import io.micrometer.core.instrument.MeterRegistry;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.sql.DriverManager;
import org.apache.kafka.clients.admin.OffsetSpec;
import org.junit.jupiter.api.Timeout;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.testcontainers.containers.MySQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.kafka.KafkaContainer;
import org.testcontainers.utility.DockerImageName;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.awaitility.Awaitility.await;
@Testcontainers
class WorkerConcurrencyTest {
@Container
static final MySQLContainer<?> MYSQL = new MySQLContainer<>("mysql:8.4.8")
.withDatabaseName("notification_lab").withUsername("notification_test")
.withPassword(UUID.randomUUID().toString()).withCommand("--default-time-zone=+00:00")
.withUrlParam("connectionTimeZone", "UTC").withUrlParam("forceConnectionTimeZoneToSession", "true")
.withCreateContainerCmdModifier(cmd -> cmd.getHostConfig().withPortBindings(
Arrays.stream(cmd.getExposedPorts()).map(port ->
new PortBinding(Ports.Binding.bindIpAndPort("127.0.0.1", 0), port)).toList()));
@Container
static final KafkaContainer KAFKA = new KafkaContainer(DockerImageName.parse("apache/kafka:4.0.2"))
.withEnv("KAFKA_HEAP_OPTS", "-Xms256m -Xmx512m")
.withCreateContainerCmdModifier(cmd -> cmd.getHostConfig().withPortBindings(
Arrays.stream(cmd.getExposedPorts()).map(port ->
new PortBinding(Ports.Binding.bindIpAndPort("127.0.0.1", 0), port)).toList()));
private ServletWebServerApplicationContext app;
private ServletWebServerApplicationContext mock;
private Admin admin;
private String topic;
private String group;
private OffsetCommitPolicy.Mode offsetMode = OffsetCommitPolicy.Mode.RECORD;
private boolean holdProvider;
@Test
@Timeout(90)
void aggregateAssignmentDoesNotProveThreeIndependentRequestOwners() throws Exception {
var directory = Files.createTempDirectory(Files.createDirectories(Path.of("build/reports/worker-readiness")), "control-");
var evidence = new LinkedHashMap<String, Object>();
Throwable primaryFailure = null;
HeldProvider held = null;
try {
holdProvider = true;
start(1, 1, 1, 5000, 0);
assertThat(container().getAssignedPartitions()).hasSize(6); // The old readiness check passes.
evidence.put("singleConsumer", requireAssigned(1));
evidence.put("legacyAggregateReady", true);
assertThatThrownBy(() -> requireAssigned(3)).isInstanceOf(AssertionError.class);
evidence.put("readyForThree", false);
var first = create(); var second = create();
held = app.getBean(HeldProvider.class);
try {
publish(first, 0);
await().atMost(Duration.ofSeconds(5)).until(() -> app.getBean(HeldProvider.class).active.get() == 1);
publish(second, 1);
await().during(Duration.ofMillis(1200)).atMost(Duration.ofSeconds(4)).untilAsserted(() -> {
assertThat(app.getBean(HeldProvider.class).active.get()).isEqualTo(1);
assertThat(status(second)).isEqualTo("QUEUED");
assertThat(attempts(second)).isZero();
assertThat(stats().requests()).isZero();
assertThat(offset(0)).isZero(); assertThat(offset(1)).isZero();
});
evidence.put("singleOwnerWhileHeld", Map.of("active", 1, "secondQueued", true,
"secondAttempts", 0, "httpCalls", 0, "committed", 0));
} finally { held.release.countDown(); }
awaitCompleted(List.of(first, second), 2);
assertThat(stats().requests()).isEqualTo(2);
app.close(); app = null;
holdProvider = false;
startApplication(3, 2, 1, 5000);
evidence.put("threeConsumers", requireAssigned(3));
assertThat(stats().requests()).isEqualTo(2);
evidence.put("result", "PASS");
} catch (Exception | AssertionError failure) {
primaryFailure = failure;
evidence.put("result", "FAIL"); evidence.put("failureType", failure.getClass().getSimpleName());
throw failure;
} finally {
if (held != null) held.release.countDown();
try { new ObjectMapper().writerWithDefaultPrettyPrinter().writeValue(directory.resolve("result.json").toFile(), evidence); }
catch (java.io.IOException failure) {
if (primaryFailure != null) primaryFailure.addSuppressed(failure); else throw failure;
}
}
}
@ParameterizedTest
@EnumSource(OffsetCommitPolicy.Mode.class)
void twoActiveAndOneWaitingKeepOffsetsAndClaimsBehindCompletedWork(OffsetCommitPolicy.Mode mode) throws Exception {
offsetMode = mode;
holdProvider = true;
start(3, 2, 1, 5000, 0);
var first = create(); var second = create(); var waiting = create(); var later = create();
var held = app.getBean(HeldProvider.class);
try {
publish(first, 0);
await().atMost(Duration.ofSeconds(5)).until(() -> held.active.get() == 1);
// Deliberately exceed the former 1500ms response window. The admitted work
// remains held without starting an HTTP deadline or relying on host speed.
await().during(Duration.ofMillis(1700)).atMost(Duration.ofSeconds(3))
.until(() -> held.active.get() == 1 && stats().requests() == 0);
publish(second, 1);
await().atMost(Duration.ofSeconds(5)).until(() -> held.active.get() == 2);
publish(waiting, 2); publish(later, 0);
await().atMost(Duration.ofSeconds(5)).until(() -> gate().waiting() == 1);
assertThat(gate().active()).isEqualTo(2);
assertThat(held.peak.get()).isEqualTo(2);
assertThat(attempts(waiting)).isZero();
assertThat(attempts(later)).isZero();
assertThat(status(waiting)).isEqualTo("QUEUED");
assertThat(offset(0)).isZero(); assertThat(offset(1)).isZero(); assertThat(offset(2)).isZero();
assertThat(stats().requests()).isZero();
} finally {
held.release.countDown(); // Also release on assertion failure before context shutdown.
}
awaitCompleted(List.of(first, second, waiting, later), 4);
assertThat(held.peak.get()).isEqualTo(2);
assertThat(held.active.get()).isZero();
assertThat(stats().maxActive()).isBetween(1, 2);
assertThat(stats().requests()).isEqualTo(4);
assertThat(offset(0)).isEqualTo(2); assertThat(offset(1)).isEqualTo(1); assertThat(offset(2)).isEqualTo(1);
assertThat(gate().active()).isZero(); assertThat(gate().waiting()).isZero();
System.out.println("WORKER_LIMIT consumers=3 activeCap=2 queueCap=1 peakProvider=2 httpAtMost=2 calls=4 committed=4 heldBeyondFormerWindow=true");
}
@ParameterizedTest
@EnumSource(OffsetCommitPolicy.Mode.class)
void admissionTimeoutLeavesNoClaimAndRecoversUncommittedRecordOnExplicitRestart(OffsetCommitPolicy.Mode mode) throws Exception {
offsetMode = mode;
start(3, 1, 2, 100, 0);
var waiting = create();
var occupied = new CountDownLatch(1);
var release = new CountDownLatch(1);
var holderFailure = new AtomicReference<Throwable>();
// Hold a real admission slot until rejection is observed. A timed HTTP delay can end
// before the second consumer is scheduled on a slower CI host, bypassing the queue.
var holder = Thread.ofPlatform().name("test-admission-holder").start(() -> {
try {
gate().execute(() -> {
occupied.countDown();
try {
if (!release.await(60, TimeUnit.SECONDS)) throw new IllegalStateException("Test holder timed out");
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new IllegalStateException(interrupted);
}
});
} catch (Throwable failure) { holderFailure.set(failure); }
});
try {
assertThat(occupied.await(5, TimeUnit.SECONDS)).isTrue();
publish(waiting, 1);
await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> {
var counter = app.getBean(MeterRegistry.class).find("notification.worker.admission.rejected")
.tag("reason", "timeout").counter();
assertThat(counter).isNotNull();
assertThat(counter.count()).isEqualTo(1);
});
await().atMost(Duration.ofSeconds(15)).until(() -> !container().isRunning());
assertThat(attempts(waiting)).isZero();
assertThat(status(waiting)).isEqualTo("QUEUED");
assertThat(offset(1)).isZero();
assertThat(stats().requests()).isZero();
} finally {
release.countDown();
holder.join(5000);
}
assertThat(holder.isAlive()).isFalse();
assertThat(holderFailure.get()).isNull();
awaitStopped();
container().start(); awaitAssigned();
awaitCompleted(List.of(waiting), 1);
assertThat(stats().requests()).isEqualTo(1);
assertThat(attempts(waiting)).isEqualTo(1);
}
@ParameterizedTest
@EnumSource(OffsetCommitPolicy.Mode.class)
void fullQueueRejectsBeforeClaimWithoutCommittingAndCanBeRestarted(OffsetCommitPolicy.Mode mode) throws Exception {
offsetMode = mode;
start(3, 1, 0, 1000, 1200);
var first = create(); var rejected = create();
publish(first, 0);
await().atMost(Duration.ofSeconds(5)).until(() -> stats().active() == 1);
publish(rejected, 1);
await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> {
var counter = app.getBean(MeterRegistry.class).find("notification.worker.admission.rejected")
.tag("reason", "full").counter();
assertThat(counter).isNotNull();
assertThat(counter.count()).isEqualTo(1);
});
awaitStopped();
assertThat(attempts(rejected)).isZero(); assertThat(offset(1)).isZero();
await().atMost(Duration.ofSeconds(5)).until(() -> status(first).equals("PROVIDER_ACCEPTED"));
container().start(); awaitAssigned();
awaitCompleted(List.of(first, rejected), 2);
assertThat(stats().requests()).isEqualTo(2);
}
@ParameterizedTest
@EnumSource(OffsetCommitPolicy.Mode.class)
void databaseFailureNeverCommitsPastFailedRecordAndRecoversAfterLeaseExpiry(OffsetCommitPolicy.Mode mode) throws Exception {
offsetMode = mode;
start(3, 2, 1, 5000, 300);
var first = create(); var later = create(); var independent = create();
root("CREATE TRIGGER reject_worker_completion BEFORE UPDATE ON notification FOR EACH ROW "
+ "BEGIN IF NEW.notification_id = '" + first.id() + "' AND NEW.status = 'PROVIDER_ACCEPTED' THEN "
+ "SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'synthetic write failure'; END IF; END");
try {
publish(first, 0); publish(later, 0); publish(independent, 1);
awaitStopped();
assertThat(offset(0)).isZero();
assertThat(attempts(later)).isZero();
assertThat(status(first)).isEqualTo("PROCESSING");
assertThat(jdbc().queryForObject("SELECT COUNT(*) FROM delivery_attempt a JOIN delivery_task t USING (task_id) WHERE t.notification_id = ? AND a.outcome='STARTED'", Integer.class, first.id())).isEqualTo(1);
} finally { root("DROP TRIGGER reject_worker_completion"); }
// Simulate lease expiry after correcting the DB fault; real elapsed lease recovery is covered by S5.
jdbc().update("UPDATE notification SET worker_lease_until = TIMESTAMPADD(SECOND, -1, UTC_TIMESTAMP(6)) WHERE notification_id = ?", first.id());
container().start(); awaitAssigned();
awaitCompleted(List.of(first, later, independent), 3);
assertThat(attempts(first)).isEqualTo(2);
assertThat(attempts(later)).isEqualTo(1);
assertThat(jdbc().queryForObject("SELECT COUNT(*) FROM delivery_attempt a JOIN delivery_task t USING (task_id) WHERE t.notification_id = ? AND a.outcome='UNKNOWN'", Integer.class, first.id())).isEqualTo(1);
assertThat(stats().requests()).isEqualTo(4);
}
@ParameterizedTest
@EnumSource(OffsetCommitPolicy.Mode.class)
void shutdownLeavesQueuedRecordUnclaimedAndNewContextFinishesIt(OffsetCommitPolicy.Mode mode) throws Exception {
offsetMode = mode;
start(3, 1, 2, 5000, 1500);
var first = create(); var queued = create();
publish(first, 0);
await().atMost(Duration.ofSeconds(5)).until(() -> stats().active() == 1);
publish(queued, 1);
await().atMost(Duration.ofSeconds(5)).until(() -> gate().waiting() == 1);
var oldGate = gate();
app.close();
assertThat(oldGate.active()).isZero(); assertThat(oldGate.waiting()).isZero();
assertThat(stats().requests()).isEqualTo(1);
// Inspect durable state without starting another consumer first.
try (var connection = DriverManager.getConnection(MYSQL.getJdbcUrl(), MYSQL.getUsername(), MYSQL.getPassword());
var statement = connection.prepareStatement("SELECT attempt_count FROM delivery_task WHERE notification_id = ?")) {
statement.setString(1, queued.id());
try (var rows = statement.executeQuery()) { assertThat(rows.next()).isTrue(); assertThat(rows.getInt(1)).isZero(); }
}
assertThat(offset(1)).isZero();
startApplication(3, 1, 2, 5000);
awaitCompleted(List.of(first, queued), 2);
assertThat(stats().requests()).isEqualTo(2);
assertThat(attempts(queued)).isEqualTo(1);
}
private void start(int consumers, int active, int queue, int waitMs, int delayMs) {
mock = MockServerApplication.start("--server.port=0", "--mock.http.response-delay-ms=" + delayMs,
"--logging.level.root=WARN", "--spring.main.banner-mode=off");
topic = "bounded-worker-" + UUID.randomUUID(); group = "bounded-worker-" + UUID.randomUUID();
startApplication(consumers, active, queue, waitMs);
}
private void startApplication(int consumers, int active, int queue, int waitMs) {
var builder = new SpringApplicationBuilder(NotificationLabApplication.class, OffsetCommitPolicy.Wiring.class);
if (holdProvider) builder.sources(ProviderGateConfiguration.class);
app = (ServletWebServerApplicationContext) builder.run(
"--notification.test.offset.mode=" + offsetMode.name(),
"--server.port=0", "--app.provider.mode=HTTP", "--app.async.relay-enabled=false",
"--app.provider.http.base-url=http://127.0.0.1:" + mock.getWebServer().getPort(),
"--app.provider.http.response-timeout-ms=3000", "--app.provider.http.deadline-ms=4000",
"--app.worker.consumers=" + consumers, "--app.worker.max-active=" + active,
"--app.worker.queue-capacity=" + queue, "--app.worker.queue-wait-ms=" + waitMs,
"--spring.datasource.url=" + MYSQL.getJdbcUrl(), "--spring.datasource.username=" + MYSQL.getUsername(),
"--spring.datasource.password=" + MYSQL.getPassword(), "--spring.kafka.bootstrap-servers=" + KAFKA.getBootstrapServers(),
"--app.async.topic=" + topic, "--app.async.group=" + group,
"--logging.level.root=WARN", "--spring.main.banner-mode=off");
if (admin == null) admin = Admin.create(Map.of("bootstrap.servers", KAFKA.getBootstrapServers()));
OffsetCommitPolicy.requireApplied(app);
awaitAssigned();
}
private record Event(String id, String payload) { }
@Test
void countTimeFlushesLowVolumeTailWithoutTenNewRecords() throws Exception {
offsetMode = OffsetCommitPolicy.Mode.COUNT_TIME;
start(1, 1, 0, 5000, 0);
var events = List.of(create(), create(), create());
for (var event : events) publish(event, 0);
awaitCompleted(events, 3);
assertThat(stats().requests()).isEqualTo(3);
assertThat(offset(0)).isEqualTo(3);
assertThat(offset(1)).isZero(); assertThat(offset(2)).isZero();
System.out.println("OFFSET_TIME_TAIL completed=3 committed=3 countThreshold=10");
}
@ParameterizedTest
@EnumSource(OffsetCommitPolicy.Mode.class)
@Timeout(120)
void parallelCompletionCommitsOnlyTheFinishedPartitionWhileItsPeerIsHeld(OffsetCommitPolicy.Mode mode) throws Exception {
observeParallelOffsets(mode, false);
}
@ParameterizedTest
@EnumSource(OffsetCommitPolicy.Mode.class)
@Timeout(120)
void parallelCompletionPreservesFailedPartitionAndRecoversInANewContext(OffsetCommitPolicy.Mode mode) throws Exception {
observeParallelOffsets(mode, true);
}
private void observeParallelOffsets(OffsetCommitPolicy.Mode mode, boolean failCompletion) throws Exception {
offsetMode = mode;
holdProvider = true;
var directory = Files.createTempDirectory(Files.createDirectories(Path.of("build/reports/worker-offset-order")),
mode.name().toLowerCase(java.util.Locale.ROOT) + (failCompletion ? "-recovery-" : "-release-"));
var evidence = new LinkedHashMap<String, Object>();
var phases = new ArrayList<Map<String, Object>>();
evidence.put("startedAtUtc", Instant.now().toString());
evidence.put("mode", mode.name()); evidence.put("completionFailure", failCompletion);
evidence.put("scope", "parallel consumer threads across partitions; synchronous within each partition");
evidence.put("settings", Map.of("consumers", 3, "maxActive", 2, "queueCapacity", 0,
"maxPollRecords", 1, "ackCount", OffsetCommitPolicy.ACK_COUNT,
"ackTimeMillis", OffsetCommitPolicy.ACK_TIME_MS, "pollTimeoutMillis", 500, "holdLimitSeconds", 45));
evidence.put("phases", phases);
HeldProvider held = null;
boolean triggerInstalled = false;
Throwable primaryFailure = null;
try {
start(3, 2, 0, 5000, 0);
var blocked = create(); var later = create(); var fastFirst = create(); var fastSecond = create();
var events = new LinkedHashMap<String, Event>();
events.put("blocked", blocked); events.put("samePartitionLater", later);
events.put("independentFirst", fastFirst); events.put("independentSecond", fastSecond);
held = app.getBean(HeldProvider.class);
held.holdOnly(blocked.id());
try {
publish(blocked, 0);
assertThat(held.entered.await(10, TimeUnit.SECONDS)).isTrue();
publish(later, 0);
publish(fastFirst, 1); publish(fastSecond, 1);
await().atMost(Duration.ofSeconds(12)).untilAsserted(() -> {
assertThat(status(fastFirst)).isEqualTo("PROVIDER_ACCEPTED");
assertThat(status(fastSecond)).isEqualTo("PROVIDER_ACCEPTED");
assertThat(offset(1)).isEqualTo(2);
});
// Longer than ACK_TIME and two poll intervals; the gate, not elapsed HTTP delay, holds p0.
await().during(Duration.ofMillis(1200)).atMost(Duration.ofSeconds(4)).untilAsserted(() -> {
assertThat(offset(0)).isZero(); assertThat(offset(1)).isEqualTo(2);
assertThat(status(blocked)).isEqualTo("PROCESSING");
assertThat(attempts(blocked)).isEqualTo(1);
assertThat(status(later)).isEqualTo("QUEUED");
assertThat(attempts(later)).isZero();
assertThat(stats().requests()).isEqualTo(2);
});
phases.add(offsetPhase("independentPartitionCommittedWhilePeerHeld", events));
if (failCompletion) {
root("CREATE TRIGGER reject_parallel_offset_completion BEFORE UPDATE ON notification FOR EACH ROW "
+ "BEGIN IF NEW.notification_id = '" + blocked.id() + "' AND NEW.status = 'PROVIDER_ACCEPTED' THEN "
+ "SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'synthetic completion failure'; END IF; END");
triggerInstalled = true;
}
} finally { held.release.countDown(); }
if (failCompletion) {
awaitStopped();
assertThat(offset(0)).isZero(); assertThat(offset(1)).isEqualTo(2);
assertThat(status(blocked)).isEqualTo("PROCESSING");
assertThat(attempts(blocked)).isEqualTo(1); assertThat(attempts(later)).isZero();
assertThat(stats().requests()).isEqualTo(3); assertThat(stats().accepted()).isEqualTo(3);
assertThat(outcomeCount(blocked, "STARTED")).isEqualTo(1);
phases.add(offsetPhase("stoppedAfterCompletionRollback", events));
root("DROP TRIGGER reject_parallel_offset_completion"); triggerInstalled = false;
app.close(); app = null;
// Deterministic DB-time control, not a real elapsed-lease or SIGKILL experiment.
try (var connection = DriverManager.getConnection(MYSQL.getJdbcUrl(), MYSQL.getUsername(), MYSQL.getPassword());
var statement = connection.prepareStatement("UPDATE notification SET worker_lease_until=TIMESTAMPADD(SECOND,-1,UTC_TIMESTAMP(6)) WHERE notification_id=?")) {
statement.setString(1, blocked.id()); assertThat(statement.executeUpdate()).isEqualTo(1);
}
holdProvider = false;
startApplication(3, 2, 0, 5000);
}
awaitCompleted(List.copyOf(events.values()), 4);
assertThat(offset(0)).isEqualTo(2); assertThat(offset(1)).isEqualTo(2); assertThat(offset(2)).isZero();
assertThat(stats().requests()).isEqualTo(failCompletion ? 5 : 4);
assertThat(stats().accepted()).isEqualTo(4);
assertThat(stats().idempotencyReplays()).isEqualTo(failCompletion ? 1 : 0);
assertThat(stats().active()).isZero();
assertThat(attempts(blocked)).isEqualTo(failCompletion ? 2 : 1);
assertThat(outcomeCount(blocked, "UNKNOWN")).isEqualTo(failCompletion ? 1 : 0);
for (var event : events.values()) assertThat(outcomeCount(event, "PROVIDER_ACCEPTED")).isEqualTo(1);
for (var event : List.of(later, fastFirst, fastSecond)) assertThat(attempts(event)).isEqualTo(1);
phases.add(offsetPhase("recoveredAllFourLogicalTasks", events));
evidence.put("result", "PASS");
System.out.printf("OFFSET_ORDER mode=%s failure=%s heldOffsets=0,2,0 finalOffsets=2,2,0 logicalTasks=4 httpAccepted=%d%n",
mode.name(), failCompletion, stats().accepted());
} catch (Exception | AssertionError failure) {
primaryFailure = failure;
evidence.put("result", "FAIL"); evidence.put("failureType", failure.getClass().getSimpleName());
throw failure;
} finally {
if (held != null) held.release.countDown();
Exception cleanupFailure = null;
if (triggerInstalled) {
try { root("DROP TRIGGER reject_parallel_offset_completion"); }
catch (Exception failure) {
if (primaryFailure != null) primaryFailure.addSuppressed(failure);
else cleanupFailure = failure;
}
}
if (cleanupFailure != null) {
evidence.put("result", "FAIL"); evidence.put("cleanupFailureType", cleanupFailure.getClass().getSimpleName());
}
evidence.put("finishedAtUtc", Instant.now().toString());
try { new ObjectMapper().writerWithDefaultPrettyPrinter().writeValue(directory.resolve("result.json").toFile(), evidence); }
catch (java.io.IOException failure) {
if (primaryFailure != null) primaryFailure.addSuppressed(failure);
else if (cleanupFailure != null) cleanupFailure.addSuppressed(failure);
else throw failure;
}
if (cleanupFailure != null) throw cleanupFailure;
}
}
private int outcomeCount(Event event, String outcome) {
return jdbc().queryForObject("SELECT COUNT(*) FROM delivery_attempt a JOIN delivery_task t USING(task_id) WHERE t.notification_id=? AND a.outcome=?",
Integer.class, event.id(), outcome);
}
private record OffsetState(int partition, long end, Long committed, boolean commitPresent) { }
private Map<String, Object> offsetPhase(String phase, Map<String, Event> events) throws Exception {
var committed = admin.listConsumerGroupOffsets(group).partitionsToOffsetAndMetadata().get(5, TimeUnit.SECONDS);
var requested = new LinkedHashMap<TopicPartition, OffsetSpec>();
for (int i = 0; i < 3; i++) requested.put(new TopicPartition(topic, i), OffsetSpec.latest());
var ends = admin.listOffsets(requested).all().get(5, TimeUnit.SECONDS);
var offsets = new ArrayList<OffsetState>();
for (var partition : requested.keySet()) {
var value = committed.get(partition);
offsets.add(new OffsetState(partition.partition(), ends.get(partition).offset(),
value == null ? null : value.offset(), value != null));
}
var states = new LinkedHashMap<String, Object>();
for (var entry : events.entrySet()) {
var event = entry.getValue();
states.put(entry.getKey(), Map.of("status", status(event), "attempts", attempts(event),
"started", outcomeCount(event, "STARTED"), "accepted", outcomeCount(event, "PROVIDER_ACCEPTED"),
"unknown", outcomeCount(event, "UNKNOWN")));
}
return Map.of("phase", phase, "offsets", offsets, "tasks", states,
"http", stats(), "admissionActive", gate().active(), "admissionWaiting", gate().waiting());
}
private Event create() throws Exception {
try (var http = HttpClient.newHttpClient()) {
var response = http.send(HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + app.getWebServer().getPort() + "/notifications"))
.header("Content-Type", "application/json").timeout(Duration.ofSeconds(5))
.POST(HttpRequest.BodyPublishers.ofString("{\"recipientId\":\"synthetic-user\",\"title\":\"test\",\"body\":\"synthetic\"}"))
.build(), HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode()).isEqualTo(202);
String id = new ObjectMapper().readTree(response.body()).path("notificationId").asText();
return new Event(id, jdbc().queryForObject("SELECT payload FROM outbox_event WHERE notification_id = ?", String.class, id));
}
}
@SuppressWarnings("unchecked")
private void publish(Event event, int partition) throws Exception {
// Explicit partitions make same-partition ordering observable. Relay is disabled for this experiment.
app.getBean(KafkaTemplate.class).send(topic, partition, event.id(), event.payload()).get(5, TimeUnit.SECONDS);
}
private void awaitAssigned() {
await().atMost(Duration.ofSeconds(20)).untilAsserted(() -> requireAssigned(container().getConcurrency()));
}
private Map<String, Object> requireAssigned(int consumers) throws Exception {
var children = container().getContainers();
assertThat(children).hasSize(consumers);
var localAssignments = new ArrayList<Set<TopicPartition>>();
for (var child : children) {
assertThat(child.isRunning()).isTrue();
var assigned = child.getAssignedPartitions();
assertThat(assigned).isNotNull();
// Gated checks need independent request owners, not just six aggregate partitions.
assertThat(assigned.stream().anyMatch(partition -> partition.topic().equals(topic))).isTrue();
localAssignments.add(Set.copyOf(assigned));
}
var wanted = new HashSet<TopicPartition>();
for (int partition = 0; partition < 3; partition++) {
wanted.add(new TopicPartition(topic, partition));
wanted.add(new TopicPartition(topic + ".retry", partition));
}
assertThat(localAssignments.stream().flatMap(Set::stream).toList())
.doesNotHaveDuplicates().containsExactlyInAnyOrderElementsOf(wanted);
var description = admin.describeConsumerGroups(List.of(group)).all().get(5, TimeUnit.SECONDS).get(group);
assertThat(description.state()).isEqualTo(ConsumerGroupState.STABLE);
assertThat(description.members()).hasSize(consumers);
var brokerAssignments = new ArrayList<Set<TopicPartition>>();
for (var member : description.members()) {
var assigned = member.assignment().topicPartitions();
assertThat(assigned.stream().anyMatch(partition -> partition.topic().equals(topic))).isTrue();
brokerAssignments.add(Set.copyOf(assigned));
}
assertThat(brokerAssignments.stream().flatMap(Set::stream).toList())
.doesNotHaveDuplicates().containsExactlyInAnyOrderElementsOf(wanted);
assertThat(localAssignments).containsExactlyInAnyOrderElementsOf(brokerAssignments);
return Map.of("localConsumers", children.size(), "brokerMembers", description.members().size(),
"requestedOwners", consumers, "assignedPartitions", wanted.size(), "groupState", description.state().name(),
"memberPartitionCounts", brokerAssignments.stream().map(Set::size).sorted().toList());
}
private void awaitStopped() {
await().atMost(Duration.ofSeconds(15)).until(() -> !container().isRunning());
await().atMost(Duration.ofSeconds(10)).until(() -> gate().active() == 0 && gate().waiting() == 0);
await().atMost(Duration.ofSeconds(10)).until(() -> admin.describeConsumerGroups(List.of(group))
.all().get(5, TimeUnit.SECONDS).get(group).members().isEmpty());
}
private void awaitCompleted(List<Event> events, int expectedOffsets) {
await().atMost(Duration.ofSeconds(25)).untilAsserted(() -> {
for (var event : events) assertThat(status(event)).isEqualTo("PROVIDER_ACCEPTED");
assertThat(offset(0) + offset(1) + offset(2)).isEqualTo(expectedOffsets);
});
}
private long offset(int partition) throws Exception {
var value = admin.listConsumerGroupOffsets(group).partitionsToOffsetAndMetadata().get(5, TimeUnit.SECONDS)
.get(new TopicPartition(topic, partition));
return value == null ? 0 : value.offset();
}
private JdbcTemplate jdbc() { return app.getBean(JdbcTemplate.class); }
private WorkerAdmission gate() { return app.getBean(WorkerAdmission.class); }
private MockPushEndpoint.Stats stats() { return mock.getBean(MockPushEndpoint.class).stats(); }
private String status(Event e) { return jdbc().queryForObject("SELECT status FROM notification WHERE notification_id = ?", String.class, e.id()); }
private int attempts(Event e) { return jdbc().queryForObject("SELECT attempt_count FROM delivery_task WHERE notification_id = ?", Integer.class, e.id()); }
private ConcurrentMessageListenerContainer<?, ?> container() {
return (ConcurrentMessageListenerContainer<?, ?>) app.getBean(KafkaListenerEndpointRegistry.class).getListenerContainer("notification-worker");
}
private void root(String sql) throws Exception {
try (var connection = DriverManager.getConnection(MYSQL.getJdbcUrl(), "root", MYSQL.getPassword());
var statement = connection.createStatement()) { statement.execute(sql); }
}
@TestConfiguration(proxyBeanMethods = false)
static class ProviderGateConfiguration {
@Bean
@Primary
HeldProvider heldProvider(HttpPushProvider delegate) { return new HeldProvider(delegate); }
}
/** Holds admitted provider work before real HTTP; does not change application timeouts. */
static final class HeldProvider implements PushProvider {
private final HttpPushProvider delegate;
private final CountDownLatch release = new CountDownLatch(1);
private final AtomicInteger active = new AtomicInteger();
private final AtomicInteger peak = new AtomicInteger();
private final CountDownLatch entered = new CountDownLatch(1);
private volatile String selectedNotification;
private volatile int holdSeconds = 20;
HeldProvider(HttpPushProvider delegate) { this.delegate = delegate; }
void holdOnly(String notificationId) {
holdSeconds = 45;
selectedNotification = notificationId;
}
@Override
public PushResult send(PushRequest request) {
peak.accumulateAndGet(active.incrementAndGet(), Math::max);
try {
try {
if (selectedNotification == null || selectedNotification.equals(request.notificationId().toString())) {
assertThat(org.springframework.transaction.support.TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
entered.countDown();
if (!release.await(holdSeconds, TimeUnit.SECONDS)) throw new IllegalStateException("Test provider gate timed out");
}
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Test provider gate interrupted");
}
return delegate.send(request);
} finally {
active.decrementAndGet();
}
}
}
@AfterEach
void close() {
if (app != null) app.close();
if (mock != null) mock.close();
if (admin != null) admin.close(Duration.ofSeconds(2));
}
}