Skip to content

ref(streams): Use abstract Producer with KafkaConsumerWithCommitLog - #772

Closed
tkaemming wants to merge 7 commits into
masterfrom
commit-log-producer
Closed

tkaemming wants to merge 7 commits into
masterfrom
commit-log-producer

Conversation

@tkaemming

Copy link
Copy Markdown
Contributor

This reduces the coupling with the Confluent Kafka client slightly, and removes one use of the FakeConfluentKafkaProducer. This also improves the logging for the KafkaProducer.

@tkaemming
tkaemming requested a review from a team February 10, 2020 22:47
while remaining:
logger.debug("Still waiting for %s in-flight messages...", remaining)
else:
logger.debug("%s in-flight messages remaining, exiting...", remaining)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

(snuba) ted@veneno % SNUBA_SETTINGS=~/Desktop/snuba_settings.py snuba consumer --log-level debug
2020-02-10 14:44:45,959 700002125000 DEBUG    snuba.utils.streams.kafka: Starting worker thread for <snuba.utils.streams.kafka.KafkaProducer object at 0x10811c3c8>...
2020-02-10 14:44:45,960 7fffb760b3c0 DEBUG    snuba.utils.streams.batching: Starting
2020-02-10 14:44:51,989 7fffb760b3c0 INFO     snuba.utils.streams.batching: New partitions assigned: {Partition(topic=Topic(name='events'), index=0): 14716}
2020-02-10 14:44:54,021 7fffb760b3c0 INFO     snuba.utils.streams.batching: Flushing 69 items (from {Partition(topic=Topic(name='events'), index=0): Offsets(lo=14716, hi=14784)}): forced:False size:False time:True
2020-02-10 14:44:54,021 7fffb760b3c0 DEBUG    snuba.utils.streams.batching: Flushing batch via worker
2020-02-10 14:44:54,022 7fffb760b3c0 DEBUG    urllib3.connectionpool: Starting new HTTP connection (1): localhost:8123
2020-02-10 14:44:54,094 7fffb760b3c0 DEBUG    urllib3.connectionpool: http://localhost:8123 "POST /?load_balancing=in_order&insert_distributed_sync=1&query=INSERT+INTO+sentry_local+FORMAT+JSONEachRow HTTP/1.1" 200 None
2020-02-10 14:44:54,095 7fffb760b3c0 INFO     snuba.utils.streams.batching: Worker flush took 73ms
2020-02-10 14:44:54,095 7fffb760b3c0 DEBUG    snuba.utils.streams.batching: Committing offsets
2020-02-10 14:44:54,105 7fffb760b3c0 DEBUG    snuba.utils.streams.batching: Committed offsets: {Partition(topic=Topic(name='events'), index=0): 14785}
2020-02-10 14:44:54,105 7fffb760b3c0 DEBUG    snuba.utils.streams.batching: Offset commit took 10ms
2020-02-10 14:44:54,106 7fffb760b3c0 DEBUG    snuba.utils.streams.batching: Resetting in-memory batch
2020-02-10 14:44:54,985 700002125000 DEBUG    snuba.utils.streams.kafka: Produced commit record: Message(partition=Partition(topic=Topic(name='snuba-commit-log'), index=0), offset=26, payload=Commit(group='snuba-consumers', partition=Partition(topic=Topic(name='events'), index=0), offset=14785), timestamp=datetime.datetime(2020, 2, 10, 22, 44, 54, 105000))
^C
2020-02-10 14:45:04,137 7fffb760b3c0 DEBUG    snuba.utils.streams.batching: Shutdown signalled
2020-02-10 14:45:04,137 7fffb760b3c0 DEBUG    snuba.utils.streams.batching: Stopping
2020-02-10 14:45:04,137 7fffb760b3c0 DEBUG    snuba.utils.streams.batching: Resetting in-memory batch
2020-02-10 14:45:04,137 7fffb760b3c0 DEBUG    snuba.utils.streams.batching: Stopping consumer
2020-02-10 14:45:04,137 7fffb760b3c0 INFO     snuba.utils.streams.batching: Partitions revoked: [Partition(topic=Topic(name='events'), index=0)]
2020-02-10 14:45:04,202 700002125000 DEBUG    snuba.utils.streams.kafka: Shutdown request received, waiting for 0 in-flight messages to be delivered...
2020-02-10 14:45:04,203 700002125000 DEBUG    snuba.utils.streams.kafka: 0 in-flight messages remaining, exiting...
2020-02-10 14:45:04,203 7fffb760b3c0 DEBUG    snuba.utils.streams.batching: Stopped

Comment on lines 661 to +669
def __commit_message_delivery_callback(
self, error: Optional[KafkaError], message: ConfluentMessage
self, commit: Commit, future: Future[Commit]
) -> None:
if error is not None:
raise Exception(error.str())
try:
message = future.result()
except Exception:
logger.warning("Failed to produce commit record: %r", commit, exc_info=True)
else:
logger.debug("Produced commit record: %r", message)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Slight behavior change here, this callback is now fired in the producer worker thread (see the logs below, the field after the timestamp is the thread ID) so a produce failure here will not cause this consumer to fail-stop. I think that should be fine — this is logged, and consumer lag on any consumers that depend on the commit log should be monitored, and whenever the consumer is able to report its offsets at a later time, progress will resume — but it is different.

messages: int = self.__producer.flush(*[timeout] if timeout is not None else [])
if messages > 0:
raise TimeoutError(f"{messages} commit log messages pending delivery")
self.__producer.close().result(timeout)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It drives me a bit crazy that this consumer is responsible for closing the producer. It seems as it should be the responsibility of the caller who provides it to the constructor, but making that change is more invasive than I'd like to get into now as it affects the stateful/snapshot consumer.

@tkaemming tkaemming Feb 10, 2020 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Just remembered that the reason this drives me a bit crazy: this is because the consumer would now require that this method is called to ensure a clean shutdown — including in exceptional cases, such as #762. So, this will not work any cases where ConsumerBuilder.build_base_consumer is called without guaranteeing the returned consumer instance is closed, because the interpreter may hang waiting for a thread that does not know it should be stopping.

The possible approaches here are:

  1. ensure the consumer is closed (this is relatively straightforward for the consumer command, less so for the stateful consumer.)
  2. register an atexit handler to ensure that thread shutdown is requested if the main thread exits, similar to the approach in fix(kafka): Flush producers on exit sentry#15934
  3. run the producer in a daemon thread and lose in-flight messages on exit without notice or warning
  4. hope no errors ever occur and that the close method is always called by the signal handler and that everything is fine it is always fine nothing to see here
  5. abandon ship

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Still going to need to figure this one out before it's ready.

@tkaemming

tkaemming commented Feb 10, 2020 •

Copy link
Copy Markdown
Contributor Author

My end goals for the consumer/commit log behavior, in several steps beyond this change itself:

  1. The Consumer API is updated to use asynchronous commit
  2. The production of commit records is triggered by a commit callback instead of waiting on the synchronous commit
  3. Producing to the commit log no longer becomes coupled to the KafkaConsumer (and does not require this concrete subclass and calling super)
  4. timeout can be removed from the Consumer.close method signature

@fpacifici fpacifici left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Seems ok, just a few clarifications

ConsumerWorker(
self.dataset,
producer=self.producer,
producer=ConfluentKafkaProducer(self.__kafka_producer_configuration),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reason for not using KafkaProducer here ? Is it because we do not have a codec for the ConsumerWorker ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yeah, this would either need to be typed as Producer[KafkaPayload] (not ideal, but not that bad, basically what we're already doing today) or Producer[Replacement] (more ideal, but also more work to do correctly.)

Comment on lines -661 to -663
def poll(self, timeout: Optional[float] = None) -> Optional[Message[TPayload]]:
self.__producer.poll(0.0)
return super().poll(timeout)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

was this not used ? Otherwise is it safe not to poll on the __producer anymore ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The producer worker thread continuously calls poll to fire callbacks so it no longer needs to be on the main thread.

try:
message = future.result()
except Exception:
logger.warning("Failed to produce commit record: %r", commit, exc_info=True)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

It is still a pretty serious issue, I think this should be logged as error.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

My thinking here: since most of the time the ERROR log level is used (via logger.exception) to log an exception that had a major impact on the code path that it was logged from since the stack was unwound, WARNING made more sense here since this exception is handled and is already off the execution path/off of the stack of the code that called it. Basically, this failing is "safe" (at least from the caller's perspective since it doesn't crash) but might cause undesirable side effects for downstream systems — which should be monitored there and the severity is sort of relative on that system's priorities.

I don't have a super strong opinion about this, so can change it if you don't agree with that perspective.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nah, don't worry not very strong opinion either. As long as we do not ignore these errors it is fine.

@tkaemming tkaemming added the WIP Work in progress label Feb 12, 2020
@tkaemming
tkaemming marked this pull request as draft April 14, 2020 16:21
@volokluev

Copy link
Copy Markdown
Member

Closing due to age

@volokluev volokluev closed this Dec 21, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

WIP Work in progress

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants