|
| 1 | +/* |
| 2 | + * Copyright © 2026 DataSQRL (contact@datasqrl.com) |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package com.datasqrl.flinkrunner.connector.kafka; |
| 17 | + |
| 18 | +import java.io.Serial; |
| 19 | +import java.time.Duration; |
| 20 | +import java.util.Arrays; |
| 21 | +import org.apache.flink.annotation.Internal; |
| 22 | +import org.apache.flink.api.common.eventtime.Watermark; |
| 23 | +import org.apache.flink.api.common.eventtime.WatermarkGenerator; |
| 24 | +import org.apache.flink.api.common.eventtime.WatermarkGeneratorSupplier; |
| 25 | +import org.apache.flink.api.common.eventtime.WatermarkOutput; |
| 26 | +import org.apache.flink.api.common.eventtime.WatermarkStrategy; |
| 27 | +import org.apache.flink.table.data.RowData; |
| 28 | + |
| 29 | +/** Adaptive watermark strategy based on Kafka record timestamps. */ |
| 30 | +@Internal |
| 31 | +public final class KafkaRecordTimestampWatermarkStrategy implements WatermarkStrategy<RowData> { |
| 32 | + |
| 33 | + @Serial private static final long serialVersionUID = 1L; |
| 34 | + |
| 35 | + static final int MIN_RECORDS = 250; |
| 36 | + static final int SAMPLE_SIZE = 4096; |
| 37 | + static final long MIN_OUT_OF_ORDERNESS_MILLIS = 50L; |
| 38 | + static final long MAX_OUT_OF_ORDERNESS_MILLIS = Duration.ofDays(1).toMillis(); |
| 39 | + |
| 40 | + private static final double OUT_OF_ORDERNESS_QUANTILE = 0.95D; |
| 41 | + |
| 42 | + public static final KafkaRecordTimestampWatermarkStrategy INSTANCE = |
| 43 | + new KafkaRecordTimestampWatermarkStrategy(); |
| 44 | + |
| 45 | + private KafkaRecordTimestampWatermarkStrategy() {} |
| 46 | + |
| 47 | + @Override |
| 48 | + public WatermarkGenerator<RowData> createWatermarkGenerator( |
| 49 | + WatermarkGeneratorSupplier.Context context) { |
| 50 | + |
| 51 | + return new AdaptiveKafkaRecordTimestampWatermarkGenerator(); |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * Watermark generator that derives event time from Kafka record timestamps and adapts its |
| 56 | + * out-of-orderness delay from recently observed records. |
| 57 | + * |
| 58 | + * <p>The generator watches how far records tend to arrive behind the newest Kafka timestamp seen |
| 59 | + * so far. It keeps a rolling sample of those delays and uses the 95th percentile as the safety |
| 60 | + * margin before advancing the watermark. This lets the source tolerate typical out-of-order |
| 61 | + * records without waiting for rare extreme delays. |
| 62 | + * |
| 63 | + * <p>The {@code eventTimestamp} argument is supplied by Flink from the Kafka source record |
| 64 | + * timestamp. |
| 65 | + */ |
| 66 | + private static final class AdaptiveKafkaRecordTimestampWatermarkGenerator |
| 67 | + implements WatermarkGenerator<RowData> { |
| 68 | + |
| 69 | + /** |
| 70 | + * Circular buffer of observed lateness values in milliseconds. |
| 71 | + * |
| 72 | + * <p>For a record with timestamp {@code t}, lateness is {@code max(0, maxTimestamp - t)} using |
| 73 | + * the maximum timestamp seen before that record. In-order records therefore contribute {@code |
| 74 | + * 0}, while older records contribute how far they lag behind the current observed frontier. |
| 75 | + */ |
| 76 | + private final long[] latenessSamples = new long[SAMPLE_SIZE]; |
| 77 | + |
| 78 | + /** Highest Kafka record timestamp observed by this generator. */ |
| 79 | + private long maxTimestamp = Long.MIN_VALUE; |
| 80 | + |
| 81 | + /** Last emitted watermark, used to preserve Flink's monotonic watermark contract. */ |
| 82 | + private long lastEmittedWatermark = Long.MIN_VALUE; |
| 83 | + |
| 84 | + /** |
| 85 | + * Number of records observed, including the first record that cannot produce a lateness sample. |
| 86 | + */ |
| 87 | + private long recordCount; |
| 88 | + |
| 89 | + /** Next slot in the circular lateness sample buffer. */ |
| 90 | + private int nextSampleIndex; |
| 91 | + |
| 92 | + @Override |
| 93 | + public void onEvent(RowData event, long eventTimestamp, WatermarkOutput output) { |
| 94 | + if (maxTimestamp != Long.MIN_VALUE) { |
| 95 | + // Sample lateness before updating maxTimestamp, so the sample reflects disorder relative to |
| 96 | + // the already observed stream frontier. |
| 97 | + latenessSamples[nextSampleIndex] = Math.max(0L, maxTimestamp - eventTimestamp); |
| 98 | + nextSampleIndex = (nextSampleIndex + 1) % SAMPLE_SIZE; |
| 99 | + } |
| 100 | + |
| 101 | + maxTimestamp = Math.max(maxTimestamp, eventTimestamp); |
| 102 | + recordCount++; |
| 103 | + } |
| 104 | + |
| 105 | + @Override |
| 106 | + public void onPeriodicEmit(WatermarkOutput output) { |
| 107 | + if (recordCount < MIN_RECORDS || maxTimestamp == Long.MIN_VALUE) { |
| 108 | + // Avoid emitting during warm-up, so limited early samples won't distort the estimate. |
| 109 | + return; |
| 110 | + } |
| 111 | + |
| 112 | + long outOfOrdernessMillis = calculateOutOfOrdernessMillis(); |
| 113 | + long watermark = maxTimestamp - outOfOrdernessMillis - 1; |
| 114 | + |
| 115 | + if (watermark > lastEmittedWatermark) { |
| 116 | + output.emitWatermark(new Watermark(watermark)); |
| 117 | + lastEmittedWatermark = watermark; |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + private long calculateOutOfOrdernessMillis() { |
| 122 | + int sampleCount = (int) Math.min(recordCount - 1, SAMPLE_SIZE); |
| 123 | + if (sampleCount <= 0) { |
| 124 | + return MIN_OUT_OF_ORDERNESS_MILLIS; |
| 125 | + } |
| 126 | + |
| 127 | + long[] samples = Arrays.copyOf(latenessSamples, sampleCount); |
| 128 | + Arrays.sort(samples); |
| 129 | + |
| 130 | + // Use a high quantile rather than the maximum, so a single pathological record does not stall |
| 131 | + // all event-time progress until it rotates out of the sample buffer. |
| 132 | + int quantileIndex = |
| 133 | + Math.min(sampleCount - 1, (int) Math.ceil(sampleCount * OUT_OF_ORDERNESS_QUANTILE) - 1); |
| 134 | + |
| 135 | + return Math.min( |
| 136 | + MAX_OUT_OF_ORDERNESS_MILLIS, |
| 137 | + Math.max(MIN_OUT_OF_ORDERNESS_MILLIS, samples[quantileIndex])); |
| 138 | + } |
| 139 | + } |
| 140 | +} |
0 commit comments