Full topic names on the public API
The 1.x client derived short topic names from the payload class and let the broker default the tenant, so publish and
subscribe could end up on different topics as soon as an environment suffix or a domain was involved. 0.3 adds the
String topic overloads with the full name and keeps the Class overloads only for compatibility. Name resolution
happens once, in klok-common, and the client never guesses.
Properties are the contract, not the payload
Correlation, invocation, task and routing context travel as Pulsar properties with the klok-* names, and the
CloudEvents attributes as ce-* properties. The payload stays the pure datamodel, so a schema never has to change to
add an id, and a consumer in any language reads the context without deserialising the body.
Three correlation ids, and what the client does with each
From 0.4 a chain is followed at three widths, global, platform and service, by the rules of the klok-common page Log
Fields And Correlation. The
clients split the work along what each one owns:
- The Java client carries the ids, it does not make them. A plain Java publisher gives its ids in the properties (or
the
correlationId argument); the Quarkus extension's invocation context does that for every route. Creating a global
id in the client was weighed: the client cannot tell a new business call from a caller that forgot to pass one, and an
id it made up would split one chain into two that nobody can join afterwards. A message without a global id therefore
carries none and has no key, as before.
- The Python and TypeScript clients own the invocation, so they create what is missing. A handler, an
invocation()
or a publish outside a handler has no extension behind it, so the client creates a global id (source generated), a
platform id and a service id where the input brought none, as it already created the correlation id of a new chain
before 0.4.
- The service id never leaves the process. It groups what one service does with one input, so it is a log field and an
MDC key only; every client strips it, and
klok-corr-global-source, from what it publishes.
- The message key is the global id. One business call stays on one partition and one Key_Shared consumer, which is
what the old correlation id key did. A reply to an addressed request keeps its reply subscription key, which the
broker's entry filter needs.
- The transition is in the client, not in every route. A consumer reads
klok-correlation-id (then klokChainId)
when klok-corr-global is absent, and uses it as the platform id too, and a publisher writes the global id as
klok-correlation-id as well, so chains stay whole across services built before and after the change. Writing
klok-correlation-id stops when the fleet no longer publishes KlokLogEventV4
(klok-common#12).
- The client's own properties are its own.
klok-instance and klok-sent-time used to give way to a caller's value,
so a service that passed on the properties of a consumed message republished them under the upstream's name and time.
They are always the client's now; klok-body-type stays overridable, because a bytes sender may know its encoding
better than the schema.
KlokLogEventV6, vendored like V4
The Python and TypeScript clients publish their service log as KlokLogEventV6 from 0.4, with the field names of the
klok-common page, and readLogEvent / read_log_event read V6 and V4 into one entry with the V6 names, so a reader
such as klok.dev's Run → Logs follows old and new services through the transition with one code path.
The V6 classes are the packages the datamodel pipeline of klok/datamodel/common/klok-log-event-v6 published
(1.0.0-build.261116125437), copied unchanged into vendor/kloklogevent-v6/ and _kloklogevent_v6/, as V4 is. A
dependency was weighed: the TypeScript client is installed from npmjs.org and the Python client from places that do not
reach the GitLab registry where datamodel packages live, so a dependency would break every install outside Klok's
network. The copy carries the schema string Java registers byte for byte, and a test keeps the two copies identical.
Legacy names for one release
The 0.1 Python and TypeScript clients and a few 1.x services read klokChainId and friends. Writing both name sets for
one release avoids a coordinated big bang; the legacy names disappear with 0.4. The Python client 0.3 already follows
the contract's rule for bindings and uses only the klok-* names.
Python registers the schema string Java registers
A Python producer and a Java consumer share a topic only if they register the same Avro schema, and Pulsar's Python
AvroSchema re-serialises the JSON it is given, which changes the bytes and so the schema identity. The Python client
therefore registers the KLOK_AVRO_SCHEMA string of the generated datamodel class unchanged, and the Gradle plugin
generates that string by asking Pulsar for the schema of the Java class. Measured on a live broker: the admin API
returns the Python-registered schema byte for byte, and Java 0.3.2 consumers and producers share the topic with it.
Service logging is part of the client, not a library next to it
A Klok log entry needs exactly what the client already owns: the invocation boundary (one handler call), the context ids
derived from the message, the broker connection and the Avro encoding. A separate library would need hooks into every
dispatch and a second connection, and a worker could forget to call it; built in, every subscription logs its
invocations with no code, as a Java route does. It follows the extension's rules (serviceLogging of the wire contract)
rather than a vocabulary of its own: the log receivers derive the chain status from START, PROGRESS, FINISHED and
FAILED and their numeric values, so any other word would leave Python invocations uncounted. The switch is on the
client (KLOK_LOGEVENTS_ENABLED) and per subscription, since a publish on its own is no invocation;
client.invocation() makes a script one explicitly.
Retries inside the invocation, as in Java
The 0.3 draft retried by negatively acknowledging and letting the broker redeliver. That makes every redelivery a new
invocation with its own START, so a message that succeeds on the third delivery would leave two unfinished invocations
and keep its chain IN_PROGRESS forever, and on an Exclusive subscription the redelivery also breaks the order. The
client now retries inside the invocation with the Java KlokRetryPolicy defaults and ends with FINISHED, or FAILED
and a disposition, like a Java route.
Workers are threads on one consumer
Concurrency in the Python client is concurrency threads receiving from one consumer, as the Java client's receive
loops, rather than a listener callback, which Pulsar's Python client runs one message at a time per consumer. Workers
are mostly waiting on I/O (an LLM, a web service), where threads are enough; the acknowledgement of each message stays
on the thread that received it.
TypeScript follows the Python client, adapted to Node
The TypeScript client 0.3 is the Python client's design translated, not a new one: the same modules (naming, properties,
CloudEvents, configuration, payloads, subscriptions, service logging, request/reply), the same outcomes and retry rules,
and the same wire contract fixtures. Where Node differs, the client follows Node:
AsyncLocalStorage is the context variable. Python keeps the running handler's context and invocation in
ContextVars; Node's equivalent follows promises and callbacks, so concurrent handlers in one process never see each
other's context, and a publish or client.log call deep inside a handler continues the right chain.
- Receive loops await
receive() without a timeout. Concurrency is n loops on one consumer, as in Java and Python.
The Node Pulsar client serves receive() asynchronously in its C++ client, while receive(timeout) (and a reader's
readNext()) runs as an AsyncWorker that holds one of libuv's threads, four by default and shared with file system,
DNS and crypto work, for as long as it waits. Four idle loops would stall a web backend. Closing the consumer fails the
pending receives, which is how the loops end.
- Reply topics are read by a non-durable reader. The Node
ConsumerConfig has no subscription mode, so a consumer
could only remove its subscription on a clean close, which a crash skips. A Pulsar reader is a non-durable subscription
that disappears with its connection, which is what
#10 asks of every client (see Addressed
replies on non-durable reply subscriptions); its listener runs on the C++ client's listener thread and reaches
JavaScript through a thread-safe function, again without a libuv thread.
- No writer schema lookup. The Node client does not expose the schema version of a received message, so the client
decodes with its package's schema and dead letters what does not fit, instead of guessing the version through the admin
API (see "Receiving another version of a schema" on the TypeScript page).
- One package for ES modules and CommonJS.
tsc builds src/ twice, each tree with a package.json that sets its
module type and maps the vendored KlokLogEventV6 and KlokLogEventV4 (#kloklogevent-v6, #kloklogevent-v4) to
copies inside the tree, since Node resolves subpath imports from the nearest package.json. The Klok Root CA is
embedded and written to a private temporary file, because the Pulsar client only takes a path and a file inside the
package is not found reliably from both trees or from a bundle. The native module is loaded on first use, so importing
the package loads no native code.
- One CA file for the broker and the issuer. The native Pulsar client under the Python and TypeScript clients takes
one CA file and uses it for the broker and for its OAuth2 requests to the issuer (the well-known configuration and the
token). The broker's certificate chains to the Klok Root CA, the issuer's (
auth.ipaas.se) to a public root, so a file
with the Klok Root CA alone failed every login with Error Code 60 ... unable to get local issuer certificate and
AuthenticationError; klok.dev's Run → Logs met it on 2026-10-12. Both clients therefore write a file with the broker's
CA (bundled or configured) first and the public roots after it: certifi's in Python, the certificates Node trusts in
TypeScript. The broker is still checked against its host name, and a configured CA file needs nothing added. The Java
client is not affected: its OAuth2 request uses the JVM's trust store.
- Message ids are written as Java writes them (
ledger:entry:partition[:batchIndex]), since they end up in
klok-original-message-id and klok.quarantine-ref next to ids written by Java routes.
- The logger is an interface. Node has no standard logging API; the client writes to any object with
debug/info/warn/error(message, fields), the console by default, and the service log lines carry their klok.*
keys as fields for a structured logger.
One Pulsar client per connection
Each KlokBrokerClient used to open its own PulsarClient, so a service with many routes held many connections and
tokens and leaked them when a route was instantiated just to read its URI. The client manager shares one Pulsar client
per connection (service URL, OAuth2 issuer, credentials and audience, trusted CA), counted by reference; the route id
and the instance stay with each KlokBrokerClient, so a service holds one connection and one token however many routes
it runs (Configuration). Up to 0.3.8 the key was the whole
configuration, route id included. The extension creates clients lazily when a route starts.
Exclusive subscriptions and framework managed dead letters
Ordering per topic is the default expectation of an integration, so subscriptions are Exclusive unless a route opts into
Shared or Key_Shared. Pulsar's native dead letter policy needs a shared subscription, which is why the framework
republishes to <topic>_DLQ itself and keeps the native policy as an opt-in.
The client quarantines what it cannot decode
Retries and the <topic>_DLQ republish of failed invocations belong to the Quarkus extension, which knows the route's
retry policy. A message whose payload cannot be decoded never becomes an invocation, though: it fails before any handler
runs, so the extension never sees it, and redelivering it cannot help. The client therefore gives it the disposition the
contract's dead letter rules and the Python client give it, DECODE_ERROR on <topic>_DLQ, with a per subscription
switch (deadLetterUndecodable) for a consumer whose failures must not be quarantined. It is republished as raw bytes
because a producer with the payload's schema cannot send bytes that do not match it.
Concurrency is a subscription option, not a thread pool setting
Parallelism is decided where the ordering trade-off is visible: on the subscription (concurrency in
KlokSubscriptionOptions, <RouteId>.subscription.concurrency in the extension). The client runs that many receive
loops on one consumer, so every message is still received, handled and acknowledged by one loop and the acknowledgement
contract of 0.3.1 holds. A global listener pool size would only say how many loops can exist, not which subscriptions
may give up their order, so the pool is derived from the subscriptions and merely has a configurable floor
(listenerThreads).
A batch is acknowledged message by message, after the handler
Batching belongs in the client, not in a framework on top of it. An aggregator in a Camel route (the Quarkus extension's
AggregateOutgoingMessages) completes each message when it joins the batch, so its acknowledgement goes out before the
batch is written, and a crash or a failed bulk request loses the batch. subscribeBatch keeps the acknowledgement
contract of a single message: the receive loop owns every message of the batch until the handler returned, then applies
the outcome the handler gave each one. Collecting the batch in the receive loop, rather than with Pulsar's own
batchReceive, keeps the consumer the same as for a single message subscription, so a service can switch a subscription
between the two without touching the consumer's configuration.
Request/reply over topics, not a separate protocol
Synchronous calls between services use the same broker, the same properties and the same security as everything else: a
request topic, a reply topic and a reply id. A service that offers a request/reply interface can also be called
asynchronously with a callback, and a REST facade in front of it stays thin.
Addressed replies on non-durable reply subscriptions
All requesters of a request/reply pair share one response topic, ReqRes_<Req>_<Res>[_<purpose>]_Response. Each
requester reads it with a subscription of its own and pairs replies by klok-reqres-id. Two things went wrong with that
(#10):
- The Java and Python reply subscriptions were durable and never removed. Every restart of a requester left a
subscription behind that kept every reply of the pair for ever. On 2026-10-06 the two ODL response topics had 367 and
396 such subscriptions and 100 to 180 million messages of backlog, removed by hand.
- Every requester received every reply. With three live instances of a requester, each reply was delivered three times
and decoded three times, and two of the three were thrown away.
What was decided, and why:
- Non-durable, not unsubscribe on close. Unsubscribing in
close() would leave a subscription behind every time a
process is killed, runs out of memory or loses its node, which is exactly when nobody cleans up. A non-durable
subscription lives only as long as its consumer's connection, so the broker removes it however the process ends. It
loses nothing a requester needs: a reply that arrives while the requester is away has no one waiting for it. Java uses
SubscriptionMode.NonDurable; the Python and Node Pulsar clients have no non-durable consumer, so they read with a
reader, which is a non-durable subscription.
- The requester names its subscription, the replier keys the reply with it. The request carries
klok-reply-subscription, the exact name of the requester's reply subscription, and the reply gets that name as its
message key. The key is the one field of a message the broker can read without decoding anything, and it is what a
broker side filter can match against the name of the subscription it is about to deliver to. A reply topic per requester
was the alternative; it was rejected because it multiplies topics, schema registrations and grants by the number of
instances, and every replier would need to be allowed to publish on topics that come and go.
- Key-based batching for replies. The broker stores a batch as one entry and filters entries, not messages. With the
default batching a batch can hold replies to several requesters under one key; key-based batching puts only replies with
the same key in one batch.
- The broker filter is an optimisation, the client stays correct without it. The Pulsar entry filter in
klok-pulsar-entry-filter turns the key into fewer
deliveries: an entry keyed
reply-subscriber-... reaches only the subscription of that name, or a reader subscription
named <key>-reader-<random>. A broker without it, a replier that does not key, or a requester that sends no
klok-reply-subscription (an older client) only brings back the fan-out. The requester therefore still pairs replies by
klok-reqres-id, and since it reads that property before the payload, a reply that is not its own is acknowledged
without being decoded.
- A reader is addressed by its prefix. The Python and Node Pulsar libraries name a reader's subscription
<prefix>-reader-<random> and expose neither the random part nor a way to choose the whole name. Those clients
therefore use reply-subscriber-<clientId>-<uuid>, unique per client instance, as the reader's subscription role prefix
and send exactly that prefix in klok-reply-subscription; the filter accepts a subscription named by the key or by the
key followed by -reader- (the contract's readerSubscriptionInfix). A key that is a whole subscription name and a key
that is a reader's prefix cannot be confused, since both carry a client id and a uuid of their own. Every client in
every language is then addressed, and none has to guess a name.
A request is pending as long as it waits
A pending request is kept for its own reply timeout, and a reply that comes later belongs to no pending request: the
wire contract's requestReply.pendingReplyLifetime, since klok-common 0.3.6. Up to 0.3.13 the Java and the Python
clients kept every pending request 30 seconds after it was sent, whatever its timeout
(#9). A chat that took 45 seconds was answered
to a requester that waited 120 seconds, the reply found no pending request, and the requester answered its own caller
with a timeout after 120 seconds. The 30 seconds stood in the contract as pendingReplyTtlMs, which no client read; the
TypeScript client already kept each request exactly as long as its timeout, and the contract now says that.
The time is the request's own because nothing else knows how long the requester waits. A longer fixed time would only
move the cliff, and a shorter one than the timeout is the bug. The table has no size limit and no timer thread, as
before: a requester removes its request when it stops waiting, and expired entries that nobody read are swept on a later
request.
A request that never left says so
The principles of error handling say that a synchronous retry is decided case by case, short, and never runs a call
twice (Error
handling). A
requester can only keep that promise if it knows whether a failed request reached its service. A request that was sent
and got no reply in time may have run; one that never left cannot have. So a request that provably never left fails with
KlokRequestNotSentException, and every other failure stays a KlokRequestReplyException.
- A subclass, not a flag. Every caller that catches
KlokRequestReplyException keeps working, and the test reads the
same in Java (instanceof), Python (isinstance) and TypeScript (instanceof). A boolean sent would have needed a
third value for the cases below, where nobody knows.
- What counts as never sent. The client has no topic to send to, nobody could read the reply (the request is then not
sent at all, so that no request runs whose answer reaches nobody), a topic is not provisioned for the client, the
producer could not be created, or the send was refused before the message went over the connection (a full queue, a
broken connection).
- What may have left. A send that timed out: the broker may have stored the message and only its acknowledgement was
lost. A send whose producer was closed while it was pending, which the Pulsar clients fail with
AlreadyClosed: the
message may have gone over the connection before. A send on a producer that was closed before fails the same way and
cannot be told apart, so it counts as one that may have left; that only costs a retry, never a second run.
- Each client tells creation from sending. The Java client creates the producer before it sends, the Python client
does the same for a request, and the Node client says which step failed (
Failed to create producer: against Failed to send message:).
- Who uses it. The Quarkus extension retries a request/reply call only on this exception, and only for a route that
configures retries; a reply timeout is never retried
(klok-quarkus-extension#13).
One implementation, two schemas
The bytes client is a supported way to use the broker client, for services where the Avro serialization of the typed
client is unnecessary or too slow compared with their own codec. Up to 0.3.4 it was a second implementation of about
1,100 lines that had stayed on the 0.2 conventions: legacy property names only, a reply topic of its own
(<topic>-replies-<instance>) that no typed client answered, no subscription options, and receive loops without the 0.3
fixes. Deprecating it was proposed (#17) and rejected, since the high-performance path is wanted; keeping two
implementations was rejected as well, since every fix to the acknowledgement contract had to be made twice and was not.
Instead the Pulsar schema is a setting of KlokBrokerClient (Avro of the payload class by default) and of
KlokBrokerClientSync for the reply, and KlokBytesBrokerClient is KlokBrokerClientSync<byte[], byte[]> with
Schema.BYTES: no payload serialization, the same properties, options, loop and request/reply as the typed clients. The
one deliberate difference is that it leaves out the 0.2.x property duplicates, which measurably cost throughput and
serve only 0.2 readers of typed topics. KlokBrokerClientBenchmark keeps the performance claim measured rather than
assumed.
A missing topic or grant fails at once, with the fix
On klok5 topics are never created automatically (topics.provisioning in klok-common's wire contract): a topic and its
grants come from the tenant's Pulsar file in Git. Before 0.3.10 the client treated a missing topic or a refused grant
like any broker failure. A failed send became a KlokSendMessageException that the Quarkus extension turned into the
retryable BROKER_UNAVAILABLE; a failed subscribe said "Failed to subscribe"; a missing _DLQ negatively acknowledged
the message forever; and a consumer whose topic was deleted logged the same error every five seconds for as long as the
service ran. None of that can heal by itself, since only a change in Git provisions the topic, and every retry hid the
one thing a developer has to do.
So the client recognises the four Pulsar errors the contract names (TopicDoesNotExistException and NotFoundException
for a missing topic, AuthorizationException and NotAllowedException for a missing grant), whatever wraps them, and
fails at once with KlokTopicMissingException or KlokTopicAccessDeniedException. Weighed against that:
- Typed exceptions rather than a code in the message. Callers (the extension's
KlokMessagePublisher, a startup
check, a health check) decide by type and read topic, role and operation from fields; nobody parses text.
- The contract's text, rendered by klok-common. The message names the topic, the role, the klok.dev request link, the
approver and the line to add by hand. The Java, TypeScript and Python clients and the Gradle plugin render the same
templates and run the same fixture cases, so a developer or an AI agent gets one wording, wherever it failed.
- Existing exception types stay where an API declares them.
sendRequestReply declares KlokRequestReplyException,
which callers catch, so a provisioning failure there is its cause rather than a new checked type that would break their
code. KlokTopicProvisioningException.find reads it out of any chain.
- One second attempt, never a loop. A producer that Pulsar closed for good is dropped from the cache and created once
more, so a topic that was deleted and created again recovers, and one that stays missing is reported on that same call.
- A receive loop stops instead of spinning. A consumer that Pulsar failed for good never receives again, and a message
whose
_DLQ is missing can never leave the subscription. Ending the loop with the reason (receiveLoopFailure) makes
the failure visible to a health check, where an endless retry only made the log longer. The message that triggered it is
negatively acknowledged once, so nothing is lost.
Verifying consume uses a reader, not a subscription
verifyConsume has to prove two things at startup: that the topic exists, and that the role holds consume on it. It
must not leave state behind, because the contract lets the consumer create its durable subscription
(subscriptionsAutoCreate) and a check that created one would start that subscription's backlog at the time of the
check, before the service was ready, and leave it there if the service never started. The options weighed:
- A lookup (
getPartitionsForTopic) creates nothing, but the broker allows it with either grant, so a role with only
publish would pass a consume check. It is what the client uses to diagnose a failed consumer, where the grant is
already known to have been there, with metadataAutoCreationEnabled=false so that it never creates the topic.
- A consumer on the real subscription, even non-durable, would compete with a running exclusive consumer of the same
subscription (a second instance starting during a rolling deployment) and fail for the wrong reason.
- A reader is a non-durable subscription of its own (
<subscription>-verify-<8 hex>, from the latest message). The
broker authorizes it exactly as a consumer, it exists only while it is connected, and it reads nothing. It also works on
a partitioned topic. That is what verifyConsume opens and closes.
The one thing a reader cannot check is a subscription-level permission (Pulsar's grant-subscription-permission or
subscriptionAuthMode=Prefix), which Klok does not use: a Klok grant is a namespace or topic grant to the role.
verifyPublish needs no such care: the only proof of publish is a producer, a producer leaves nothing on the topic,
and the client keeps it, so the check is also the eager creation of the producer the first send would make, the _DLQ
producer included.
A lost connection is loud, and the client recovers what it can
On 2026-10-09 the request producer of klok-documentation-egress lost its broker registration after a failed
re-authentication and never got it back. The client sent on it for more than four hours, every request waited for the
send timeout, the pod stayed Running and Ready, and nothing reported anything
(#34). The client had no notion of whether a
producer was connected; it replaced one only when Pulsar had closed it. Jakob's requirement for the fix: a broken broker
connection is among the most serious failures the platform can have, so the client must retry, log every attempt loudly,
and every service without a working connection must be visible in an alert.
What was decided (see Connection health):
- A watchdog per JVM, not per producer. One thread checks every producer and consumer of every open client every 10
seconds through Pulsar's own
isConnected() and getLastDisconnectedTimestamp(). A Pulsar listener for connection
events does not exist in the 5.0 client, and a check per send would see nothing on an idle service.
- Quiet for 30 seconds, then an ERROR on every check. A broker restart or a topic unload reconnects within a second,
and logging those would teach people to ignore the line. An outage that lasts is logged at least every 10 seconds, so a
log-based alert needs no state: no broken line in the last minutes means healthy.
- One fixed marker with
key=value fields (KLOK_BROKER_CONNECTION state=... kind=... topic=...), on a logger of its
own. The Quarkus console format is plain text, and an alert must match the line without parsing the rest.
- Producers and reply consumers are created again, durable consumers are not. A producer and a non-durable reply
consumer hold no state the broker needs, so a new one loses nothing. A durable consumer of an exclusive subscription
cannot be doubled while the first is attached, and its unacknowledged messages belong to it; Pulsar keeps reconnecting
it, and the client only reports it.
- A send timeout drops the producer. A producer whose send was not acknowledged within 30 seconds is not trusted with
the next message. That alone would have ended the incident within a minute.
- No rebuild of the shared Pulsar client. Every route of a service shares one Pulsar client
(
KlokPulsarClientManager), with its consumers, their receive loops and their unacknowledged messages. Swapping it
under them was weighed and rejected as riskier than what it replaces: a service whose connection does not come back is
restarted by its health check, which builds a new client the clean way.
- The token is refreshed before it expires (
earlyTokenRefreshPercent 0.8), so the broker's 60 second check no longer
catches a token the client still uses. The broker side gets a leeway as well (openIDAcceptedTimeLeewaySeconds in
klok-environment-setup).
- The lines go to the console, never over the broker. Klok log events travel over the broker and are lost exactly when
the connection is broken.
The root cause inside Pulsar, why the producer did not reconnect when its consumer did, is not proven: the client's
reconnect treats an authentication error as retriable. The fix does not depend on it: whatever keeps a producer
disconnected, the watchdog replaces it.
An Error in a handler does not end the receive loop
A review of klok-egress-ai (solution KLK003, klok-egress-ai!17) proved it: a hostile PDF of 423 KB overflowed the stack
of a worker, and a StackOverflowError passed every catch (Exception) on its way out of the receive loop. The message
got neither an acknowledgement nor a negative one, the loop never ran again, and six files stopped reading for every
tenant, until the pod happened to restart. runningReceiveLoops dropped, but nothing read it. Decided:
- A
StackOverflowError is the failure of that message. The recursion has unwound by the time the client catches it,
so the thread is as good as before, and there is nothing to report about the process: the input does it, and the same
input does it again. It is what a hostile document looks like, and a framework whose every worker a small file can take
out is not acceptable. One thing a stack overflow can leave behind: a class whose static initializer it interrupted
stays unusable (NoClassDefFoundError: Could not initialize class) until the JVM restarts. That shows up as every later
message failing with that error, and the fix is a restart.
- Every other
VirtualMachineError means the process cannot be trusted. An OutOfMemoryError strikes whichever
thread allocates next, also one of Pulsar's. A scheduled task that throws never runs again, and a finally that fails
leaves a lock taken. Nothing tells you afterwards whether that happened, and a restart is the only cure. So the error is
recorded for as long as the JVM lives, and a liveness check takes it from there.
- The message in hand goes back to the broker, and is not dead lettered. An out of memory error says nothing about the
message: another one may have used the memory. A message that really does exhaust the heap every time brings the pod
down every time, with a growing restart count and an error line that names its topic. That is on purpose: no count of
deliveries survives a restart that could be relied on (the broker keeps none on an exclusive subscription), and dead
lettering on a guess would lose good messages whenever a service is short of memory. A handler that can tell that its
input is too large should say so with an exception.
- The loop goes on after a fatal error too. Stopping it was weighed. The process would hardly be safer for it, since
every other thread goes on, and the rest of the service's routes with them. Stopping every loop in the JVM would be
safer, but it turns one bad message into a whole service that reads nothing wherever no probe restarts it. The price is
that the loop handles messages in a process that may be damaged until the restart comes, about half a minute with a
liveness probe. What such a process most likely does is hang or redeliver, which at-least-once delivery covers.
- The client does not end the process.
System.exit or Runtime.halt would restart a service with no health check at
all (Spring AMQP exits with 99 on an Error), but the client is a library, and which failures end a process is its
application's decision. Klok's services leave out -XX:+ExitOnOutOfMemoryError, the JVM's own way of doing it. It ends
the process before this containment can run, so the log names no route and raises no alert, and it turns a burst that a
service's own guard recovers from into a crash loop: of ten large documents sent to klok-egress-ai at once, all ten
finished without the flag and none with it (klok/environment/project-template-integration#15). The price is that an out
of memory on a thread no Klok code runs on restarts nothing.
- The loop goes on on a new thread. The stack is unwound, but what the handler was in the middle of may have left
state behind that is bound to its thread. Camel's engine is the known case: it keeps the rest of an exchange in a queue
per thread, and its bridge around a synchronous step calls the callback in a
finally, with the error in flight and no
exception on the exchange. A loop that catches the error and goes on with that thread runs the failed exchange's next
step when the next message arrives, as if the step had succeeded. A test saw the hostile body arrive there. The Quarkus
extension now keeps an Error from reaching the engine's outside at all, but this client is released first, runs under
older extensions until a service is rebuilt, and serves applications with thread state of their own. So it must be safe
by itself. A new thread costs next to nothing for something this rare, and retiring the old one takes letting its task
throw, since a pool has no other way to end one particular thread. When no thread can be had, the loop stays where it
is.
- Any other
Error is the failure of that message. A NoClassDefFoundError from a class missing in the image fails
every message, loudly, in the log and in consumer.received.error. A restart would not bring the class back, and the
messages come back when the image is fixed.
- A stack overflow is logged with 64 frames. Its 1024 frames make one log line of about 100 KB, and a line that long
is cut or dropped on its way to the log index, with the error in it.
- What ends a loop anyway is seen.
subscriptionHealth() counts every loop that ends while its client is open,
whatever the reason, so also one nobody thought of. A consumer with no loop left is the worst kind of broken: it stays
connected, so the connection watchdog has nothing to report, it keeps its exclusive subscription from anyone else, and
it holds the messages in its receive queue.
A failure in a handler does not end a Python receive thread
The Python client had the fault that the Java client lost with klok-brokerclient-java!28, in its own shape
(klok/framework/klok-brokerclient-java#37, found by reading the code): dispatch caught Exception around the handler,
and the receive loop caught only a provisioning failure around dispatch. A BaseException from a handler, or an
acknowledge on a closed consumer, ended the thread for good. The message got neither an acknowledgement nor a negative
one, threading printed the error to stderr (or, for a SystemExit, nothing), and the consumer stayed connected, so a
subscription with concurrency=1 read nothing while the service looked fine. _reply_loop had the same shape. Decided:
- Anything that is not a stop request fails its message, and the thread goes on. A
BaseException from a handler that
is not an Exception (asyncio.CancelledError, GeneratorExit, one of a library's own) is given back to the broker
without retries or a dead letter: a cancellation says nothing about the message, as an Error says nothing in Java. A
failure outside the handler (acknowledge, negative acknowledge, the invocation's log, _give_up) is caught by the loop,
which negatively acknowledges the message in hand, logs at ERROR with the traceback, and receives the next one. Unlike
the Java loop, the Python one goes on on the same thread: the handler's context variables are reset in a finally, and
there is no engine with a queue per thread that a failed message could leave a step in.
SystemExit and KeyboardInterrupt are a request to stop, and the client honours it. They are the only two with a
case for ending the process rather than the message: sys.exit() in a handler, or in a library it calls, says that the
code wants the process to end, and in a single threaded program it would. Taken as the failure of one message, it would
be redelivered and asked again, forever. Ignored, as threading does, it left a dead thread and a silent consumer. So
the message goes back to the broker, the invocation ends FAILED with STOP_REQUESTED, the client closes cleanly (on a
thread of its own, since closing joins the receive threads), and run_forever() raises the request again on the main
thread, with the same exit code. The Java client has no counterpart to decide against: System.exit ends the JVM
wherever it is called, and Java's own rule that the client never ends the process is kept, since here the handler asked,
not the client. KlokSubscriptionHealth.stop_request reports it, so a worker that does not use run_forever() sees it
in its health check.
- A
MemoryError is the failure of its message, retried and then dead lettered like any other exception. In Java an
OutOfMemoryError marks the process as not to be trusted, because it strikes whichever thread allocates next, one of
Pulsar's included, and the JVM has a heap that a burst can fill. CPython is different in both ways. A container that
runs out of memory is ended by the kernel, which a MemoryError never reports; what raises one is a single allocation
too large to be made at all (a huge decompression, a payload that asks for a list of a billion items), and the
allocation fails before anything is half done, so the process is as good as before. That is what the input does, and the
same input does it again, which is the case for a dead letter, as for a stack overflow in Java. The price is a message
that a moment's memory pressure sends to the DLQ, which a redrive brings back; the alternative, redelivering a message
that fails this way every time, never ends. RecursionError is the same: the stack has unwound when it is caught.
- What ends a thread anyway is seen.
KlokSubscriptionHealth counts every receive thread that ends while its client
is open, whatever the reason, also one nobody thought of, with the reason. A liveness check that reads it restarts the
worker. The reply reader is not counted but given up: the next request on its topic reads it again, which mends it
without a restart, as the Java requester does.
The claim check store speaks S3 itself, and never creates a bucket
The documentation senders needed the claim check outside the Quarkus extension (klok-gradle-plugin#13): a Gradle task
and klok-cli had to store a payload above 3 MiB and publish only its reference. Following the rule that a broker
capability is built in the client first, the store is a public API of the Java and the TypeScript client, with the
extension's key layout, metadata and klokcc:// form, so a reference reads the same from every client.
It speaks the S3 REST API itself, path style with Signature Version 4, over java.net.http and fetch. Weighed against
the AWS SDK, which the extension's store uses: the SDK would have put a dozen jars on every user of the Java client
(Maven Central included, and the Gradle plugin's classpath) and the many @aws-sdk/@smithy packages into klok-cli's
bundle, for four calls on one object. Both clients run the same cases, including the signing examples of the S3
documentation, and are tested against RustFS in the version the platform runs. The extension keeps its SDK store until
it moves onto this one.
The store never creates a bucket or a lifecycle rule. Claim check buckets are provisioned in klok-environment-setup,
like topics on the broker, and a key that may write objects need not be one that may create buckets. A lookup the key
may not make (a 403 on HEAD) is taken as "not there", so a consumer can be given a write-only key, as the CI key of the
documentation senders is meant to be.
klok-common and pulsar-client come from the dependency catalog
The client takes the two dependencies that consumers see through its API from gradle/klok-libs.versions.toml,
refreshed by the build job, as the Quarkus extension does. A hand pin of klok-common kept the release chain from
working: klok catalog release-dependents could only report the client as pinned, and the client stayed a release
behind the catalog until someone raised it. pulsar-client follows because the catalog states that it must align with
this client, which two pins kept true by hand. The copy is written by the last released Gradle plugin's
UpdateKlokLibsTomlTask, applied with apply false: a second implementation of the same bytes was the alternative, and
the plugin does not otherwise configure this build. The other pins stay in gradle/libs.versions.toml for now, because
they do not reach the chain (#18).
Tested on 2026-11-04: ./gradlew build against klok-common 0.3.5+261013111836, the version the catalog has, with the
fixture cases of its jar; the generated POM names that version. The broker tests ran only in the pipeline.
The wire contract copies are synced in the job that ships them
The TypeScript and Python clients read klok-common's wire contract as files, because they have no Java dependency. They
take a copy with klok vendor, and source.json next to it names the release. A hand-carried copy had drifted: on
2026-11-03 all of them missed answeredNotFound, added to klok-common on 2026-10-13. Three ways were weighed:
| Option |
Why not, or why |
| Fail the pipeline when klok-common has a newer contract |
It makes an unrelated merge request red, and still leaves a person to do the work. |
| Commit the refreshed copy back from the pipeline |
One more bot commit per release in a repository that builds against the current bytes anyway. |
klok vendor sync --latest before the tests and the packages, the way a build refreshes the catalog copy (chosen) |
A release of a client carries the current contract, its tests have seen it, and nothing is committed. A release of klok-common starts this pipeline through klok catalog release-dependents. The committed copy is checked for integrity only. |
A released package therefore carries a contract that may be newer than the committed one, and source.json in the
package says which release it is.
Tested on 2026-11-04 with klok-cli's branch: klok vendor sync brought answeredNotFound into both copies, npm test
(296 tests) and pytest (218 passed, 13 skipped, the broker tests) passed against them. The clients do not apply
answeredNotFound in their servicelog yet, and no fixture case asks them to
(#38).