You are viewing a plain text version of this content. The canonical link for it is here.
Posted to jira@kafka.apache.org by GitBox <gi...@apache.org> on 2022/05/24 17:26:59 UTC
[GitHub] [kafka] guozhangwang opened a new pull request, #12204: [9/N][Emit final] Emit final for session window aggregations
guozhangwang opened a new pull request, #12204:
URL: https://github.com/apache/kafka/pull/12204
1. Add a new API for session windows to range query session window by end time (KIP related).
2. Augment session window aggregator with emit strategy.
3. Minor: consolidated some dup classes.
### Committer Checklist (excluded from commit message)
- [ ] Verify design and implementation
- [ ] Verify test coverage and CI build status
- [ ] Verify documentation (including upgrade notes)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mjsax commented on a diff in pull request #12204: [9/N WIP][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
mjsax commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r898339592
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/InMemorySessionStore.java:
##########
@@ -202,25 +205,43 @@ public void remove(final Windowed<Bytes> sessionKey) {
@Override
public byte[] fetchSession(final Bytes key,
- final long earliestSessionEndTime,
- final long latestSessionStartTime) {
+ final long sessionStartTime,
+ final long sessionEndTime) {
removeExpiredSegments();
Objects.requireNonNull(key, "key cannot be null");
// Only need to search if the record hasn't expired yet
- if (latestSessionStartTime > observedStreamTime - retentionPeriod) {
- final ConcurrentNavigableMap<Bytes, ConcurrentNavigableMap<Long, byte[]>> keyMap = endTimeMap.get(latestSessionStartTime);
+ if (sessionEndTime > observedStreamTime - retentionPeriod) {
+ final ConcurrentNavigableMap<Bytes, ConcurrentNavigableMap<Long, byte[]>> keyMap = endTimeMap.get(sessionEndTime);
if (keyMap != null) {
final ConcurrentNavigableMap<Long, byte[]> startTimeMap = keyMap.get(key);
if (startTimeMap != null) {
- return startTimeMap.get(earliestSessionEndTime);
+ return startTimeMap.get(sessionStartTime);
}
}
}
return null;
}
+ @Override
+ public KeyValueIterator<Windowed<Bytes>, byte[]> findSessions(final Instant earliestSessionEndTime,
+ final Instant latestSessionEndTime) {
+ removeExpiredSegments();
+
+ final long earliestEndTime = ApiUtils.validateMillisecondInstant(earliestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(earliestSessionEndTime, "earliestSessionEndTime"));
+ final long latestEndTime = ApiUtils.validateMillisecondInstant(latestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(latestSessionEndTime, "latestSessionEndTime"));
+
+ // since subMap is exclusive on toKey, we need to plus one
+ return registerNewIterator(null,
+ null,
+ Long.MAX_VALUE,
+ endTimeMap.subMap(earliestEndTime, latestEndTime + 1).entrySet().iterator(),
Review Comment:
Nit: can we call `subMap(earliestEndTime, true, latestEndTime, true)` which is the same thing but more "intuitive" as we always search for _inclusive_ bounds throughout the code (otherwise, this is the only place which has an exclusive upper bound).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mjsax commented on a diff in pull request #12204: [9/N WIP][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
mjsax commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r898340071
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/InMemorySessionStore.java:
##########
@@ -202,25 +205,43 @@ public void remove(final Windowed<Bytes> sessionKey) {
@Override
public byte[] fetchSession(final Bytes key,
- final long earliestSessionEndTime,
- final long latestSessionStartTime) {
+ final long sessionStartTime,
+ final long sessionEndTime) {
removeExpiredSegments();
Objects.requireNonNull(key, "key cannot be null");
// Only need to search if the record hasn't expired yet
- if (latestSessionStartTime > observedStreamTime - retentionPeriod) {
- final ConcurrentNavigableMap<Bytes, ConcurrentNavigableMap<Long, byte[]>> keyMap = endTimeMap.get(latestSessionStartTime);
+ if (sessionEndTime > observedStreamTime - retentionPeriod) {
+ final ConcurrentNavigableMap<Bytes, ConcurrentNavigableMap<Long, byte[]>> keyMap = endTimeMap.get(sessionEndTime);
if (keyMap != null) {
final ConcurrentNavigableMap<Long, byte[]> startTimeMap = keyMap.get(key);
if (startTimeMap != null) {
- return startTimeMap.get(earliestSessionEndTime);
+ return startTimeMap.get(sessionStartTime);
}
}
}
return null;
}
+ @Override
+ public KeyValueIterator<Windowed<Bytes>, byte[]> findSessions(final Instant earliestSessionEndTime,
+ final Instant latestSessionEndTime) {
+ removeExpiredSegments();
+
+ final long earliestEndTime = ApiUtils.validateMillisecondInstant(earliestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(earliestSessionEndTime, "earliestSessionEndTime"));
+ final long latestEndTime = ApiUtils.validateMillisecondInstant(latestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(latestSessionEndTime, "latestSessionEndTime"));
+
+ // since subMap is exclusive on toKey, we need to plus one
+ return registerNewIterator(null,
+ null,
+ Long.MAX_VALUE,
+ endTimeMap.subMap(earliestEndTime, latestEndTime + 1).entrySet().iterator(),
+ true);
Review Comment:
Ok. I read the code of `InMemorySessionStore` in detail and now understand what's going on. This LGTM.
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/InMemorySessionStore.java:
##########
@@ -202,25 +205,43 @@ public void remove(final Windowed<Bytes> sessionKey) {
@Override
public byte[] fetchSession(final Bytes key,
- final long earliestSessionEndTime,
- final long latestSessionStartTime) {
+ final long sessionStartTime,
+ final long sessionEndTime) {
removeExpiredSegments();
Objects.requireNonNull(key, "key cannot be null");
// Only need to search if the record hasn't expired yet
- if (latestSessionStartTime > observedStreamTime - retentionPeriod) {
- final ConcurrentNavigableMap<Bytes, ConcurrentNavigableMap<Long, byte[]>> keyMap = endTimeMap.get(latestSessionStartTime);
+ if (sessionEndTime > observedStreamTime - retentionPeriod) {
+ final ConcurrentNavigableMap<Bytes, ConcurrentNavigableMap<Long, byte[]>> keyMap = endTimeMap.get(sessionEndTime);
if (keyMap != null) {
final ConcurrentNavigableMap<Long, byte[]> startTimeMap = keyMap.get(key);
if (startTimeMap != null) {
- return startTimeMap.get(earliestSessionEndTime);
+ return startTimeMap.get(sessionStartTime);
}
}
}
return null;
}
+ @Override
+ public KeyValueIterator<Windowed<Bytes>, byte[]> findSessions(final Instant earliestSessionEndTime,
+ final Instant latestSessionEndTime) {
+ removeExpiredSegments();
+
+ final long earliestEndTime = ApiUtils.validateMillisecondInstant(earliestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(earliestSessionEndTime, "earliestSessionEndTime"));
+ final long latestEndTime = ApiUtils.validateMillisecondInstant(latestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(latestSessionEndTime, "latestSessionEndTime"));
+
+ // since subMap is exclusive on toKey, we need to plus one
+ return registerNewIterator(null,
+ null,
+ Long.MAX_VALUE,
Review Comment:
nit: indention
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] guozhangwang commented on a diff in pull request #12204: [9/N][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
guozhangwang commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r907965204
##########
streams/src/main/java/org/apache/kafka/streams/kstream/internals/KStreamSessionWindowAggregate.java:
##########
@@ -148,55 +173,182 @@ public void process(final Record<KIn, VIn> record) {
}
}
- if (mergedWindow.end() < closeTime) {
- if (context().recordMetadata().isPresent()) {
- final RecordMetadata recordMetadata = context().recordMetadata().get();
- LOG.warn(
- "Skipping record for expired window. " +
- "topic=[{}] " +
- "partition=[{}] " +
- "offset=[{}] " +
- "timestamp=[{}] " +
- "window=[{},{}] " +
- "expiration=[{}] " +
- "streamTime=[{}]",
- recordMetadata.topic(), recordMetadata.partition(), recordMetadata.offset(),
- timestamp,
- mergedWindow.start(), mergedWindow.end(),
- closeTime,
- observedStreamTime
- );
- } else {
- LOG.warn(
- "Skipping record for expired window. Topic, partition, and offset not known. " +
- "timestamp=[{}] " +
- "window=[{},{}] " +
- "expiration=[{}] " +
- "streamTime=[{}]",
- timestamp,
- mergedWindow.start(), mergedWindow.end(),
- closeTime,
- observedStreamTime
- );
- }
- droppedRecordsSensor.record();
+ if (mergedWindow.end() < windowCloseTime) {
+ logSkippedRecordForExpiredWindow(timestamp, windowCloseTime, mergedWindow);
} else {
if (!mergedWindow.equals(newSessionWindow)) {
for (final KeyValue<Windowed<KIn>, VAgg> session : merged) {
store.remove(session.key);
+
+ maybeForwardUpdate(session.key, session.value, null);
+ /*
tupleForwarder.maybeForward(
record.withKey(session.key)
.withValue(new Change<>(null, session.value)));
+ */
}
}
agg = aggregator.apply(record.key(), record.value(), agg);
final Windowed<KIn> sessionKey = new Windowed<>(record.key(), mergedWindow);
store.put(sessionKey, agg);
+
+ maybeForwardUpdate(sessionKey, null, agg);
+ /*
tupleForwarder.maybeForward(
record.withKey(sessionKey)
.withValue(new Change<>(agg, null)));
+ */
+ }
+
+ maybeForwardFinalResult(record, windowCloseTime);
+ }
+
+ private void maybeForwardUpdate(final Windowed<KIn> windowedkey,
+ final VAgg oldAgg,
+ final VAgg newAgg) {
+ if (emitStrategy.type() == EmitStrategy.StrategyType.ON_WINDOW_CLOSE) {
+ return;
+ }
+
+ // Update the sent record timestamp to the window end time if possible
+ final long newTimestamp = windowedkey.window().end();
+ tupleForwarder.maybeForward(new Record<>(windowedkey, new Change<>(newAgg, sendOldValues ? oldAgg : null), newTimestamp));
+ }
+
+ // TODO: consolidate SessionWindow with TimeWindow to merge common functions
+ private void maybeForwardFinalResult(final Record<KIn, VIn> record, final long windowCloseTime) {
+ if (shouldEmitFinal(windowCloseTime)) {
+ final long emitRangeUpperBound = emitRangeUpperBound(windowCloseTime);
+
+ // if the upper bound is smaller than 0, then there's no window closed ever;
+ // and we can skip range fetching
+ if (emitRangeUpperBound >= 0) {
+ final long emitRangeLowerBound = emitRangeLowerBound();
+
+ if (shouldRangeFetch(emitRangeLowerBound, emitRangeUpperBound)) {
+ fetchAndEmit(record, windowCloseTime, emitRangeLowerBound, emitRangeUpperBound);
+ }
+ }
+ }
+ }
+
+ private boolean shouldEmitFinal(final long windowCloseTime) {
+ if (emitStrategy.type() != EmitStrategy.StrategyType.ON_WINDOW_CLOSE) {
+ return false;
+ }
+
+ final long now = internalProcessorContext.currentSystemTimeMs();
+ // Throttle emit frequency
+ if (now < timeTracker.nextTimeToEmit) {
+ return false;
+ }
+
+ // Schedule next emit time based on now to avoid the case that if system time jumps a lot,
+ // this can be triggered every time
+ timeTracker.nextTimeToEmit = now;
+ timeTracker.advanceNextTimeToEmit();
+
+ // Only EMIT if the window close time does progress
+ return lastEmitWindowCloseTime == ConsumerRecord.NO_TIMESTAMP || lastEmitWindowCloseTime < windowCloseTime;
+ }
+
+ private long emitRangeLowerBound() {
+ return lastEmitWindowCloseTime == ConsumerRecord.NO_TIMESTAMP ? 0L : Math.max(0L, lastEmitWindowCloseTime);
+ }
+
+ private long emitRangeUpperBound(final long windowCloseTime) {
+ // Session window's start and end timestamps are inclusive, so
+ // we should minus 1 for the inclusive closed window-end upper bound
+ return windowCloseTime - 1;
+ }
+
+ private boolean shouldRangeFetch(final long emitRangeLowerBound, final long emitRangeUpperBound) {
+ return emitRangeUpperBound > emitRangeLowerBound;
+ }
+
+ private void fetchAndEmit(final Record<KIn, VIn> record,
+ final long windowCloseTime,
+ final long emitRangeLowerBound,
+ final long emitRangeUpperBound) {
+ final long startMs = time.milliseconds();
Review Comment:
Should be ms to be consistent with other metrics.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] guozhangwang commented on a diff in pull request #12204: [9/N][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
guozhangwang commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r909085084
##########
streams/src/main/java/org/apache/kafka/streams/kstream/internals/SessionWindowedKStreamImpl.java:
##########
@@ -286,7 +286,8 @@ private <VR> StoreBuilder<SessionStore<K, VR>> materialize(final MaterializedInt
builder.withLoggingDisabled();
}
- if (materialized.cachingEnabled()) {
+ // do not enable cache if the emit final strategy is used
Review Comment:
cc @lihaosky this is what I did for session store during the topology building phase.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] guozhangwang commented on a diff in pull request #12204: [9/N][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
guozhangwang commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r909084546
##########
streams/src/test/java/org/apache/kafka/streams/kstream/internals/KStreamSessionWindowAggregateProcessorTest.java:
##########
@@ -253,20 +300,29 @@ public void shouldRemoveMergedSessionsFromStateStore() {
@Test
public void shouldHandleMultipleSessionsAndMerging() {
+ time.sleep(1001L);
Review Comment:
Ack!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mjsax commented on a diff in pull request #12204: [9/N][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
mjsax commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r907880688
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/SessionKeySchema.java:
##########
@@ -35,7 +35,7 @@ public class SessionKeySchema implements SegmentedBytesStore.KeySchema {
private static final byte[] MIN_SUFFIX = new byte[SUFFIX_SIZE];
public static int keyByteLength(final Bytes key) {
- return key.get().length + 2 * TIMESTAMP_SIZE;
+ return (key == null ? 0 : key.get().length) + 2 * TIMESTAMP_SIZE;
Review Comment:
Can `key` ever be `null` here?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] guozhangwang commented on a diff in pull request #12204: [9/N][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
guozhangwang commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r907965549
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/PrefixedSessionKeySchemas.java:
##########
@@ -204,7 +203,8 @@ public static void writeBinary(final ByteBuffer buf,
final long endTime) {
buf.putLong(endTime);
buf.putLong(startTime);
- buf.put(key.get());
+ if (key != null)
Review Comment:
Yes it's possible since it's used to write lower/upper boundaries in which keys could be null.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mjsax commented on a diff in pull request #12204: [9/N WIP][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
mjsax commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r898406030
##########
streams/src/main/java/org/apache/kafka/streams/state/SessionStore.java:
##########
@@ -39,6 +39,13 @@
*/
public interface SessionStore<K, AGG> extends StateStore, ReadOnlySessionStore<K, AGG> {
+ // TODO: javadoc; both ends are inclusive
+ default KeyValueIterator<Windowed<K>, AGG> findSessions(final Instant earliestSessionEndTime,
Review Comment:
I think there is no way around it? In the end, we allow users to plugin a custom session-store -- thus, if the use the new emit-final, why will need to implement this new method -- existing code with custom session-stores should not break, because existing code does neither implement but also not sure this new method.
If we don't make it public API, we would prevent users to pass in custom session-stores in combination with the new emit-final feature, what seems to be too restrictive?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mjsax commented on a diff in pull request #12204: [9/N WIP][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
mjsax commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r887381498
##########
streams/src/main/java/org/apache/kafka/streams/kstream/internals/KStreamSessionWindowAggregate.java:
##########
@@ -83,50 +94,64 @@ private class KStreamSessionWindowAggregateProcessor extends
ContextualProcessor<KIn, VIn, Windowed<KIn>, Change<VAgg>> {
private SessionStore<KIn, VAgg> store;
- private SessionTupleForwarder<KIn, VAgg> tupleForwarder;
+ private TimestampedTupleForwarder<Windowed<KIn>, VAgg> tupleForwarder;
private Sensor droppedRecordsSensor;
+ private Sensor emittedRecordsSensor;
+ private Sensor emitFinalLatencySensor;
+ private long lastEmitWindowCloseTime = ConsumerRecord.NO_TIMESTAMP;
private long observedStreamTime = ConsumerRecord.NO_TIMESTAMP;
+ private InternalProcessorContext<Windowed<KIn>, Change<VAgg>> internalProcessorContext;
+
+ private final Time time = Time.SYSTEM;
Review Comment:
Should we not better pass in a `Time` object, so we can mock it using TTD?
##########
streams/src/main/java/org/apache/kafka/streams/kstream/internals/AbstractKStreamTimeWindowAggregateProcessor.java:
##########
@@ -73,11 +73,10 @@ public void init(final ProcessorContext<Windowed<KIn>, Change<VAgg>> context) {
internalProcessorContext = (InternalProcessorContext<Windowed<KIn>, Change<VAgg>>) context;
final StreamsMetricsImpl metrics = internalProcessorContext.metrics();
final String threadId = Thread.currentThread().getName();
+ final String processorName = internalProcessorContext.currentNode().name();
droppedRecordsSensor = droppedRecordsSensor(threadId, context.taskId().toString(), metrics);
- emittedRecordsSensor = emittedRecordsSensor(threadId, context.taskId().toString(),
- internalProcessorContext.currentNode().name(), metrics);
- emitFinalLatencySensor = emitFinalLatencySensor(threadId, context.taskId().toString(),
- internalProcessorContext.currentNode().name(), metrics);
+ emittedRecordsSensor = emittedRecordsSensor(threadId, context.taskId().toString(), processorName, metrics);
+ emitFinalLatencySensor = emitFinalLatencySensor(threadId, context.taskId().toString(), processorName, metrics);
Review Comment:
Thanks for all the cleanup -- it's somewhat distracting from the actual changes.
Can we (in the future) extract refactorings/cleanups into individual PRs to simplify reviewing?
##########
streams/src/main/java/org/apache/kafka/streams/kstream/internals/KStreamSessionWindowAggregate.java:
##########
@@ -148,55 +173,184 @@ public void process(final Record<KIn, VIn> record) {
}
}
- if (mergedWindow.end() < closeTime) {
- if (context().recordMetadata().isPresent()) {
- final RecordMetadata recordMetadata = context().recordMetadata().get();
- LOG.warn(
- "Skipping record for expired window. " +
- "topic=[{}] " +
- "partition=[{}] " +
- "offset=[{}] " +
- "timestamp=[{}] " +
- "window=[{},{}] " +
- "expiration=[{}] " +
- "streamTime=[{}]",
- recordMetadata.topic(), recordMetadata.partition(), recordMetadata.offset(),
- timestamp,
- mergedWindow.start(), mergedWindow.end(),
- closeTime,
- observedStreamTime
- );
- } else {
- LOG.warn(
- "Skipping record for expired window. Topic, partition, and offset not known. " +
- "timestamp=[{}] " +
- "window=[{},{}] " +
- "expiration=[{}] " +
- "streamTime=[{}]",
- timestamp,
- mergedWindow.start(), mergedWindow.end(),
- closeTime,
- observedStreamTime
- );
- }
- droppedRecordsSensor.record();
+ if (mergedWindow.end() < windowCloseTime) {
+ logSkippedRecordForExpiredWindow(timestamp, windowCloseTime, mergedWindow);
} else {
if (!mergedWindow.equals(newSessionWindow)) {
for (final KeyValue<Windowed<KIn>, VAgg> session : merged) {
store.remove(session.key);
+
+ maybeForwardUpdate(session.key, session.value, null, record.timestamp());
+ /*
tupleForwarder.maybeForward(
record.withKey(session.key)
.withValue(new Change<>(null, session.value)));
+ */
}
}
agg = aggregator.apply(record.key(), record.value(), agg);
final Windowed<KIn> sessionKey = new Windowed<>(record.key(), mergedWindow);
store.put(sessionKey, agg);
+
+ maybeForwardUpdate(sessionKey, null, agg, record.timestamp());
+ /*
tupleForwarder.maybeForward(
record.withKey(sessionKey)
.withValue(new Change<>(agg, null)));
+ */
}
+
+ maybeForwardFinalResult(record, windowCloseTime);
+ }
+
+ private void maybeForwardUpdate(final Windowed<KIn> windowedkey,
+ final VAgg oldAgg,
+ final VAgg newAgg,
+ final long oldTimestamp) {
+ if (emitStrategy.type() == EmitStrategy.StrategyType.ON_WINDOW_CLOSE) {
+ return;
+ }
+
+ // Update the sent record timestamp to the window end time if possible
+ final long newTimestamp = windowedkey.key() != null ? windowedkey.window().end() : oldTimestamp;
Review Comment:
For what case could `windowedkey.key() == null` ? Is this even possible?
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/RocksDBTimeOrderedSessionStore.java:
##########
@@ -61,6 +65,18 @@ public <R> QueryResult<R> query(final Query<R> query,
);
}
+ @Override
+ public KeyValueIterator<Windowed<Bytes>, byte[]> findSessions(final Instant earliestSessionEndTime,
+ final Instant latestSessionEndTime) {
+ final long earliestEndTime = ApiUtils.validateMillisecondInstant(earliestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(earliestSessionEndTime, "earliestSessionEndTime"));
+ final long latestEndTime = ApiUtils.validateMillisecondInstant(latestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(latestSessionEndTime, "latestSessionEndTime"));
+
+ final KeyValueIterator<Bytes, byte[]> bytesIterator = wrapped().fetchAll(earliestEndTime, latestEndTime);
Review Comment:
Not sure -- I always need to think very hard to understand (not even sure if I succeed) the fetch logic and how we compute the bounds...
But same question as above: why do we need this new method instead of calling `findSessions(null, null, A, B)` -- I briefly dug into the code and it seems it would do the same thing?
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/InMemorySessionStore.java:
##########
@@ -202,25 +205,43 @@ public void remove(final Windowed<Bytes> sessionKey) {
@Override
public byte[] fetchSession(final Bytes key,
- final long earliestSessionEndTime,
- final long latestSessionStartTime) {
+ final long sessionStartTime,
+ final long sessionEndTime) {
removeExpiredSegments();
Objects.requireNonNull(key, "key cannot be null");
// Only need to search if the record hasn't expired yet
- if (latestSessionStartTime > observedStreamTime - retentionPeriod) {
- final ConcurrentNavigableMap<Bytes, ConcurrentNavigableMap<Long, byte[]>> keyMap = endTimeMap.get(latestSessionStartTime);
+ if (sessionEndTime > observedStreamTime - retentionPeriod) {
+ final ConcurrentNavigableMap<Bytes, ConcurrentNavigableMap<Long, byte[]>> keyMap = endTimeMap.get(sessionEndTime);
if (keyMap != null) {
final ConcurrentNavigableMap<Long, byte[]> startTimeMap = keyMap.get(key);
if (startTimeMap != null) {
- return startTimeMap.get(earliestSessionEndTime);
+ return startTimeMap.get(sessionStartTime);
}
}
}
return null;
}
+ @Override
+ public KeyValueIterator<Windowed<Bytes>, byte[]> findSessions(final Instant earliestSessionEndTime,
+ final Instant latestSessionEndTime) {
+ removeExpiredSegments();
+
+ final long earliestEndTime = ApiUtils.validateMillisecondInstant(earliestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(earliestSessionEndTime, "earliestSessionEndTime"));
+ final long latestEndTime = ApiUtils.validateMillisecondInstant(latestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(latestSessionEndTime, "latestSessionEndTime"));
+
+ // since subMap is exclusive on toKey, we need to plus one
+ return registerNewIterator(null,
+ null,
+ Long.MAX_VALUE,
+ endTimeMap.subMap(earliestEndTime, latestEndTime + 1).entrySet().iterator(),
+ true);
Review Comment:
Not sure if I fully understand why we add this new method instead of calling `findSession(null, null, A, B)` ?
The code to create the iterator is different, but I am also not sure why. Is it semantically actually the same? Calling `findSession(null, null, A, B)` would do:
```
registerNewIterator(null, // same
null, // same
latestSessionStartTime, // why does your code pass Long.MAX_VALUE,
// but because we use `tailMap` instead of `subMap` below, it seems to do the same thing overall?
endTimeMap.tailMap(earliestSessionEndTime, true).entrySet().iterator(),
true); // same
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mjsax commented on pull request #12204: [9/N][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
mjsax commented on PR #12204:
URL: https://github.com/apache/kafka/pull/12204#issuecomment-1169391432
LGTM (assuming Jenkins passes).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] guozhangwang commented on a diff in pull request #12204: [9/N][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
guozhangwang commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r907967640
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/RocksDBTimeOrderedSessionSegmentedBytesStore.java:
##########
@@ -71,6 +72,36 @@ public byte[] fetchSession(final Bytes key,
));
}
+ public KeyValueIterator<Bytes, byte[]> fetchSessions(final long earliestSessionEndTime,
+ final long latestSessionEndTime) {
+ final List<KeyValueSegment> searchSpace = segments.segments(earliestSessionEndTime, latestSessionEndTime, true);
+
+ // here we want [0, latestSE, FF] as the upper bound to cover any possible keys,
Review Comment:
This is the other minor bug I detected in the latest commit.
##########
streams/src/main/java/org/apache/kafka/streams/kstream/internals/KStreamSessionWindowAggregate.java:
##########
@@ -148,55 +173,174 @@ public void process(final Record<KIn, VIn> record) {
}
}
- if (mergedWindow.end() < closeTime) {
- if (context().recordMetadata().isPresent()) {
- final RecordMetadata recordMetadata = context().recordMetadata().get();
- LOG.warn(
- "Skipping record for expired window. " +
- "topic=[{}] " +
- "partition=[{}] " +
- "offset=[{}] " +
- "timestamp=[{}] " +
- "window=[{},{}] " +
- "expiration=[{}] " +
- "streamTime=[{}]",
- recordMetadata.topic(), recordMetadata.partition(), recordMetadata.offset(),
- timestamp,
- mergedWindow.start(), mergedWindow.end(),
- closeTime,
- observedStreamTime
- );
- } else {
- LOG.warn(
- "Skipping record for expired window. Topic, partition, and offset not known. " +
- "timestamp=[{}] " +
- "window=[{},{}] " +
- "expiration=[{}] " +
- "streamTime=[{}]",
- timestamp,
- mergedWindow.start(), mergedWindow.end(),
- closeTime,
- observedStreamTime
- );
- }
- droppedRecordsSensor.record();
+ if (mergedWindow.end() < windowCloseTime) {
+ logSkippedRecordForExpiredWindow(timestamp, windowCloseTime, mergedWindow);
} else {
if (!mergedWindow.equals(newSessionWindow)) {
for (final KeyValue<Windowed<KIn>, VAgg> session : merged) {
store.remove(session.key);
- tupleForwarder.maybeForward(
- record.withKey(session.key)
- .withValue(new Change<>(null, session.value)));
+
+ maybeForwardUpdate(session.key, session.value, null);
}
}
agg = aggregator.apply(record.key(), record.value(), agg);
final Windowed<KIn> sessionKey = new Windowed<>(record.key(), mergedWindow);
store.put(sessionKey, agg);
+
+ maybeForwardUpdate(sessionKey, null, agg);
+ }
+
+ maybeForwardFinalResult(record, windowCloseTime);
+ }
+
+ private void maybeForwardUpdate(final Windowed<KIn> windowedkey,
+ final VAgg oldAgg,
+ final VAgg newAgg) {
+ if (emitStrategy.type() == EmitStrategy.StrategyType.ON_WINDOW_CLOSE) {
+ return;
+ }
+
+ // Update the sent record timestamp to the window end time if possible
+ final long newTimestamp = windowedkey.window().end();
+ tupleForwarder.maybeForward(new Record<>(windowedkey, new Change<>(newAgg, sendOldValues ? oldAgg : null), newTimestamp));
+ }
+
+ // TODO: consolidate SessionWindow with TimeWindow to merge common functions
+ private void maybeForwardFinalResult(final Record<KIn, VIn> record, final long windowCloseTime) {
+ if (shouldEmitFinal(windowCloseTime)) {
+ final long emitRangeUpperBound = emitRangeUpperBound(windowCloseTime);
+
+ // if the upper bound is smaller than 0, then there's no window closed ever;
+ // and we can skip range fetching
+ if (emitRangeUpperBound >= 0) {
+ final long emitRangeLowerBound = emitRangeLowerBound();
+
+ if (shouldRangeFetch(emitRangeLowerBound, emitRangeUpperBound)) {
+ fetchAndEmit(record, windowCloseTime, emitRangeLowerBound, emitRangeUpperBound);
+ }
+ }
+ }
+ }
+
+ private boolean shouldEmitFinal(final long windowCloseTime) {
+ if (emitStrategy.type() != EmitStrategy.StrategyType.ON_WINDOW_CLOSE) {
+ return false;
+ }
+
+ final long now = internalProcessorContext.currentSystemTimeMs();
+ // Throttle emit frequency
+ if (now < timeTracker.nextTimeToEmit) {
+ return false;
+ }
+
+ // Schedule next emit time based on now to avoid the case that if system time jumps a lot,
+ // this can be triggered every time
+ timeTracker.nextTimeToEmit = now;
+ timeTracker.advanceNextTimeToEmit();
+
+ // Only EMIT if the window close time does progress
+ return lastEmitWindowCloseTime == ConsumerRecord.NO_TIMESTAMP || lastEmitWindowCloseTime < windowCloseTime;
+ }
+
+ private long emitRangeLowerBound() {
+ return Math.max(0L, lastEmitWindowCloseTime);
+ }
+
+ private long emitRangeUpperBound(final long windowCloseTime) {
+ // Session window's start and end timestamps are inclusive, so
+ // we should minus 1 for the inclusive closed window-end upper bound
+ return windowCloseTime - 1;
+ }
+
+ private boolean shouldRangeFetch(final long emitRangeLowerBound, final long emitRangeUpperBound) {
Review Comment:
This is one minor bug I detected in the latest commit.
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/SessionStoreBuilder.java:
##########
@@ -52,6 +53,16 @@ private SessionStore<Bytes, byte[]> maybeWrapCaching(final SessionStore<Bytes, b
if (!enableCaching) {
return inner;
}
+
+ if (!inner.persistent()) {
Review Comment:
Here's the other change I made in order to work around the current tricky situation, since in-memory stores are always "time ordered" as well, we stripe the caching if the inner store is not persistent. cc @mjsax
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] guozhangwang commented on a diff in pull request #12204: [9/N WIP][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
guozhangwang commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r880784817
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/RocksDBTimeOrderedSessionStore.java:
##########
@@ -61,6 +65,18 @@ public <R> QueryResult<R> query(final Query<R> query,
);
}
+ @Override
+ public KeyValueIterator<Windowed<Bytes>, byte[]> findSessions(final Instant earliestSessionEndTime,
+ final Instant latestSessionEndTime) {
+ final long earliestEndTime = ApiUtils.validateMillisecondInstant(earliestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(earliestSessionEndTime, "earliestSessionEndTime"));
+ final long latestEndTime = ApiUtils.validateMillisecondInstant(latestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(latestSessionEndTime, "latestSessionEndTime"));
+
+ final KeyValueIterator<Bytes, byte[]> bytesIterator = wrapped().fetchAll(earliestEndTime, latestEndTime);
Review Comment:
This is the second open question: with the current prefixed (base, i.e. time-first) session key schema, this fetchAll would be effectively searching for `[earliestEnd, INF]` because of this logic: https://github.com/apache/kafka/blob/trunk/streams/src/main/java/org/apache/kafka/streams/state/internals/PrefixedSessionKeySchemas.java#L46
This is because we translate the range query without key inside `AbstractRocksDBTimeOrderedSegmentedBytesStore` by using the `lower/upperRange` instead of `lower/upperRangeFixedSize`): https://github.com/apache/kafka/blob/trunk/streams/src/main/java/org/apache/kafka/streams/state/internals/AbstractRocksDBTimeOrderedSegmentedBytesStore.java#L241-L242
I cannot remember why we need to do this. @lihaosky @mjsax do you remember why?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] guozhangwang commented on a diff in pull request #12204: [9/N WIP][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
guozhangwang commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r888483482
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/InMemorySessionStore.java:
##########
@@ -202,25 +205,43 @@ public void remove(final Windowed<Bytes> sessionKey) {
@Override
public byte[] fetchSession(final Bytes key,
- final long earliestSessionEndTime,
- final long latestSessionStartTime) {
+ final long sessionStartTime,
+ final long sessionEndTime) {
removeExpiredSegments();
Objects.requireNonNull(key, "key cannot be null");
// Only need to search if the record hasn't expired yet
- if (latestSessionStartTime > observedStreamTime - retentionPeriod) {
- final ConcurrentNavigableMap<Bytes, ConcurrentNavigableMap<Long, byte[]>> keyMap = endTimeMap.get(latestSessionStartTime);
+ if (sessionEndTime > observedStreamTime - retentionPeriod) {
+ final ConcurrentNavigableMap<Bytes, ConcurrentNavigableMap<Long, byte[]>> keyMap = endTimeMap.get(sessionEndTime);
if (keyMap != null) {
final ConcurrentNavigableMap<Long, byte[]> startTimeMap = keyMap.get(key);
if (startTimeMap != null) {
- return startTimeMap.get(earliestSessionEndTime);
+ return startTimeMap.get(sessionStartTime);
}
}
}
return null;
}
+ @Override
+ public KeyValueIterator<Windowed<Bytes>, byte[]> findSessions(final Instant earliestSessionEndTime,
+ final Instant latestSessionEndTime) {
+ removeExpiredSegments();
+
+ final long earliestEndTime = ApiUtils.validateMillisecondInstant(earliestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(earliestSessionEndTime, "earliestSessionEndTime"));
+ final long latestEndTime = ApiUtils.validateMillisecondInstant(latestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(latestSessionEndTime, "latestSessionEndTime"));
+
+ // since subMap is exclusive on toKey, we need to plus one
+ return registerNewIterator(null,
+ null,
+ Long.MAX_VALUE,
+ endTimeMap.subMap(earliestEndTime, latestEndTime + 1).entrySet().iterator(),
+ true);
Review Comment:
Logically, the main reason is that for emit-final, we need a range query where the from/to are both `endTime`, i.e. you can see the parameters are `earliestSessionEndTime` and `latestSessionEndTime`.
Whereas for the existing functions, their semantics are based on `earliestSessionEndTime` but `latestSessionStartTime`. And that's also the reason for using `Long.MAX_VALUE` here.
On the physical implementation, the main difference is not in the in-memory session store, but the rocksDB session store. I will reply there separately.
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/RocksDBTimeOrderedSessionStore.java:
##########
@@ -61,6 +65,18 @@ public <R> QueryResult<R> query(final Query<R> query,
);
}
+ @Override
+ public KeyValueIterator<Windowed<Bytes>, byte[]> findSessions(final Instant earliestSessionEndTime,
+ final Instant latestSessionEndTime) {
+ final long earliestEndTime = ApiUtils.validateMillisecondInstant(earliestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(earliestSessionEndTime, "earliestSessionEndTime"));
+ final long latestEndTime = ApiUtils.validateMillisecondInstant(latestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(latestSessionEndTime, "latestSessionEndTime"));
+
+ final KeyValueIterator<Bytes, byte[]> bytesIterator = wrapped().fetchAll(earliestEndTime, latestEndTime);
Review Comment:
The main reason is that for emit final I need a range API that based on `endTime` for both ends. And that's also why within its implementation I'd have to use `fetchAll` instead of `fetch` here.
##########
streams/src/main/java/org/apache/kafka/streams/kstream/internals/AbstractKStreamTimeWindowAggregateProcessor.java:
##########
@@ -73,11 +73,10 @@ public void init(final ProcessorContext<Windowed<KIn>, Change<VAgg>> context) {
internalProcessorContext = (InternalProcessorContext<Windowed<KIn>, Change<VAgg>>) context;
final StreamsMetricsImpl metrics = internalProcessorContext.metrics();
final String threadId = Thread.currentThread().getName();
+ final String processorName = internalProcessorContext.currentNode().name();
droppedRecordsSensor = droppedRecordsSensor(threadId, context.taskId().toString(), metrics);
- emittedRecordsSensor = emittedRecordsSensor(threadId, context.taskId().toString(),
- internalProcessorContext.currentNode().name(), metrics);
- emitFinalLatencySensor = emitFinalLatencySensor(threadId, context.taskId().toString(),
- internalProcessorContext.currentNode().name(), metrics);
+ emittedRecordsSensor = emittedRecordsSensor(threadId, context.taskId().toString(), processorName, metrics);
+ emitFinalLatencySensor = emitFinalLatencySensor(threadId, context.taskId().toString(), processorName, metrics);
Review Comment:
Yes! It's my bad to mingle them together here.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] guozhangwang merged pull request #12204: [9/N][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
guozhangwang merged PR #12204:
URL: https://github.com/apache/kafka/pull/12204
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mjsax commented on a diff in pull request #12204: [9/N][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
mjsax commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r907880169
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/RocksDBTimeOrderedSessionSegmentedBytesStore.java:
##########
@@ -71,6 +72,36 @@ public byte[] fetchSession(final Bytes key,
));
}
+ public KeyValueIterator<Bytes, byte[]> fetchSessions(final long earliestSessionEndTime,
+ final long latestSessionEndTime) {
+ final List<KeyValueSegment> searchSpace = segments.segments(earliestSessionEndTime, latestSessionEndTime, true);
+
+ // here we use both as lower range since we the search boundaries are both on the session time end;
+ // hence effectively our search range is [0 earliestSE] - [0, latestSE]
+ final Bytes binaryFrom = baseKeySchema.lowerRangeFixedSize(null, earliestSessionEndTime);
+ final Bytes binaryTo = baseKeySchema.lowerRangeFixedSize(null, latestSessionEndTime);
+
+ return new SegmentIterator<>(
+ searchSpace.iterator(),
+ iterator -> {
+ while (iterator.hasNext()) {
+ final Bytes bytes = iterator.peekNextKey();
+
+ final Windowed<Bytes> windowedKey = TimeFirstSessionKeySchema.from(bytes);
+ final long endTime = windowedKey.window().end();
+
+ if (endTime <= latestSessionEndTime && endTime >= earliestSessionEndTime)
Review Comment:
nit: add `{}` to block
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mjsax commented on a diff in pull request #12204: [9/N][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
mjsax commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r907875412
##########
streams/src/main/java/org/apache/kafka/streams/kstream/internals/KStreamSessionWindowAggregate.java:
##########
@@ -148,55 +173,182 @@ public void process(final Record<KIn, VIn> record) {
}
}
- if (mergedWindow.end() < closeTime) {
- if (context().recordMetadata().isPresent()) {
- final RecordMetadata recordMetadata = context().recordMetadata().get();
- LOG.warn(
- "Skipping record for expired window. " +
- "topic=[{}] " +
- "partition=[{}] " +
- "offset=[{}] " +
- "timestamp=[{}] " +
- "window=[{},{}] " +
- "expiration=[{}] " +
- "streamTime=[{}]",
- recordMetadata.topic(), recordMetadata.partition(), recordMetadata.offset(),
- timestamp,
- mergedWindow.start(), mergedWindow.end(),
- closeTime,
- observedStreamTime
- );
- } else {
- LOG.warn(
- "Skipping record for expired window. Topic, partition, and offset not known. " +
- "timestamp=[{}] " +
- "window=[{},{}] " +
- "expiration=[{}] " +
- "streamTime=[{}]",
- timestamp,
- mergedWindow.start(), mergedWindow.end(),
- closeTime,
- observedStreamTime
- );
- }
- droppedRecordsSensor.record();
+ if (mergedWindow.end() < windowCloseTime) {
+ logSkippedRecordForExpiredWindow(timestamp, windowCloseTime, mergedWindow);
} else {
if (!mergedWindow.equals(newSessionWindow)) {
for (final KeyValue<Windowed<KIn>, VAgg> session : merged) {
store.remove(session.key);
+
+ maybeForwardUpdate(session.key, session.value, null);
+ /*
tupleForwarder.maybeForward(
record.withKey(session.key)
.withValue(new Change<>(null, session.value)));
+ */
}
}
agg = aggregator.apply(record.key(), record.value(), agg);
final Windowed<KIn> sessionKey = new Windowed<>(record.key(), mergedWindow);
store.put(sessionKey, agg);
+
+ maybeForwardUpdate(sessionKey, null, agg);
+ /*
tupleForwarder.maybeForward(
record.withKey(sessionKey)
.withValue(new Change<>(agg, null)));
+ */
+ }
+
+ maybeForwardFinalResult(record, windowCloseTime);
+ }
+
+ private void maybeForwardUpdate(final Windowed<KIn> windowedkey,
+ final VAgg oldAgg,
+ final VAgg newAgg) {
+ if (emitStrategy.type() == EmitStrategy.StrategyType.ON_WINDOW_CLOSE) {
+ return;
+ }
+
+ // Update the sent record timestamp to the window end time if possible
+ final long newTimestamp = windowedkey.window().end();
+ tupleForwarder.maybeForward(new Record<>(windowedkey, new Change<>(newAgg, sendOldValues ? oldAgg : null), newTimestamp));
+ }
+
+ // TODO: consolidate SessionWindow with TimeWindow to merge common functions
+ private void maybeForwardFinalResult(final Record<KIn, VIn> record, final long windowCloseTime) {
+ if (shouldEmitFinal(windowCloseTime)) {
+ final long emitRangeUpperBound = emitRangeUpperBound(windowCloseTime);
+
+ // if the upper bound is smaller than 0, then there's no window closed ever;
+ // and we can skip range fetching
+ if (emitRangeUpperBound >= 0) {
+ final long emitRangeLowerBound = emitRangeLowerBound();
+
+ if (shouldRangeFetch(emitRangeLowerBound, emitRangeUpperBound)) {
+ fetchAndEmit(record, windowCloseTime, emitRangeLowerBound, emitRangeUpperBound);
+ }
+ }
+ }
+ }
+
+ private boolean shouldEmitFinal(final long windowCloseTime) {
+ if (emitStrategy.type() != EmitStrategy.StrategyType.ON_WINDOW_CLOSE) {
+ return false;
+ }
+
+ final long now = internalProcessorContext.currentSystemTimeMs();
+ // Throttle emit frequency
+ if (now < timeTracker.nextTimeToEmit) {
+ return false;
+ }
+
+ // Schedule next emit time based on now to avoid the case that if system time jumps a lot,
+ // this can be triggered every time
+ timeTracker.nextTimeToEmit = now;
+ timeTracker.advanceNextTimeToEmit();
+
+ // Only EMIT if the window close time does progress
+ return lastEmitWindowCloseTime == ConsumerRecord.NO_TIMESTAMP || lastEmitWindowCloseTime < windowCloseTime;
+ }
+
+ private long emitRangeLowerBound() {
+ return lastEmitWindowCloseTime == ConsumerRecord.NO_TIMESTAMP ? 0L : Math.max(0L, lastEmitWindowCloseTime);
Review Comment:
nit: can this be simplified to `Math.max(0L, lastEmitWindowCloseTime)`? (Can also be address in follow up PR)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mjsax commented on a diff in pull request #12204: [9/N][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
mjsax commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r908934184
##########
streams/src/test/java/org/apache/kafka/streams/kstream/internals/KStreamSessionWindowAggregateProcessorTest.java:
##########
@@ -253,20 +300,29 @@ public void shouldRemoveMergedSessionsFromStateStore() {
@Test
public void shouldHandleMultipleSessionsAndMerging() {
+ time.sleep(1001L);
Review Comment:
Might it be easier to change the internal config of the "emit interval" and set it to zero (instead of advancing time)?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] guozhangwang commented on a diff in pull request #12204: [9/N][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
guozhangwang commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r906425650
##########
streams/src/main/java/org/apache/kafka/streams/kstream/internals/KStreamSessionWindowAggregate.java:
##########
@@ -148,55 +173,184 @@ public void process(final Record<KIn, VIn> record) {
}
}
- if (mergedWindow.end() < closeTime) {
- if (context().recordMetadata().isPresent()) {
- final RecordMetadata recordMetadata = context().recordMetadata().get();
- LOG.warn(
- "Skipping record for expired window. " +
- "topic=[{}] " +
- "partition=[{}] " +
- "offset=[{}] " +
- "timestamp=[{}] " +
- "window=[{},{}] " +
- "expiration=[{}] " +
- "streamTime=[{}]",
- recordMetadata.topic(), recordMetadata.partition(), recordMetadata.offset(),
- timestamp,
- mergedWindow.start(), mergedWindow.end(),
- closeTime,
- observedStreamTime
- );
- } else {
- LOG.warn(
- "Skipping record for expired window. Topic, partition, and offset not known. " +
- "timestamp=[{}] " +
- "window=[{},{}] " +
- "expiration=[{}] " +
- "streamTime=[{}]",
- timestamp,
- mergedWindow.start(), mergedWindow.end(),
- closeTime,
- observedStreamTime
- );
- }
- droppedRecordsSensor.record();
+ if (mergedWindow.end() < windowCloseTime) {
+ logSkippedRecordForExpiredWindow(timestamp, windowCloseTime, mergedWindow);
} else {
if (!mergedWindow.equals(newSessionWindow)) {
for (final KeyValue<Windowed<KIn>, VAgg> session : merged) {
store.remove(session.key);
+
+ maybeForwardUpdate(session.key, session.value, null, record.timestamp());
+ /*
tupleForwarder.maybeForward(
record.withKey(session.key)
.withValue(new Change<>(null, session.value)));
+ */
}
}
agg = aggregator.apply(record.key(), record.value(), agg);
final Windowed<KIn> sessionKey = new Windowed<>(record.key(), mergedWindow);
store.put(sessionKey, agg);
+
+ maybeForwardUpdate(sessionKey, null, agg, record.timestamp());
+ /*
tupleForwarder.maybeForward(
record.withKey(sessionKey)
.withValue(new Change<>(agg, null)));
+ */
}
+
+ maybeForwardFinalResult(record, windowCloseTime);
+ }
+
+ private void maybeForwardUpdate(final Windowed<KIn> windowedkey,
+ final VAgg oldAgg,
+ final VAgg newAgg,
+ final long oldTimestamp) {
+ if (emitStrategy.type() == EmitStrategy.StrategyType.ON_WINDOW_CLOSE) {
+ return;
+ }
+
+ // Update the sent record timestamp to the window end time if possible
+ final long newTimestamp = windowedkey.key() != null ? windowedkey.window().end() : oldTimestamp;
Review Comment:
This behavior was meant to inherit from the deleted code: https://github.com/apache/kafka/pull/12204/files#diff-85c8c92d464af8eb3a60684bf929725f8fc5263353c38cacc20bee4cefe4fd9eL53, but after checking that logic I now realized it's not necessary anymore (the original PR has to do so since we cannot programmatically guarantee it's always not `null` but in this change we do not have that concern anymore).
Will remove.
##########
streams/src/main/java/org/apache/kafka/streams/kstream/internals/KStreamSessionWindowAggregate.java:
##########
@@ -83,50 +94,64 @@ private class KStreamSessionWindowAggregateProcessor extends
ContextualProcessor<KIn, VIn, Windowed<KIn>, Change<VAgg>> {
private SessionStore<KIn, VAgg> store;
- private SessionTupleForwarder<KIn, VAgg> tupleForwarder;
+ private TimestampedTupleForwarder<Windowed<KIn>, VAgg> tupleForwarder;
private Sensor droppedRecordsSensor;
+ private Sensor emittedRecordsSensor;
+ private Sensor emitFinalLatencySensor;
+ private long lastEmitWindowCloseTime = ConsumerRecord.NO_TIMESTAMP;
private long observedStreamTime = ConsumerRecord.NO_TIMESTAMP;
+ private InternalProcessorContext<Windowed<KIn>, Change<VAgg>> internalProcessorContext;
+
+ private final Time time = Time.SYSTEM;
Review Comment:
Makes sense. I will do this in a follow-up PR after merging this.
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/RocksDBTimeOrderedSessionStore.java:
##########
@@ -61,6 +65,18 @@ public <R> QueryResult<R> query(final Query<R> query,
);
}
+ @Override
+ public KeyValueIterator<Windowed<Bytes>, byte[]> findSessions(final Instant earliestSessionEndTime,
+ final Instant latestSessionEndTime) {
+ final long earliestEndTime = ApiUtils.validateMillisecondInstant(earliestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(earliestSessionEndTime, "earliestSessionEndTime"));
+ final long latestEndTime = ApiUtils.validateMillisecondInstant(latestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(latestSessionEndTime, "latestSessionEndTime"));
+
+ final KeyValueIterator<Bytes, byte[]> bytesIterator = wrapped().fetchAll(earliestEndTime, latestEndTime);
Review Comment:
Sounds good. I would just have a special handling on both lower/upper bound as well as the hasNext function for this specific purpose.
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/InMemorySessionStore.java:
##########
@@ -202,25 +205,43 @@ public void remove(final Windowed<Bytes> sessionKey) {
@Override
public byte[] fetchSession(final Bytes key,
- final long earliestSessionEndTime,
- final long latestSessionStartTime) {
+ final long sessionStartTime,
+ final long sessionEndTime) {
removeExpiredSegments();
Objects.requireNonNull(key, "key cannot be null");
// Only need to search if the record hasn't expired yet
- if (latestSessionStartTime > observedStreamTime - retentionPeriod) {
- final ConcurrentNavigableMap<Bytes, ConcurrentNavigableMap<Long, byte[]>> keyMap = endTimeMap.get(latestSessionStartTime);
+ if (sessionEndTime > observedStreamTime - retentionPeriod) {
+ final ConcurrentNavigableMap<Bytes, ConcurrentNavigableMap<Long, byte[]>> keyMap = endTimeMap.get(sessionEndTime);
if (keyMap != null) {
final ConcurrentNavigableMap<Long, byte[]> startTimeMap = keyMap.get(key);
if (startTimeMap != null) {
- return startTimeMap.get(earliestSessionEndTime);
+ return startTimeMap.get(sessionStartTime);
}
}
}
return null;
}
+ @Override
+ public KeyValueIterator<Windowed<Bytes>, byte[]> findSessions(final Instant earliestSessionEndTime,
+ final Instant latestSessionEndTime) {
+ removeExpiredSegments();
+
+ final long earliestEndTime = ApiUtils.validateMillisecondInstant(earliestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(earliestSessionEndTime, "earliestSessionEndTime"));
+ final long latestEndTime = ApiUtils.validateMillisecondInstant(latestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(latestSessionEndTime, "latestSessionEndTime"));
+
+ // since subMap is exclusive on toKey, we need to plus one
+ return registerNewIterator(null,
+ null,
+ Long.MAX_VALUE,
+ endTimeMap.subMap(earliestEndTime, latestEndTime + 1).entrySet().iterator(),
Review Comment:
Ack.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mjsax commented on a diff in pull request #12204: [9/N][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
mjsax commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r907876784
##########
streams/src/main/java/org/apache/kafka/streams/state/SessionStore.java:
##########
@@ -39,6 +39,13 @@
*/
public interface SessionStore<K, AGG> extends StateStore, ReadOnlySessionStore<K, AGG> {
+ // TODO: javadoc; both ends are inclusive
+ default KeyValueIterator<Windowed<K>, AGG> findSessions(final Instant earliestSessionEndTime,
Review Comment:
Why did you pick `Instant` over `long` (wondering if `long` might be better as it's more an internal API)?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] guozhangwang commented on a diff in pull request #12204: [9/N][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
guozhangwang commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r907966031
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/SessionKeySchema.java:
##########
@@ -35,7 +35,7 @@ public class SessionKeySchema implements SegmentedBytesStore.KeySchema {
private static final byte[] MIN_SUFFIX = new byte[SUFFIX_SIZE];
public static int keyByteLength(final Bytes key) {
- return key.get().length + 2 * TIMESTAMP_SIZE;
+ return (key == null ? 0 : key.get().length) + 2 * TIMESTAMP_SIZE;
Review Comment:
Yes that's possible -- see above comment, for the lower/upper bound cases.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] guozhangwang commented on a diff in pull request #12204: [9/N WIP][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
guozhangwang commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r880778694
##########
streams/src/main/java/org/apache/kafka/streams/state/SessionStore.java:
##########
@@ -39,6 +39,13 @@
*/
public interface SessionStore<K, AGG> extends StateStore, ReadOnlySessionStore<K, AGG> {
+ // TODO: javadoc; both ends are inclusive
+ default KeyValueIterator<Windowed<K>, AGG> findSessions(final Instant earliestSessionEndTime,
Review Comment:
This is related to 1) in the description, and the first open question: is this public API worth to add? Note I added it into SessionStore not ReadOnlySessionStore, to not expose via IQv1, also I've only added this function for `Instant` param type as well.
##########
streams/src/main/java/org/apache/kafka/streams/kstream/internals/KStreamSessionWindowAggregate.java:
##########
@@ -148,55 +173,184 @@ public void process(final Record<KIn, VIn> record) {
}
}
- if (mergedWindow.end() < closeTime) {
- if (context().recordMetadata().isPresent()) {
- final RecordMetadata recordMetadata = context().recordMetadata().get();
- LOG.warn(
- "Skipping record for expired window. " +
- "topic=[{}] " +
- "partition=[{}] " +
- "offset=[{}] " +
- "timestamp=[{}] " +
- "window=[{},{}] " +
- "expiration=[{}] " +
- "streamTime=[{}]",
- recordMetadata.topic(), recordMetadata.partition(), recordMetadata.offset(),
- timestamp,
- mergedWindow.start(), mergedWindow.end(),
- closeTime,
- observedStreamTime
- );
- } else {
- LOG.warn(
- "Skipping record for expired window. Topic, partition, and offset not known. " +
- "timestamp=[{}] " +
- "window=[{},{}] " +
- "expiration=[{}] " +
- "streamTime=[{}]",
- timestamp,
- mergedWindow.start(), mergedWindow.end(),
- closeTime,
- observedStreamTime
- );
- }
- droppedRecordsSensor.record();
+ if (mergedWindow.end() < windowCloseTime) {
+ logSkippedRecordForExpiredWindow(timestamp, windowCloseTime, mergedWindow);
} else {
if (!mergedWindow.equals(newSessionWindow)) {
for (final KeyValue<Windowed<KIn>, VAgg> session : merged) {
store.remove(session.key);
+
+ maybeForwardUpdate(session.key, session.value, null, record.timestamp());
+ /*
tupleForwarder.maybeForward(
record.withKey(session.key)
.withValue(new Change<>(null, session.value)));
+ */
}
}
agg = aggregator.apply(record.key(), record.value(), agg);
final Windowed<KIn> sessionKey = new Windowed<>(record.key(), mergedWindow);
store.put(sessionKey, agg);
+
+ maybeForwardUpdate(sessionKey, null, agg, record.timestamp());
+ /*
tupleForwarder.maybeForward(
record.withKey(sessionKey)
.withValue(new Change<>(agg, null)));
+ */
}
+
+ maybeForwardFinalResult(record, windowCloseTime);
+ }
+
+ private void maybeForwardUpdate(final Windowed<KIn> windowedkey,
+ final VAgg oldAgg,
+ final VAgg newAgg,
+ final long oldTimestamp) {
+ if (emitStrategy.type() == EmitStrategy.StrategyType.ON_WINDOW_CLOSE) {
+ return;
+ }
+
+ // Update the sent record timestamp to the window end time if possible
+ final long newTimestamp = windowedkey.key() != null ? windowedkey.window().end() : oldTimestamp;
+
+ tupleForwarder.maybeForward(new Record<>(windowedkey, new Change<>(newAgg, sendOldValues ? oldAgg : null), newTimestamp));
+ }
+
+ // TODO: consolidate SessionWindow with TimeWindow to merge common functions
Review Comment:
I realize that our SessionWindow and TimeWindow, and even SlidingWindow caused many code duplications (e.g. here) where we can just consolidate into the same class, with boolean flags indicating if the start/end are inclusive or exclusive, with that we can further reduce code duplication. Will file a JIRA for it.
##########
streams/src/main/java/org/apache/kafka/streams/kstream/internals/TimestampedTupleForwarder.java:
##########
@@ -38,7 +39,7 @@
@SuppressWarnings({"unchecked", "rawtypes"})
TimestampedTupleForwarder(final StateStore store,
final ProcessorContext<K, Change<V>> context,
- final TimestampedCacheFlushListener<K, V> flushListener,
+ final CacheFlushListener<K, ?> flushListener,
Review Comment:
This is 3) in the description: as we can use the base class, we then would not need the duplicated TupleFowarder any more.
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/InMemorySessionStore.java:
##########
@@ -202,25 +205,43 @@ public void remove(final Windowed<Bytes> sessionKey) {
@Override
public byte[] fetchSession(final Bytes key,
- final long earliestSessionEndTime,
- final long latestSessionStartTime) {
+ final long sessionStartTime,
Review Comment:
This is a minor fix on the param names: the old ones are simply wrong and misleading.
##########
streams/src/main/java/org/apache/kafka/streams/kstream/internals/KStreamSessionWindowAggregate.java:
##########
@@ -148,55 +173,184 @@ public void process(final Record<KIn, VIn> record) {
}
}
- if (mergedWindow.end() < closeTime) {
- if (context().recordMetadata().isPresent()) {
- final RecordMetadata recordMetadata = context().recordMetadata().get();
- LOG.warn(
- "Skipping record for expired window. " +
- "topic=[{}] " +
- "partition=[{}] " +
- "offset=[{}] " +
- "timestamp=[{}] " +
- "window=[{},{}] " +
- "expiration=[{}] " +
- "streamTime=[{}]",
- recordMetadata.topic(), recordMetadata.partition(), recordMetadata.offset(),
- timestamp,
- mergedWindow.start(), mergedWindow.end(),
- closeTime,
- observedStreamTime
- );
- } else {
- LOG.warn(
- "Skipping record for expired window. Topic, partition, and offset not known. " +
- "timestamp=[{}] " +
- "window=[{},{}] " +
- "expiration=[{}] " +
- "streamTime=[{}]",
- timestamp,
- mergedWindow.start(), mergedWindow.end(),
- closeTime,
- observedStreamTime
- );
- }
- droppedRecordsSensor.record();
+ if (mergedWindow.end() < windowCloseTime) {
+ logSkippedRecordForExpiredWindow(timestamp, windowCloseTime, mergedWindow);
} else {
if (!mergedWindow.equals(newSessionWindow)) {
for (final KeyValue<Windowed<KIn>, VAgg> session : merged) {
store.remove(session.key);
+
+ maybeForwardUpdate(session.key, session.value, null, record.timestamp());
+ /*
tupleForwarder.maybeForward(
record.withKey(session.key)
.withValue(new Change<>(null, session.value)));
+ */
}
}
agg = aggregator.apply(record.key(), record.value(), agg);
final Windowed<KIn> sessionKey = new Windowed<>(record.key(), mergedWindow);
store.put(sessionKey, agg);
+
+ maybeForwardUpdate(sessionKey, null, agg, record.timestamp());
+ /*
Review Comment:
Will remove commented out code when removing WIP, ditto elsewhere.
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/SegmentedBytesStore.java:
##########
@@ -91,8 +91,8 @@ public interface SegmentedBytesStore extends StateStore {
/**
* Gets all the key-value pairs that belong to the windows within in the given time range.
*
- * @param from the beginning of the time slot from which to search
- * @param to the end of the time slot from which to search
+ * @param from the beginning of the time slot from which to search (inclusive)
Review Comment:
Minor javadoc improvement to remind developers.
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/RocksDBTimeOrderedSessionStore.java:
##########
@@ -61,6 +65,18 @@ public <R> QueryResult<R> query(final Query<R> query,
);
}
+ @Override
+ public KeyValueIterator<Windowed<Bytes>, byte[]> findSessions(final Instant earliestSessionEndTime,
+ final Instant latestSessionEndTime) {
+ final long earliestEndTime = ApiUtils.validateMillisecondInstant(earliestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(earliestSessionEndTime, "earliestSessionEndTime"));
+ final long latestEndTime = ApiUtils.validateMillisecondInstant(latestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(latestSessionEndTime, "latestSessionEndTime"));
+
+ final KeyValueIterator<Bytes, byte[]> bytesIterator = wrapped().fetchAll(earliestEndTime, latestEndTime);
Review Comment:
This is the second open question: with the current prefixed (base, i.e. time-first) session key schema, this fetchAll would be effectively searching for `[earliestEnd, INF]` because of this logic: https://github.com/apache/kafka/blob/trunk/streams/src/main/java/org/apache/kafka/streams/state/internals/PrefixedSessionKeySchemas.java#L46
This is because we translate the range query without key inside `AbstractRocksDBTimeOrderedSegmentedBytesStore` by using the `lower/upperRange` instead of `lower/upperRangeFixedSize): https://github.com/apache/kafka/blob/trunk/streams/src/main/java/org/apache/kafka/streams/state/internals/AbstractRocksDBTimeOrderedSegmentedBytesStore.java#L241-L242
I cannot remember why we need to do this. @lihaosky @mjsax do you remember why?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mjsax commented on a diff in pull request #12204: [9/N WIP][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
mjsax commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r898411852
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/RocksDBTimeOrderedSessionStore.java:
##########
@@ -61,6 +65,18 @@ public <R> QueryResult<R> query(final Query<R> query,
);
}
+ @Override
+ public KeyValueIterator<Windowed<Bytes>, byte[]> findSessions(final Instant earliestSessionEndTime,
+ final Instant latestSessionEndTime) {
+ final long earliestEndTime = ApiUtils.validateMillisecondInstant(earliestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(earliestSessionEndTime, "earliestSessionEndTime"));
+ final long latestEndTime = ApiUtils.validateMillisecondInstant(latestSessionEndTime,
+ prepareMillisCheckFailMsgPrefix(latestSessionEndTime, "latestSessionEndTime"));
+
+ final KeyValueIterator<Bytes, byte[]> bytesIterator = wrapped().fetchAll(earliestEndTime, latestEndTime);
Review Comment:
If I read the code correctly, what `fetchAll()` does is correct: from my understanding, that fetchAll() is implement to find "overlapping sessions" given a lower and upper bound -- the lower bound must be smaller and session end and the upper bound must be smaller than session start to find an overlap. Because the upper bound compares to session start,, and we use the "base" we need to search the full "data/base part" of the store.
I guess the issue is, that you actually cannot use `fetchAll()` at all for our purpose here? Passing in `lastEndTime` does not work (does it) as it would be used to compare to session start-times, but we want to do a comparison to session end time. -- Thus, I think the right solution is, to actually also add the new `findSessions()` to the internal `SegmentedStore` and implement a proper iterator there?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] guozhangwang commented on a diff in pull request #12204: [9/N][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
guozhangwang commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r907965067
##########
streams/src/main/java/org/apache/kafka/streams/kstream/internals/KStreamSessionWindowAggregate.java:
##########
@@ -148,55 +173,182 @@ public void process(final Record<KIn, VIn> record) {
}
}
- if (mergedWindow.end() < closeTime) {
- if (context().recordMetadata().isPresent()) {
- final RecordMetadata recordMetadata = context().recordMetadata().get();
- LOG.warn(
- "Skipping record for expired window. " +
- "topic=[{}] " +
- "partition=[{}] " +
- "offset=[{}] " +
- "timestamp=[{}] " +
- "window=[{},{}] " +
- "expiration=[{}] " +
- "streamTime=[{}]",
- recordMetadata.topic(), recordMetadata.partition(), recordMetadata.offset(),
- timestamp,
- mergedWindow.start(), mergedWindow.end(),
- closeTime,
- observedStreamTime
- );
- } else {
- LOG.warn(
- "Skipping record for expired window. Topic, partition, and offset not known. " +
- "timestamp=[{}] " +
- "window=[{},{}] " +
- "expiration=[{}] " +
- "streamTime=[{}]",
- timestamp,
- mergedWindow.start(), mergedWindow.end(),
- closeTime,
- observedStreamTime
- );
- }
- droppedRecordsSensor.record();
+ if (mergedWindow.end() < windowCloseTime) {
+ logSkippedRecordForExpiredWindow(timestamp, windowCloseTime, mergedWindow);
} else {
if (!mergedWindow.equals(newSessionWindow)) {
for (final KeyValue<Windowed<KIn>, VAgg> session : merged) {
store.remove(session.key);
+
+ maybeForwardUpdate(session.key, session.value, null);
+ /*
tupleForwarder.maybeForward(
record.withKey(session.key)
.withValue(new Change<>(null, session.value)));
+ */
}
}
agg = aggregator.apply(record.key(), record.value(), agg);
final Windowed<KIn> sessionKey = new Windowed<>(record.key(), mergedWindow);
store.put(sessionKey, agg);
+
+ maybeForwardUpdate(sessionKey, null, agg);
+ /*
tupleForwarder.maybeForward(
record.withKey(sessionKey)
.withValue(new Change<>(agg, null)));
+ */
+ }
+
+ maybeForwardFinalResult(record, windowCloseTime);
+ }
+
+ private void maybeForwardUpdate(final Windowed<KIn> windowedkey,
+ final VAgg oldAgg,
+ final VAgg newAgg) {
+ if (emitStrategy.type() == EmitStrategy.StrategyType.ON_WINDOW_CLOSE) {
+ return;
+ }
+
+ // Update the sent record timestamp to the window end time if possible
+ final long newTimestamp = windowedkey.window().end();
+ tupleForwarder.maybeForward(new Record<>(windowedkey, new Change<>(newAgg, sendOldValues ? oldAgg : null), newTimestamp));
+ }
+
+ // TODO: consolidate SessionWindow with TimeWindow to merge common functions
+ private void maybeForwardFinalResult(final Record<KIn, VIn> record, final long windowCloseTime) {
+ if (shouldEmitFinal(windowCloseTime)) {
+ final long emitRangeUpperBound = emitRangeUpperBound(windowCloseTime);
+
+ // if the upper bound is smaller than 0, then there's no window closed ever;
+ // and we can skip range fetching
+ if (emitRangeUpperBound >= 0) {
+ final long emitRangeLowerBound = emitRangeLowerBound();
+
+ if (shouldRangeFetch(emitRangeLowerBound, emitRangeUpperBound)) {
+ fetchAndEmit(record, windowCloseTime, emitRangeLowerBound, emitRangeUpperBound);
+ }
+ }
+ }
+ }
+
+ private boolean shouldEmitFinal(final long windowCloseTime) {
+ if (emitStrategy.type() != EmitStrategy.StrategyType.ON_WINDOW_CLOSE) {
+ return false;
+ }
+
+ final long now = internalProcessorContext.currentSystemTimeMs();
+ // Throttle emit frequency
+ if (now < timeTracker.nextTimeToEmit) {
+ return false;
+ }
+
+ // Schedule next emit time based on now to avoid the case that if system time jumps a lot,
+ // this can be triggered every time
+ timeTracker.nextTimeToEmit = now;
+ timeTracker.advanceNextTimeToEmit();
+
+ // Only EMIT if the window close time does progress
+ return lastEmitWindowCloseTime == ConsumerRecord.NO_TIMESTAMP || lastEmitWindowCloseTime < windowCloseTime;
+ }
+
+ private long emitRangeLowerBound() {
+ return lastEmitWindowCloseTime == ConsumerRecord.NO_TIMESTAMP ? 0L : Math.max(0L, lastEmitWindowCloseTime);
Review Comment:
Ack.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] guozhangwang commented on pull request #12204: [9/N][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
guozhangwang commented on PR #12204:
URL: https://github.com/apache/kafka/pull/12204#issuecomment-1168138944
Thanks @mjsax , I've addressed your comment, and also added the test coverage. While adding tests I noticed a bug in the code and fixed it (see my comment above).
Could you please take another look?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mjsax commented on a diff in pull request #12204: [9/N][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
mjsax commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r907876120
##########
streams/src/main/java/org/apache/kafka/streams/kstream/internals/KStreamSessionWindowAggregate.java:
##########
@@ -148,55 +173,182 @@ public void process(final Record<KIn, VIn> record) {
}
}
- if (mergedWindow.end() < closeTime) {
- if (context().recordMetadata().isPresent()) {
- final RecordMetadata recordMetadata = context().recordMetadata().get();
- LOG.warn(
- "Skipping record for expired window. " +
- "topic=[{}] " +
- "partition=[{}] " +
- "offset=[{}] " +
- "timestamp=[{}] " +
- "window=[{},{}] " +
- "expiration=[{}] " +
- "streamTime=[{}]",
- recordMetadata.topic(), recordMetadata.partition(), recordMetadata.offset(),
- timestamp,
- mergedWindow.start(), mergedWindow.end(),
- closeTime,
- observedStreamTime
- );
- } else {
- LOG.warn(
- "Skipping record for expired window. Topic, partition, and offset not known. " +
- "timestamp=[{}] " +
- "window=[{},{}] " +
- "expiration=[{}] " +
- "streamTime=[{}]",
- timestamp,
- mergedWindow.start(), mergedWindow.end(),
- closeTime,
- observedStreamTime
- );
- }
- droppedRecordsSensor.record();
+ if (mergedWindow.end() < windowCloseTime) {
+ logSkippedRecordForExpiredWindow(timestamp, windowCloseTime, mergedWindow);
} else {
if (!mergedWindow.equals(newSessionWindow)) {
for (final KeyValue<Windowed<KIn>, VAgg> session : merged) {
store.remove(session.key);
+
+ maybeForwardUpdate(session.key, session.value, null);
+ /*
tupleForwarder.maybeForward(
record.withKey(session.key)
.withValue(new Change<>(null, session.value)));
+ */
}
}
agg = aggregator.apply(record.key(), record.value(), agg);
final Windowed<KIn> sessionKey = new Windowed<>(record.key(), mergedWindow);
store.put(sessionKey, agg);
+
+ maybeForwardUpdate(sessionKey, null, agg);
+ /*
tupleForwarder.maybeForward(
record.withKey(sessionKey)
.withValue(new Change<>(agg, null)));
+ */
+ }
+
+ maybeForwardFinalResult(record, windowCloseTime);
+ }
+
+ private void maybeForwardUpdate(final Windowed<KIn> windowedkey,
+ final VAgg oldAgg,
+ final VAgg newAgg) {
+ if (emitStrategy.type() == EmitStrategy.StrategyType.ON_WINDOW_CLOSE) {
+ return;
+ }
+
+ // Update the sent record timestamp to the window end time if possible
+ final long newTimestamp = windowedkey.window().end();
+ tupleForwarder.maybeForward(new Record<>(windowedkey, new Change<>(newAgg, sendOldValues ? oldAgg : null), newTimestamp));
+ }
+
+ // TODO: consolidate SessionWindow with TimeWindow to merge common functions
+ private void maybeForwardFinalResult(final Record<KIn, VIn> record, final long windowCloseTime) {
+ if (shouldEmitFinal(windowCloseTime)) {
+ final long emitRangeUpperBound = emitRangeUpperBound(windowCloseTime);
+
+ // if the upper bound is smaller than 0, then there's no window closed ever;
+ // and we can skip range fetching
+ if (emitRangeUpperBound >= 0) {
+ final long emitRangeLowerBound = emitRangeLowerBound();
+
+ if (shouldRangeFetch(emitRangeLowerBound, emitRangeUpperBound)) {
+ fetchAndEmit(record, windowCloseTime, emitRangeLowerBound, emitRangeUpperBound);
+ }
+ }
+ }
+ }
+
+ private boolean shouldEmitFinal(final long windowCloseTime) {
+ if (emitStrategy.type() != EmitStrategy.StrategyType.ON_WINDOW_CLOSE) {
+ return false;
+ }
+
+ final long now = internalProcessorContext.currentSystemTimeMs();
+ // Throttle emit frequency
+ if (now < timeTracker.nextTimeToEmit) {
+ return false;
+ }
+
+ // Schedule next emit time based on now to avoid the case that if system time jumps a lot,
+ // this can be triggered every time
+ timeTracker.nextTimeToEmit = now;
+ timeTracker.advanceNextTimeToEmit();
+
+ // Only EMIT if the window close time does progress
+ return lastEmitWindowCloseTime == ConsumerRecord.NO_TIMESTAMP || lastEmitWindowCloseTime < windowCloseTime;
+ }
+
+ private long emitRangeLowerBound() {
+ return lastEmitWindowCloseTime == ConsumerRecord.NO_TIMESTAMP ? 0L : Math.max(0L, lastEmitWindowCloseTime);
+ }
+
+ private long emitRangeUpperBound(final long windowCloseTime) {
+ // Session window's start and end timestamps are inclusive, so
+ // we should minus 1 for the inclusive closed window-end upper bound
+ return windowCloseTime - 1;
+ }
+
+ private boolean shouldRangeFetch(final long emitRangeLowerBound, final long emitRangeUpperBound) {
+ return emitRangeUpperBound > emitRangeLowerBound;
+ }
+
+ private void fetchAndEmit(final Record<KIn, VIn> record,
+ final long windowCloseTime,
+ final long emitRangeLowerBound,
+ final long emitRangeUpperBound) {
+ final long startMs = time.milliseconds();
Review Comment:
Should we use milliseconds or nanoseconds (I am always unsure)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mjsax commented on a diff in pull request #12204: [9/N][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
mjsax commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r907879361
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/PrefixedSessionKeySchemas.java:
##########
@@ -204,7 +203,8 @@ public static void writeBinary(final ByteBuffer buf,
final long endTime) {
buf.putLong(endTime);
buf.putLong(startTime);
- buf.put(key.get());
+ if (key != null)
Review Comment:
Can `key` ever be `null` here? (nit: add `{}` to block)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mjsax commented on a diff in pull request #12204: [9/N][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
mjsax commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r908926903
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/SessionStoreBuilder.java:
##########
@@ -52,6 +53,16 @@ private SessionStore<Bytes, byte[]> maybeWrapCaching(final SessionStore<Bytes, b
if (!enableCaching) {
return inner;
}
+
+ if (!inner.persistent()) {
Review Comment:
If we strip the caching, this applies to eager emitting, right? -- So it would be a behavioral change? Do we want to piggy-back such a change into this KIP? Sounds "risky"?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] guozhangwang commented on a diff in pull request #12204: [9/N][Emit final] Emit final for session window aggregations
Posted by GitBox <gi...@apache.org>.
guozhangwang commented on code in PR #12204:
URL: https://github.com/apache/kafka/pull/12204#discussion_r909084851
##########
streams/src/main/java/org/apache/kafka/streams/state/internals/SessionStoreBuilder.java:
##########
@@ -52,6 +53,16 @@ private SessionStore<Bytes, byte[]> maybeWrapCaching(final SessionStore<Bytes, b
if (!enableCaching) {
return inner;
}
+
+ if (!inner.persistent()) {
Review Comment:
Sounds good, I will move this logic into the earlier stage during the topology building phase for the moment. Also cc @lihaosky who would do similar things for sliding windows.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org