// We'll store the output records in order.
private List<OutputRecord<KEY, OUT>> outputRecords;
// We also might want to store the current state (if we want to inspect it) but that might be operator-specific.
public void setup(Operator<IN, OUT, KEY> operator) {
this.operator = operator;
this.outputRecords = new ArrayList<>();
}
public void processElement(IN element, long timestamp) {
// We assume the element has a timestamp? Or we pass the timestamp separately?
// Let's assume we have a way to extract the timestamp from the element or we pass it separately.
// For simplicity, let's say the element is a tuple of (key, value) and the timestamp is separate.
// But note: the operator might be keyed or not. We can have:
// If the operator is keyed, then the element must have a key. Otherwise, the key is null.
// We'll call the operator's processElement method, and then capture any output.
// However, the operator might have side outputs. We'll only capture the main output for now.
// We'll assume the operator has a method:
// void processElement(IN element, long timestamp, Collector<OUT> output)
// But to capture retractions, we need to know if the output is a retraction. How?
// In Flink, the `Collector` does not have a retraction flag. Instead, for retractions, the operator emits a special message (with a flag)
// in the case of two-phase aggregation. Alternatively, in a `ProcessFunction` you can emit a retraction by emitting a special signal.
// Since the problem is generic, let's assume that the operator's output type `OUT` can be either a normal output or a retraction.
// But that would require the output type to have a flag, which is not always the case.
// Alternatively, we can have two collectors: one for regular output and one for retractions? But that is not standard.
// Let's think: in a typical window operator that does retractions, the output is a `WindowResult` that has a flag.
// So we leave it to the operator to encode retractions in the output. Then the harness just records every output.
// But then how do we know if it's a retraction? We don't, unless the output type has that information.
// Alternatively, we can have the operator emit a tuple of (value, isRetraction). But that changes the operator's signature.
// Since the problem says "safe backfill harness", we are building a test harness, so we can require that the operator we test
// uses a specific interface for output that includes a retraction flag.
// Let's define:
// interface RetractableOutput<T> {
// T getValue();
// boolean isRetraction();
// }
// But that might be too restrictive.
// Another idea: in the harness, we can have two lists: one for regular outputs and one for retractions? But then the order might be lost.
// Alternatively, we can have a single list of `OutputRecord` that has:
// class OutputRecord<KEY, OUT> {
// KEY key;
// OUT value;
// boolean isRetraction;
// long timestamp; // the event time timestamp of this output (might be the window timestamp, or the element timestamp, etc.)
// }
// But then we require the operator to tell us which output is a retraction. How?
// We can change the operator's interface to:
// void processElement(IN element, long timestamp, OutputCollector<OUT> collector)
// where OutputCollector has:
// void collect(OUT value, boolean isRetraction)
// But that changes the operator's code.
// Alternatively, we can have the operator return a list of outputs (with retraction flag) from processElement and from timer.
// Since we are building a test harness, we can define an interface for the operator that is test-friendly:
// interface TestableOperator<IN, OUT, KEY> {
// List<OutputRecord<KEY, OUT>> processElement(IN element, long timestamp);
// List<OutputRecord<KEY, OUT>> advanceWatermark(long watermark);
// }
// Then the harness can call these and collect the records.
// But then the operator has to be written to work with this harness. That might be acceptable for testing.
// However, the problem says "create a safe backfill harness", meaning we are testing existing operators? Or we are writing operators that are testable?
// Let's assume we are writing a harness for operators that are designed to be testable (i.e., they implement a testable interface).
// But if we cannot change the operator, we might have to adapt. For example, if the operator uses the standard Flink `Collector` and does not mark retractions,
// then we cannot distinguish. So we have to know the operator's behavior.
// Given the complexity, let's assume we are designing for a specific system that has a clear retraction signal.
// Alternatively, we can design the harness to be used in two ways:
// a) The operator emits a special type that includes a retraction flag. Then we can extract that.
// b) The operator emits the same type for retractions and regular outputs, but we can infer by comparing with previous outputs?
// That is not reliable because the same value might be emitted again (and it's not a retraction).
// So we go with (a): require the operator to output a type that has a retraction flag.
// But then the harness must be generic over the output type and also have a way to extract the flag.
// We can do:
// interface OutputWithRetraction<OUT> {
// OUT getValue();
// boolean isRetraction();
// }
// And then the operator's output type must implement that.
// But what if we don't want to change the output type? We can have a wrapper.
// Alternatively, we can have the harness accept a `OutputExtractor` that given an output record, returns:
// - the key (if keyed, otherwise null)
// - the value (the actual output value)
// - the retraction flag
// This way, the harness does not depend on a specific interface.
// Let's do:
// class OutputRecord<KEY, OUT> {
// KEY key;
// OUT value;
// boolean isRetraction;
// long timestamp;
// }
// and we provide a way to convert the operator's raw output (of type `OUT`) to an `OutputRecord` by using an `OutputExtractor`.
// interface OutputExtractor<RAW_OUT, KEY> {
// OutputRecord<KEY, RAW_OUT> extract(RAW_OUT rawOutput, long outputTimestamp);
// }
// Then the harness can use this extractor to convert the operator's output to our `OutputRecord`.
// But note: the operator might output multiple records at once (like a list). So we need to handle that.
// We can have the operator return a `List<RAW_OUT>` and then we convert each one.
// However, the operator might also have side outputs. We are only capturing the main output.
// Let's design:
// interface TestableOperator<IN, RAW_OUT, KEY> {
// List<RAW_OUT> processElement(IN element, long timestamp);
// List<RAW_OUT> advanceWatermark(long watermark);
// }
// And then the harness has:
// private TestableOperator<IN, RAW_OUT, KEY> operator;
// private OutputExtractor<RAW_OUT, KEY> outputExtractor;
// public void processElement(IN element, long timestamp) {
// List<RAW_OUT> rawOutputs = operator.processElement(element, timestamp);
// for (RAW_OUT raw : rawOutputs) {
// OutputRecord<KEY, RAW_OUT> record = outputExtractor.extract(raw, timestamp); // or should we use the element's timestamp?
// // But note: the output might have a different timestamp (like window end). So we need the operator to provide the output timestamp?
// // Alternatively, the `OutputExtractor` might extract the timestamp from the raw output?
// // Let's change the `OutputExtractor` to:
// // OutputRecord<KEY, RAW_OUT> extract(RAW_OUT rawOutput);
// // and then the `OutputRecord` must have a timestamp. How do we get it?
// // We can have the raw output type contain the timestamp? Or the operator's output already includes the timestamp?
// // Since we are in a test harness, we can assume that the raw output has a way to get the timestamp (like a field or method).
// // But then the `OutputExtractor` would extract the key, value, retraction flag, and timestamp from the raw output.
// // So:
// // OutputRecord<KEY, RAW_OUT> record = outputExtractor.extract(raw);
// // and then we record it.
// }
// }
// This is getting complex.
// Let's simplify:
// We assume the operator we are testing is already designed to work with this harness, so it implements:
// interface TestableOperator<IN, OUT, KEY> {
// List<OutputRecord<KEY, OUT>> processElement(IN element, long timestamp);
// List<OutputRecord<KEY, OUT>> advanceWatermark(long watermark);
// }
// Then the harness is just a runner that calls these and collects the records.
// But then the operator has to create `OutputRecord` objects. That might be acceptable.
// Alternatively, we can have the harness do the conversion by providing a `Function` that maps (raw output, timestamp) to `OutputRecord`.
// Given the time, let's go with:
// The harness is built for an operator that implements:
// interface OperatorAdapter<IN, OUT, KEY> {
// List<OUT> processElement(IN element, long timestamp);
// List<OUT> advanceWatermark(long watermark);
// }
// And then we provide a `OutputAdapter` that given an output of type `OUT` and the current watermark (or the event time that triggered it)
// can create an `OutputRecord`.
// But note: the `advanceWatermark` might trigger timers and the output might have a timestamp that is the timer's timestamp (which is the watermark or a specific time).
// We can have:
// class OutputRecord<KEY, OUT> {
// KEY key;
// OUT value;
// boolean isRetraction;
// long timestamp; // the event time timestamp of this output
// }
// and an interface:
// interface OutputAdapter<OUT, KEY> {
// OutputRecord<KEY, OUT> toOutputRecord(OUT output, long triggerTimestamp, boolean isRetraction);
// }
// But then the operator doesn't know about retractions? We have to tell it?
// Actually, the operator should know when it is emitting a retraction. So the operator should return two things: the output and a flag.
// So we change the operator interface to return a list of `Tuple2<OUT, Boolean>` (output and isRetraction). Then the harness can use the OutputAdapter to get the key and timestamp?
// Alternatively, we can have:
// interface OperatorAdapter<IN, OUT, KEY> {
// List<OutputRecord<KEY, OUT>> processElement(IN element, long timestamp);
// List<OutputRecord<KEY, OUT>> advanceWatermark(long watermark);
// }
// and the `OutputRecord` already contains the key, value, retraction flag, and timestamp.
// Then the operator is responsible for setting the correct timestamp and retraction flag.
// This is the simplest for the harness.
// So we design the harness to work with operators that already produce `OutputRecord`.
// But what if the operator doesn't? Then we cannot use it.
// Given the constraints, let's assume we are testing operators that are written to be testable and they produce `OutputRecord`.
// So the harness:
// public class BackfillHarness<IN, OUT, KEY> {
// private OperatorAdapter<IN, OUT, KEY> operator;
// private List<OutputRecord<KEY, OUT>> outputRecords;
//
// public void setup(OperatorAdapter<IN, OUT, KEY> operator) {
// this.operator = operator;
// this.outputRecords = new ArrayList<>();
// }
//
// public void processElement(IN element, long timestamp) {
// List<OutputRecord<KEY, OUT>> records = operator.processElement(element, timestamp);
// outputRecords.addAll(records);
// }
//
// public void advanceWatermark(long watermark) {
// List<OutputRecord<KEY, OUT>> records = operator.advanceWatermark(watermark);
// outputRecords.addAll(records);
// }
//
// // Then we can have methods to assert the output:
// // - getOutputRecords(): returns all output records in order.
// // - getCurrentOutput(): returns a map of key to the latest non-retracted output?
// // But note: retractions are also in the output stream. So the current output for a key is the last non-retracted record for that key?
// // But what if the last record for a key is a retraction? Then the current output for that key is nothing (or null).
// //
// // We can provide:
// // Map<KEY, OUT> getCurrentOutput() {
// // Map<KEY, OUT> current = new HashMap<>();
// // for (OutputRecord<KEY, OUT> record : outputRecords) {
// // if (!record.isRetraction) {
// // current.put(record.key, record.value);
// // } else {
// // current.remove(record.key); // because retraction removes the key?
// // }
// // }
// // return current;
// // }
// //
// // But note: what if the operator is not keyed? Then the key is null and we cannot have multiple records?
// // For non-keyed, we might have multiple outputs at different timestamps. Then the current output is the last non-retracted record?
// // But if the operator is non-keyed, then we might have a sequence of outputs and retractions that are not keyed.
// // Then the current output is the last non-retracted record? But then we lose the previous ones?
// // Actually, for non-keyed, the current output might be a single value (like a count) that updates. So we can use a similar approach:
// // the last non-retracted record for the null key? But that doesn't make sense because we can have multiple non-keyed outputs that are not retractions?
// // For example, a non-keyed window might output multiple windows. Then we have multiple outputs for different windows (with different timestamps).
// // So the current output for non-keyed might be a list of the latest non-retracted records for each window?
// // But windows are identified by the window itself (which is part of the output).
// // So we cannot use a simple map.
// //
// // Therefore, we might not want to provide a `getCurrentOutput` for non-keyed. Instead, we let the test check the entire output record list.
// //
// // Alternatively, we can have:
// // List<OutputRecord<KEY, OUT>> getOutputRecords() // all in order
// // and then the test can filter and check as needed.
// //
// // So we only provide the list.
// }
// But wait, the problem says "watermark moves", so we need to test watermark progression. The `advanceWatermark` method in the operator should handle that.
// Also, we need to set the initial watermark? We can have a method to set the initial watermark.
// Let's design:
// public void setInitialWatermark(long watermark) {
// // This might be needed if the operator has state that depends on the watermark (like cleanup timers)
// // But note: the operator might not have an explicit method for initial watermark. We can assume that the operator starts with watermark = Long.MIN_VALUE.
// // We can have the operator's `advanceWatermark` method handle any watermark, including the initial one.
// }
// Actually, we don't need an initial watermark method because we can just call `advanceWatermark` with the starting watermark.
// But note: the operator might have registered timers that are set to fire at a specific time. When we advance the watermark, those timers should fire.
// So the `advanceWatermark` method should:
// - Update the current watermark.
// - Fire any timers that are due (i.e., timer timestamp <= new watermark) and then produce output (as `OutputRecord`s).
// And the `processElement` method might also set timers and produce output.
// So the harness is:
// public class BackfillHarness<IN, OUT, KEY> {
// private OperatorAdapter<IN, OUT, KEY> operator;
// private List<OutputRecord<KEY, OUT>> outputRecords;
// private long currentWatermark;
//
// public void setup(OperatorAdapter<IN, OUT, KEY> operator, long initialWatermark) {
// this.operator = operator;
// this.outputRecords = new ArrayList<>();
// this.currentWatermark = initialWatermark;
// }
//
// public void processElement(IN element, long timestamp) {
// // Check that the element's timestamp is not before the current watermark?
// // In a real system, late elements might be handled differently. But for the test, we can allow any timestamp.
// List<OutputRecord<KEY, OUT>> records = operator.processElement(element, timestamp);
// outputRecords.addAll(records);
// }
//
// public void advanceWatermark(long newWatermark) {
// if (newWatermark < currentWatermark) {
// throw new IllegalArgumentException("Watermark cannot go backwards");
// }
// currentWatermark = newWatermark;
// List<OutputRecord<KEY, OUT>> records = operator.advanceWatermark(newWatermark);
// outputRecords.addAll(records);
// }
//
// public List<OutputRecord<KEY, OUT>> getOutputRecords() {
// return new ArrayList<>(outputRecords);
// }
//
// // Optionally, we can reset the harness for a new test.
// public void reset() {
// outputRecords.clear();
// currentWatermark = Long.MIN_VALUE;
// }
// }
// But note: the operator might have internal state that is affected by the watermark. So when we call `advanceWatermark`, we are essentially telling the operator
// that the watermark has moved to `newWatermark`. The operator should then fire any timers that are due and clean up state if needed.
// However, the operator might also have processing time timers. But the problem says "watermark moves", so we focus on event time.
// We assume the operator only has event time timers.
// Also, note that the operator might have state that is keyed by key. The harness does not manage the state; the operator does.
// This harness is safe because:
// - It does not allow watermark to go backwards.
// - Each test can create a new harness (or reset) so no state leaks.
// But what about the operator's state? The harness does not reset the operator's state. So if we reuse the same operator instance, we must reset it too.
// We can require the operator to have a `clear()` method to clear its state.
// Alternatively, we can create a new operator for each test.
// Let's change the `setup` to take an operator instance and then we can have:
// public void reset() {
// outputRecords.clear();
// currentWatermark = Long.MIN_VALUE;
// operator.clear(); // if the operator has a clear method
// }
// But not every operator has a clear method. So we can leave it to the test to create a fresh operator.
// So we won't include `reset` in the harness, but the test can create a new harness for each test.
// Now, what about the `OutputRecord`? We defined it as:
// class OutputRecord<KEY, OUT> {
// KEY key;
// OUT value;
// boolean isRetraction;
// long timestamp;
// }
// The operator, when it emits an output, must set:
// - the key (if keyed, otherwise null)
// - the value
// - whether it's a retraction
// - the timestamp of the output (which might be the element's timestamp, or the window's timestamp, or the timer's timestamp)
// The harness does not set these; the operator does.
// Now, how does the operator know the key?
// If the operator is keyed, then the `processElement` method might receive a keyed element. The operator must extract the key and set it in the `OutputRecord`.
// Similarly, for `advanceWatermark`, the operator might fire timers that are per-key. So the `OutputRecord` must have the key for that timer.
// This design seems workable.
// But note: the operator might output multiple records for one element or one timer fire. So the `processElement` and `advanceWatermark` return a list.
// Now, let's write an example operator and test.
// Example: a keyed process function that counts elements per key and emits the count when the watermark passes the element's timestamp + 1.
// But wait, we are testing backfill. So we want to test that when we backfill old data (with old timestamps) and then move the watermark, we get the right outputs.
// We can write:
// class CountOperator implements OperatorAdapter<String, Integer, String> {
// private Map<String, Integer> counts = new HashMap<>();
//
// @Override
// public List<OutputRecord<String, Integer>> processElement(String element, long timestamp) {
// // element is the key? Actually, let's say the element is a tuple (key, value) but we only care about the key.
// // But the operator is keyed by the element itself? Let's assume the element is the key and we count the number of elements for that key.
// String key = element;
// counts.merge(key, 1, Integer::sum);
// // We don't emit immediately. We wait for the watermark.
// return Collections.emptyList();
// }
//
// @Override
// public List<OutputRecord<String, Integer>> advanceWatermark(long watermark) {
// List<OutputRecord<String, Integer>> outputs = new ArrayList<>();
// for (Map.Entry<String, Integer> entry : counts.entrySet()) {
// // We emit the count for every key? But that would emit every time. We need to remember what we emitted.
// // So we need to store the last emitted count per key.
// // Let's change: we store the last emitted count per key.
// }
// // This example is not complete.
// return outputs;
// }
// }
// This example shows that the operator must remember what it has emitted to avoid emitting the same count again.
// So the operator must have state for the last emitted value per key.
// But note: in a real window, the window state would be stored and then when the watermark passes the window end, the window emits.
// So for this harness, we are testing the operator's behavior including its state.
// The harness does not manage the state; the operator does.
// Therefore, the harness is just a driver that calls the operator and collects the output.
// We can now write a test:
// @Test
// public void testCountOperator() {
// CountOperator operator = new CountOperator();
// BackfillHarness<String, Integer, String> harness = new BackfillHarness<>();
// harness.setup(operator, Long.MIN_VALUE);
//
// // Emit two elements for key "a" with timestamps 1 and 2.
// harness.processElement("a", 1);
// harness.processElement("a", 2);
//
// // Advance watermark to 3 (which is > 2). Then we expect the count for "a" to be 2.
// harness.advanceWatermark(3);
//
// List<OutputRecord<String, Integer>> outputs = harness.getOutputRecords();
// // We expect one output for key "a" with value 2, and isRetraction=false, and timestamp?
// // The operator might set the timestamp to the watermark? or the max timestamp of the elements?
// // It depends on the operator. Let's assume the operator sets the output timestamp to the watermark when it fires.
// OutputRecord<String, Integer> expected = new OutputRecord<>("a", 2, false, 3);
// assertEquals(1, outputs.size());
// assertEquals(expected, outputs.get(0));
// }
// But note: the operator might emit the count at the watermark time (3) or at the max timestamp of the elements (2).
// It depends on the operator's logic. The test must know what to expect.
// Now, what about retractions?
// Example: a window that counts and then when a late element arrives, it retracts the previous count and emits a new one.
// We can write an operator that does:
// class WindowCountOperator implements OperatorAdapter<String, Integer, String> {
// private Map<String, Integer> counts = new HashMap<>();
// private Map<String, Integer> lastEmitted = new HashMap<>();
// private long watermark = Long.MIN_VALUE;
//
// @Override
// public List<OutputRecord<String, Integer>> processElement(String element, long timestamp) {
// String key = element;
// counts.merge(key, 1, Integer::sum);
// // If the element is late (timestamp <= watermark) then we might need to retract?
// // But note: in a window, we only consider elements that are within the window.
// // For simplicity, let's assume we have a window of [0,10] and we only count elements with timestamp in [0,10].
// // And we emit when watermark >= 10.
// // But then if we get an element with timestamp 5 after watermark 10, we should retract?
// // That's a late element. We might ignore it or update the window.
// // Let's assume we update the window and then retract the previous count and emit a new one.
//
// // But note: the operator is not windowed? We are just counting per key without window. Then every element updates the count and we don't retract.
// // So we need a window to have retractions.
//
// // Let's change: we are counting in a tumbling window of size 10.
// // But then the operator must know the window. That complicates.
//
// // Alternatively, we can have a simpler example: a stateful operator that remembers the last count and emits when the watermark advances.
// // And if it gets an element that is late (timestamp <= current watermark) then it retracts the previous count and emits a new one?
// // That doesn't make sense because the element is late, so it shouldn't change the count?
//
// // Actually, in a window, a late element might be allowed to update the window if the window is not cleaned up yet.
// // So we need to maintain state for the window.
//
// // Given the complexity, let's stick to a simple example without windows for now.
//
// return Collections.emptyList();
// }
//
// @Override
// public List<OutputRecord<String, Integer>> advanceWatermark(long newWatermark) {
// this.watermark = newWatermark;
// List<OutputRecord<String, Integer>> outputs = new ArrayList<>();
// for (Map.Entry<String, Integer> entry : counts.entrySet()) {
// String key = entry.getKey();
// int count = entry.getValue();
// Integer last = lastEmitted.get(key);
// if (last == null || last != count) {
// // Emit the new count and remember it.
// OutputRecord<String, Integer> record = new OutputRecord<>(key, count, false, watermark);
// outputs.add(record);
// lastEmitted.put(key, count);
// }
// }
// return outputs;
// }
// }
// This operator emits the count for every key whenever the watermark advances and the count has changed.
// But note: it does not retract. It only emits new counts.
// To test retractions, we need an operator that emits a retraction (isRetraction=true) for a previous output.
// Example: an operator that emits a running count, but if it receives a negative update (like a correction) it retracts the previous count.
// Let's do:
// class CorrectableCountOperator implements OperatorAdapter<String, Integer, String> {
// private Map<String, Integer> counts = new HashMap<>();
// private Map<String, Integer> lastEmitted = new HashMap<>();
// private long watermark = Long.MIN_VALUE;
//
// @Override
// public List<OutputRecord<String, Integer>> processElement(String element, long timestamp) {
// // element is a tuple (key, delta) but for simplicity, let's say the element is the key and we always add 1?
// // We need to handle corrections. Let's say the element is (key, delta) and delta can be negative.
// // But then the operator must be keyed by key and the element has a key and a delta.
// // We change the operator to work with a different input type.
//
// // For simplicity, let's assume the input is a pair (key, delta) and we are counting the sum of deltas.
// // We'll represent the element as a class Pair.
//
// // But we don't want to change the harness. The harness is generic over IN, OUT, KEY.
// // So we can have:
// // IN = Pair<String, Integer>
// // KEY = String
// // OUT = Integer
//
// // Then:
// String key = element.key;
// int delta = element.delta;
// int oldCount = counts.getOrDefault(key, 0);
// int newCount = oldCount + delta;
// counts.put(key, newCount);
//
// // We don't emit immediately. We wait for watermark.
// return Collections.emptyList();
// }
//
// @Override
// public List<OutputRecord<String, Integer>> advanceWatermark(long newWatermark) {
// this.watermark = newWatermark;
// List<OutputRecord<String, Integer>> outputs = new ArrayList<>();
// for (Map.Entry<String, Integer> entry : counts.entrySet()) {
// String key = entry.getKey();
// int count = entry.getValue();
// Integer last = lastEmitted.get(key);
// if (last == null) {
// // First time
// outputs.add(new OutputRecord<>(key, count, false, watermark));
// lastEmitted.put(key, count);
// } else if (!last.equals(count)) {
// // Emit a retraction for the previous count and then the new count.
// outputs.add(new OutputRecord<>(key, last, true, watermark));
// outputs.add(new OutputRecord<>(key, count, false, watermark));
// lastEmitted.put(key, count);
// }
// }
// return outputs;
// }
// }
// Then a test:
// @Test
// public void testCorrectableCountOperator() {
// CorrectableCountOperator operator = new CorrectableCountOperator();
// BackfillHarness<Pair<String, Integer>, Integer, String> harness = new BackfillHarness<>();
// harness.setup(operator, Long.MIN_VALUE);
//
// // Emit (a, 1) at time 1.
// harness.processElement(Pair.of("a", 1), 1);
// // Watermark to 2 -> emits count=1 for "a".
// harness.advanceWatermark(2);
//
// // Now emit a correction: (a, -1) at time 3.
// harness.processElement(Pair.of("a", -1), 3);
// // Watermark to 4 -> should retract 1 and emit 0.
// harness.advanceWatermark(4);
//
// List<OutputRecord<String, Integer>> outputs = harness.getOutputRecords();
// assertEquals(3, outputs.size());
// assertEquals(new OutputRecord<>("a", 1, false, 2), outputs.get(0));
// assertEquals(new OutputRecord<>("a", 1, true, 4), outputs.get(1));
// assertEquals(new OutputRecord<>("a", 0, false, 4), outputs.get(2));
// }
// This test checks the sequence of outputs, including the retraction.
// But note: the operator emits the retraction and the new count at the same watermark (4). That's typical.
// Now, what if we want to test that the operator does not emit anything until the watermark passes? We can check that after processing the first element,
// there is no output until we advance the watermark.
// This harness seems to work.
// However, we have not addressed:
// - The operator might have processing time timers. But the problem says "watermark moves", so we ignore.
// - The operator might have state that is cleaned up by the watermark. We can test that by advancing the watermark and then checking state?
// But the harness does not expose the operator's state. We can add a method to get the state? But that would be operator-specific.
// We can extend the harness to allow accessing the operator's state if the operator provides a getter. But that would break the abstraction.
// Alternatively, we can have the operator implement an interface that exposes its state for testing.
// Since the problem is about backfill, we are mostly interested in the output and the watermark moves.
// So we leave it at that.
// Summary:
// We design a harness that:
// - Works with an operator that implements `OperatorAdapter<IN, OUT, KEY>` (with methods `processElement` and `advanceWatermark` returning `List<OutputRecord<KEY, OUT>>`).
// - Captures all output records (including retractions) in order.
// - Tracks the current watermark (and does not allow it to go backwards).
// - Does not manage the operator's state (the operator does).
// - Does not expose the operator's state (but we can extend if needed).
// We also need to define `OutputRecord`:
// class OutputRecord<KEY, OUT> {
// private final KEY key;
// private final OUT value;
// private final boolean isRetraction;
// private final long timestamp;
//
// // constructor, getters, equals, hashCode
// }
// And the `OperatorAdapter`:
// interface OperatorAdapter<IN, OUT, KEY> {
// List<OutputRecord<KEY, OUT>> processElement(IN element, long timestamp);
// List<OutputRecord<KEY, OUT>> advanceWatermark(long watermark);
// }
// Then the harness:
// public class BackfillHarness<IN, OUT, KEY> {
// private OperatorAdapter<IN, OUT, KEY> operator;
// private List<OutputRecord<KEY, OUT>> outputRecords;
// private long currentWatermark;
//
// public void setup(OperatorAdapter<IN, OUT, KEY> operator, long initialWatermark) {
// this.operator = operator;
// this.outputRecords = new ArrayList<>();
// this.currentWatermark = initialWatermark;
// }
//
// public void processElement(IN element, long timestamp) {
// List<OutputRecord<KEY, OUT>> records = operator.processElement(element, timestamp);
// outputRecords.addAll(records);
// }
//
// public void advanceWatermark(long newWatermark) {
// if (newWatermark < currentWatermark) {
// throw new IllegalArgumentException("Watermark cannot go backwards: current=" + currentWatermark + ", new=" + newWatermark);
// }
// currentWatermark = newWatermark;
// List<OutputRecord<KEY, OUT>> records = operator.advanceWatermark(newWatermark);
// outputRecords.addAll(records);
// }
//
// public List<OutputRecord<KEY, OUT>> getOutputRecords() {
// return new ArrayList<>(outputRecords);
// }
//
// public long getCurrentWatermark() {
// return currentWatermark;
// }
// }
// This is a simple and safe design.
// However, note: the operator might emit output during `processElement` with a timestamp that is not the element's timestamp (like a timer that fires during processing?).
// But that would be unusual. We assume that `processElement` only emits output that is directly caused by the element, and the output's timestamp is set appropriately by the operator.
// Also, note that the operator might register timers during `processElement` that will fire later when the watermark advances.
// So the `advanceWatermark` method should fire the timers that are due and then emit.
// This design does not allow the harness to inject processing time. If we need processing time, we can extend with:
// public void advanceProcessingTime(long newProcessingTime) { ... }
// But the problem says "watermark moves", so we don't.
// Let's stick to event time.
// This harness is safe because:
// - It does not allow watermark to go backwards (which is a common error).
// - It records every output in order, so we can check the sequence.
// - It is deterministic: given the same sequence of operations, the same output records are produced.
// We can also add a `reset` method to clear the output records and reset the watermark, but not the operator's state. The operator's state must be reset by creating a new operator.
// Alternatively, we can have:
// public void reset(OperatorAdapter<IN, OUT, KEY> operator, long initialWatermark) {
// this.operator = operator;
// this.outputRecords.clear();
// this.currentWatermark = initialWatermark;
// }
// Then the test can reuse the harness but with a fresh operator.
// But note: the operator might hold state from previous runs. So we must pass a new operator to `reset`.
// We can do:
// public void reset(OperatorAdapter<IN, OUT, KEY> operator, long initialWatermark) {
// this.operator = operator;
// this.outputRecords.clear();
// this.currentWatermark = initialWatermark;
// }
// Then the test can do:
// harness.reset(new Operator(), Long.MIN_VALUE);
// But then the harness holds a reference to the old operator until reset? That's okay.
// We can also have a constructor that takes the operator and initial watermark.
// Let's finalize:
// public class BackfillHarness<IN, OUT, KEY> {
// private OperatorAdapter<IN, OUT, KEY> operator;
// private final List<OutputRecord<KEY, OUT>> outputRecords;
// private long currentWatermark;
//
// public BackfillHarness(OperatorAdapter<IN, OUT, KEY> operator, long initialWatermark) {
// this.operator = operator;
// this.outputRecords = new ArrayList<>();
// this.currentWatermark = initialWatermark;
// }
//
// public void processElement(IN element, long timestamp) {
// List<OutputRecord<KEY, OUT>> records = operator.processElement(element, timestamp);
// outputRecords.addAll(records);
// }
//
// public void advanceWatermark(long newWatermark) {
// if (newWatermark < currentWatermark) {
// throw new IllegalArgumentException("Watermark cannot go backwards: current=" + currentWatermark + ", new=" + newWatermark);
// }
// currentWatermark = newWatermark;
// List<OutputRecord<KEY, OUT>> records = operator.advanceWatermark(newWatermark);
// outputRecords.addAll(records);
// }
//
// public List<OutputRecord<KEY, OUT>> getOutputRecords() {
// return new ArrayList<>(outputRecords);
// }
//
// public long getCurrentWatermark() {
// return currentWatermark;
// }
// }
// And if we want to reset (with a new operator) we can create a new harness.
// This is a clean design.
// However, note: the operator might have side outputs. We are only capturing the main output.
// If we want to test side outputs, we can extend the `OperatorAdapter` to return a map of output tag to list of records.
// But for simplicity, we leave it as main output only.
// We can also have a version that supports multiple outputs.
// Given the problem statement, we are only asked for a safe backfill harness for streaming: watermark moves, retractions, and tests.
// This design covers:
// - Watermark moves: via `advanceWatermark`.
// - Retractions: via `OutputRecord.isRetraction`.
// - Tests: by capturing the output records and allowing assertions.
// And it is safe because:
// - Watermark cannot go backwards.
// - Each test uses a new harness (or we can reset with a new operator) so no state leakage.
// Let's write the code accordingly.
// We'll write:
// OutputRecord class
// OperatorAdapter interface
// BackfillHarness class
// And then an example test and operator.
// But note: the operator might be keyed or not. In the `OutputRecord`, the key can be null for non-keyed operators.
// We are done.
// However, one more thing: the operator might have state that is keyed by the key. The harness does not manage that state.
// But when we advance the watermark, the operator might clean up state for keys that are no longer needed (like in a window).
// That is internal to the operator.
// So the harness is just a driver.
// Let's code accordingly.
// But wait: the operator's `advanceWatermark` method might need to know the current watermark? We are passing the new watermark, but the operator might need to know the current one?
// We can have the operator store the current watermark as well? Or we can pass the old and new?
// In our design, the operator's `advanceWatermark` method is called with the new watermark. The operator must have stored the old watermark (if needed) or it can figure out the difference.
// We can change the signature to:
// List<OutputRecord<KEY, OUT>> advanceWatermark(long oldWatermark, long newWatermark);
// but that would require the harness to store the old watermark. Alternatively, the operator can store the current watermark.
// We'll keep it simple: the operator stores the current watermark (if it needs) and the harness just calls with the new watermark.
// The operator can have:
// private long currentWatermark = Long.MIN_VALUE;
// @Override
// public List<OutputRecord<KEY, OUT>> advanceWatermark(long newWatermark) {
// if (newWatermark < this.currentWatermark) {
// throw new IllegalArgumentException("Watermark cannot go backwards");
// }
// this.currentWatermark = newWatermark;
// ...
// }
// But then the operator must do the same check as the harness? We can let the harness do the check and then the operator assumes the watermark is increasing.
// We'll do the check in the harness and then the operator can assume the watermark is increasing.
// So the operator does not need to store the watermark? It might need to for timer comparisons. So the operator should store the current watermark.
// We can change the operator interface to:
// interface OperatorAdapter<IN, OUT, KEY> {
// void setWatermark(long watermark); // set the current watermark (and fire timers if needed)
// List<OutputRecord<KEY, OUT>> processElement(IN element, long timestamp);
// }
// Then the harness would:
// public void setWatermark(long watermark) {
// operator.setWatermark(watermark);
// // and then we get the output from the operator? How?
// }
// That doesn't work because `setWatermark` would need to return the output.
// So we keep the `advanceWatermark` that returns the output.
// And the operator must store the current watermark to compare with timer timestamps.
// So the operator will have:
// private long currentWatermark = Long.MIN_VALUE;
// @Override
// public List<OutputRecord<KEY, OUT>> advanceWatermark(long newWatermark) {
// if (newWatermark < this.currentWatermark) {
// throw new IllegalArgumentException("Watermark cannot go backwards");
// }
// this.currentWatermark = newWatermark;
// ... // fire timers that are due (timerTimestamp <= newWatermark)
// }
// But then the harness also checks. That's redundant. We can remove the check from the harness and let the operator do it?
// But the harness is the one that is driving the watermark. It should ensure the watermark does not go backwards.
// We'll keep the check in the harness and then the operator can assume the watermark is increasing.
// So the operator does not need to check, but it must store the current watermark for timer comparisons.
// We can change the operator interface to:
// interface OperatorAdapter<IN, OUT, KEY> {
// List<OutputRecord<KEY, OUT>> processElement(IN element, long timestamp);
// List<OutputRecord<KEY, OUT>> advanceWatermark(long newWatermark, long oldWatermark); // but we don't want to pass oldWatermark?
// }
// Actually, the operator needs to know the new watermark and also the old watermark to know which timers have become due?
// The operator can store the current watermark and then when `advanceWatermark` is called, it knows the old watermark (the stored one) and the new one.
// So we can have:
// List<OutputRecord<KEY, OUT>> advanceWatermark(long newWatermark);
// and the operator stores the current watermark. Then the operator can compute the difference and fire timers that are in (oldWatermark, newWatermark].
// So we are good.
// Let's write the code.
// We'll create:
// public class OutputRecord<KEY, OUT> {
// private final KEY key;
// private final OUT value;
// private final boolean isRetraction;
// private final long timestamp;
//
// public OutputRecord(KEY key, OUT value, boolean isRetraction, long timestamp) {
// this.key = key;
// this.value = value;
// this.isRetraction = isRetraction;
// this.timestamp = timestamp;
// }
//
// // getters, equals, hashCode
// }
// public interface OperatorAdapter<IN, OUT, KEY> {
// List<OutputRecord<KEY, OUT>> processElement(IN element, long timestamp);
// List<OutputRecord<KEY, OUT>> advanceWatermark(long newWatermark);
// }
// public class BackfillHarness<IN, OUT, KEY> {
// private OperatorAdapter<IN, OUT, KEY> operator;
// private List<OutputRecord<KEY, OUT>> outputRecords;
// private long currentWatermark;
//
// public BackfillHarness(OperatorAdapter<IN, OUT, KEY> operator, long initialWatermark) {
// this.operator = operator;
// this.outputRecords = new ArrayList<>();
// this.currentWatermark = initialWatermark;
// }
//
// public void processElement(IN element, long timestamp) {
// List<OutputRecord<KEY, OUT>> records = operator.processElement(element, timestamp);
// outputRecords.addAll(records);
// }
//
// public void advanceWatermark(long newWatermark) {
// if (newWatermark < currentWatermark) {
// throw new IllegalArgumentException("Watermark cannot go backwards: current=" + currentWatermark + ", new=" + newWatermark);
// }
// currentWatermark = newWatermark;
// List<OutputRecord<KEY, OUT>> records = operator.advanceWatermark(newWatermark);
// outputRecords.addAll(records);
// }
//
// public List<OutputRecord<KEY, OUT>> getOutputRecords() {
// return new ArrayList<>(outputRecords);
// }
//
// public long getCurrentWatermark() {
// return currentWatermark;
// }
// }
// This is the design.
// Now, note: the operator might also have processing time timers. We can extend with:
// public void advanceProcessingTime(long newProcessingTime) {
// // similar to watermark
// }
// But the problem says "watermark moves", so we skip.
// We are done.
// However, the problem says "safe backfill harness". We must also consider:
// - The operator might have state that is stored in checkpointed state. The harness does not deal with checkpointing.
// We are only testing the operator's behavior in a single JVM, not distributed.
// So we are good.
// Let's write the code accordingly.
// But note: the operator might be multi-threaded? We assume single-threaded for testing.
// We are done.
// One more thing: the operator might emit output with a timestamp that is less than the current watermark? That is allowed (like when processing late elements, but then the watermark is already past that).
// The harness does not enforce that the output's timestamp is >= currentWatermark. It just records whatever the operator emits.
// That's okay because the operator might emit late data (with a timestamp less than the watermark) and then we can check that in the test.
// So we are flexible.
// Final code:
// We'll write the classes as above.
// But note: the `OutputRecord` should be immutable and have proper equals and hashCode.
// We'll write:
// public final class OutputRecord<KEY, OUT> {
// private final KEY key;
// private final OUT value;
// private final boolean isRetraction;
// private final long timestamp;
//
// public OutputRecord(KEY key, OUT value, boolean isRetraction, long timestamp) {
// this.key = key;
// this.value = value;
// this.isRetraction = isRetraction;
// this.timestamp = timestamp;
// }
//
// public KEY getKey() { return key; }
// public OUT getValue() { return value; }
// public boolean isRetraction() { return isRetraction; }
// public long getTimestamp() { return timestamp; }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// OutputRecord<?, ?> that = (OutputRecord<?, ?>) o;
// return isRetraction == that.isRetraction && timestamp == that.timestamp &&
// Objects.equals(key, that.key) && Objects.equals(value, that.value);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(key, value, isRetraction, timestamp);
// }
// }
// And the rest as above.
// We are done.
// However, note: the operator might be stateful and we want to test state cleanup. The harness does not provide a way to check the operator's state.
// We can extend the `OperatorAdapter` to have a method to get the state (for testing). But that would be operator-specific.
// Alternatively, we can have a separate interface for stateful operators that we want to inspect.
// Since the problem does not specify, we leave it out.
// This harness is for output verification and watermark control.
// Let's write the code.
// But note: the operator might have multiple keys. The `OutputRecord` has a key of type KEY. So for non-keyed operators, we can set key to null.
// We are done.
// One more: what if the operator emits multiple records for the same key at the same watermark? That's allowed.
// The harness records them in order.
// We are done.
// Let's write the code accordingly.
// However, note: the operator might emit records with the same key, value, and timestamp but one is a retraction and one is not? That would be odd.
// We don't prevent that.
// We are done.
// Final note: the operator might have internal timers that are set to fire at a specific timestamp. When we advance the watermark, we fire all timers with timestamp <= newWatermark.
// The operator must handle that.
// We are done.
// Let's write the code.</think>