Messaging
Five Hazelcast queues are the only channel between the FCC Service and the Auto Configuration Server (ACS). The two services share a message package, byte for byte, and no handshake. See Why the ACS link is queues only.
Hazelcast queues
Both services are Hazelcast clients of version 5.5.0. The cluster runs in its own container. The queue names carry no prefix.
| Queue | Direction | Message type | Maximum size | Batching |
|---|---|---|---|---|
|
Service to ACS |
Command |
1000 |
None |
|
ACS to service |
Acknowledgement |
1000 |
None |
|
ACS to service |
Result batch |
10000 |
100 items or 5 seconds |
|
ACS to service |
Device state batch |
10000 |
100 items or 5 seconds |
|
ACS to service |
Run event |
1000 |
None |
The maximum size of each queue is configured in the Hazelcast cluster, not in this service.
The five constants for these names live in FccQueueNames.
FccQueueNames now lives in com.friendly:shared-dto, in the package com.friendly.fcc.dto.
See The message compatibility contract for the shared library and its trade-off.
Producer and consumer rules
Both sides follow the same four rules.
The producer offers with a timeout of one second. It never uses a plain add, because an add drops the message on a full queue. A failed offer never loses the message: the outbox row stays pending. See The transactional outbox.
The consumer runs one thread per queue, in a blocking loop. An interrupt ends the loop, and that is the shutdown signal.
An unreadable message is skipped, logged and counted. The thread keeps reading, and only that one message is lost.
Any other failure retries the message in hand. The service logs the failure, counts it, drops the queue handle and waits five seconds. A reconnected client hands out a new handle, so the next round uses it. After five attempts the message is given up and counted. A read removes the element from the queue. Without this retry one short database outage would destroy a whole batch of up to a hundred measurements. The acknowledgement queue has a republish path, and the result queue has none.
Command order and repeated commands
The command sequence number is monotonic per campaign.
The service stores it on the campaign row and raises it in the same transaction as the outbox row.
The ACS discards a command with a sequence number not above the last applied one, and answers a rejection with the reason STALE_SEQ.
A rejected command consumes its sequence number. The service raises the number for every new command, whatever the ACS answers. A corrected command, after an operator fixed the configuration, is a new command with a new key and a new number.
A republication after a timeout is not a new command. It carries the same idempotency key and the same sequence number. See The acknowledgement timeout.
The idempotency key is the identifier of the run.
A repeated key gets the answer DUPLICATE, never a second execution.
See A duplicate carries the original outcome.
Every identifier on the wire is a 64-bit number, so nothing on the queue path narrows an id.
Rejection reasons
Both sides agree on this closed list. No other text ever appears as the reason of a rejection.
| Reason | Meaning |
|---|---|
|
The sequence number was not above the last applied one for this campaign. |
|
This ACS version does not support the command type. |
|
The command asked for more than one device chunk. Chunking does not exist in this version. |
|
The configuration failed the validation of the ACS. |
|
The command consumer of the ACS is switched off. In practice no acknowledgement arrives at all in this case. |
|
Anything else on the ACS side. |
A failed run event uses its own closed list: ACS_RESTART, ACS_UNAVAILABLE and INTERNAL.
This service adds one constant of its own, UNKNOWN.
An unrecognised reason from a future ACS release becomes UNKNOWN, with a log line.
A new reason therefore never breaks the queue.
The service stores the unwrapped reason text in the failure column of the run, truncated to 255 characters. The exact text of the ACS therefore survives for a report. The closed list serves the check and the log line only.
A rejection for a run that already started or already closed changes nothing.
The service logs it with the run, its state and the reason.
The real case is a lost acknowledgement.
The ACS started the run, and the timeout poller republished the command.
The ACS no longer has a record of that command, so it answers STALE_SEQ.
How an acknowledgement is matched
An acknowledgement carries the sequence number of the command it answers. The service matches it on two fields: the key finds the outbox row, and the number says which send of that key it answers. The key alone names the run and not a send.
| Sequence number against the outbox row | What the service does |
|---|---|
Equal |
The normal case. The service applies the acknowledgement. |
Lower |
A stale acknowledgement for an earlier send. The service logs both numbers and changes nothing. This check stops a late acceptance from reviving a run the service has written off. |
Higher |
This should not happen, because the ACS answered a send with no record here. The service logs it and applies it anyway, because it is the freshest information about that key. |
Empty |
An older ACS without the field. The service applies the acknowledgement on the key alone. The field is optional for exactly this reason, so the two sides can deploy in either order. |
A duplicate carries the original outcome
A duplicate means the ACS already processed this key. It says nothing by itself about the outcome of that processing. The reason field carries the original outcome, and the service applies that outcome.
| Reason on a duplicate | Applied as |
|---|---|
|
An acceptance. The run moves to running, and the window end is recomputed from the real start. |
|
The named rejection, from the closed list above. The reason without the wrapper lands in the failure column. |
|
Still a rejection, because the ACS said it refused the original. The run fails with the reason |
|
Still that rejection. The service stores the text as it came and uses |
Anything else |
The service logs a warning and treats it as an acceptance. |
The match ignores case and surrounding spaces, so the result does not depend on the spelling of the ACS.
|
The two fallbacks differ on purpose. An unrecognised envelope becomes an acceptance. The realistic cause is a newer ACS reporting a running campaign in a shape this version does not know. A failure on an unknown text would kill a live run over a vocabulary mismatch, and the real state arrives anyway through results and events. A |
Commands
ACTIVATE
The ACS saves the run with its devices, schedules its own job and acknowledges at once. The acknowledgement comes after the save, not after the first device started.
Three events follow later:
-
a start event at the first tick of the job
-
a finish event after every iteration ran and no device is left in flight
-
a failure event after an ACS restart without a surviving job, or after an unrecoverable error
The ACS computes the number of iterations from the total duration and the single duration. It starts at the later of the current instant and the window start. Its own window end is informational, because it decides completion from the iteration count and the devices in flight.
This service recomputes the window end from the real start, as soon as an acceptance arrives. It applies that only once, because the acknowledgement and the start event travel on different queues in any order.
|
The two records therefore differ by the dispatch latency, and that is the contract. The command on the ACS still carries the original window, and the ACS decides completion from something else. The watchdog and the reports of this service use the new value, so a command delayed in the outbox still gets its full window. |
A watchdog closes a run with an expired window.
It claims running rows past the window end plus ft.fcc.watchdog.finish-grace and closes them as finished, with the reason WATCHDOG.
The outcome is not a failure, because the window ran to its end and nobody reported a fault.
The campaign then gets the same finish event a reported completion would produce, and that plans the next daily run.
The service logs this at warning level, because a control message was lost.
See What the watchdog closes.
STOP
The ACS removes its job, clears the next action of every device, cancels its own pending tasks and acknowledges at once. It then reports a stop event with the number of devices still in flight. Results for those devices still arrive, each marked as taken after the stop.
On this side the run stays in the stopping state until the in-flight count reaches zero or ft.fcc.stop-grace expires.
The default grace is 15 minutes.
Every activate command carries that same grace to the ACS, so both sides hold in-flight results for the same window.
A stop is always a new command, with a fresh key and the next sequence number. The service writes the same stop on three paths. Those paths are an operator stop or pause, a delete of a campaign with a live run, and a run the ACS never acknowledged.
The stop reason does not travel on the wire. The reasons live in the run row and in the log only.
A run still in the planned state is the one case without a command. See the planned divergence.
The stop drain is recounted, never decremented
The service writes the in-flight count from the stop event, and only when the ACS reported one. An empty count is left alone. A written zero would close the run at once and discard every measurement still in flight.
From then on the service recomputes the figure from the device states.
stillSent = SELECT COUNT(*) FROM fcc_device_state
WHERE activation_id = ? AND state = 'SENT'
in_flight_count = MIN(stored_in_flight_count, stillSent)
A decrement per message cannot be made safe on a queue with repeated delivery. A redelivered batch, or two instances with overlapping batches, would subtract twice. The column would then name devices that were never in flight.
A count of the rows still in the sent state is exact by construction. It reads the state the upsert wrote, on the same connection and in the same transaction. It also costs one indexed count per stopping run instead of one update per device.
The lower bound matters. The column may only fall. Hazelcast does not order messages, so a reordered batch can re-assert the sent state for a device that has finished. A recount of the raw figure would revive drained devices. The run would stay open until the stop grace closed it.
The close is additionally guarded by a stored count above zero. That is not the same condition as a recount of zero. A run reaches the stopping state with the column at zero whenever the ACS reported no count. Reading that zero as drained would undo the rule above.
A recount of zero closes the run as stopped. Otherwise the stop grace closes it.
|
A device state of |
PAUSE and resume
A pause on the REST surface is a stop of the current run with the reason USER_PAUSE.
The campaign then moves to the paused state instead of the not-active state.
There is no pause on the wire. The ACS receives an ordinary stop, so the measurements end instead of waiting.
A resume is a plain activation. It creates a new run with a new key, a new sequence number and a fresh settings snapshot. It is never a resend of the paused run. See POST /FCC/pause.
Two command types exist for future use, and this ACS version rejects both as unsupported. The outbox of this service never writes either type.
The acknowledgement timeout
Without an acknowledgement within ft.fcc.command-ack-timeout, 60 seconds by default, the poller republishes the outbox row.
The poller ticks every ft.fcc.outbox.ack-timeout-interval, 30 seconds by default.
The republication keeps the key and the sequence number and follows the same delay ladder as a fresh publication.
The ACS recognises the key and answers with a duplicate.
A late acceptance still starts the run, as long as the delay is inside ft.fcc.activation-max-delay, 30 minutes by default.
The run then starts with a shifted window, recomputed from the real start.
The sequence check of How an acknowledgement is matched is the second half of this rule. An acknowledgement with a lower number answers a send the service has moved past, so it cannot restart a run already written off.
The same poller tick also fails stalled runs. It claims every run still dispatching whose window opened before the maximum delay. This check reads the age of the run, not the attempt count of the outbox row.
Such a run fails with the reason ACS_UNAVAILABLE, the campaign moves to the error state, and a fresh stop command goes to the outbox.
The stop exists in case the ACS did apply the original command after the acknowledgement was lost.
|
A planned run is deliberately not a stalled run, and the wider reading is a data-loss bug. Nothing was ever sent for a planned row. It carries the unassigned sequence number and owns no outbox row, so no acknowledgement can have timed out. Such a claim would fail the next daily run of a campaign half an hour after its window opened. It would publish a stop for a run the ACS never heard of. That consumes a sequence number. It would also feed a failure to a campaign that may be running a healthy newer run. The case such a predicate would cover is a command that never reached the queue. The attempt budget of the outbox already covers it. |
Run events
The run event queue is the control channel of the ACS about a run it executes. It is the only channel able to report a finish. Everything else this service knows about the end of a run is a local decision.
One listener translates the wire vocabulary into the events of the two state machines and applies both, in one transaction per message.
| Event | Run event | Campaign event | Effect |
|---|---|---|---|
|
|
|
The run moves to running with a start instant and a recomputed window end. From running it is an idempotent confirmation. The campaign stays running. |
|
|
|
The run moves to finished, or to stopped when it was already stopping. This event carries the cadence of the campaign. See Reactivation is daily, and missed slots are skipped. |
|
|
|
The run fails and the campaign moves to the error state. The service stores the reason of the ACS as it came, truncated at 255 characters. The column is free text on purpose, because no local vocabulary could substitute for it. An empty reason leaves the column unchanged. |
|
|
|
The run moves to stopping or stopped, split on the reported in-flight count. The campaign is often not touched at all. |
An event naming an unknown run is dropped and counted, not an error. An event can outlive the run it describes, after a purge, a restored backup or an ACS pointed at another database.
An event without a type or without a run id is dropped the same way, with a warning. An event without an instant falls back to the current instant, because an empty start instant would hide the run from the window watchdog forever.
The reported columns are written after the transition
Two columns of an event are not part of any transition: the failure reason and the in-flight count. The service writes them only after the state machine allowed the transition.
A field set on the run reaches the database at the end of the transaction. A late failure event for a finished run is denied. An early write would still leave its reason on that finished run, next to a stop reason that says something else.
The campaign half is skipped too when the run transition is denied. Apply only the campaign half, and a late report revives a stopped campaign.
A stop event does not always reach the campaign
Two cases stop short of the campaign:
-
The run is still stopping. It has devices in flight. The campaign is reported as stopped once, when the run closes.
-
The stop reason is a user stop or a user pause. The operator stopped the run, and the endpoint already moved the campaign. A campaign paused and then stopped keeps the pause reason on its draining run and falls under the same clause.
|
The second case matters. A stop event applied on top of a pause is the single way a pause degrades into a stop. The transition from running to stopped is valid, so nothing downstream would refuse it. The campaign would end up stopped, and the distinction between a pause and a stop would be gone. One method implements that rule, and all three call sites use it: this event path, the drain recount and the stop-grace watchdog. |
Reactivation is daily, and missed slots are skipped
The reactivation effect plans the next daily run as a planned row with no command.
The cadence is a product rule. The campaign column holds a count of daily runs, so run number two opens 24 hours after run number one opened. A cadence from the finish instant would let the campaign drift by the length of every run.
The anchor falls back from the start instant to the window start and finally to the current instant. A run closed by the watchdog before any reported start has no start instant, and the cadence still needs an anchor.
|
Missed slots after an outage are skipped, never fired. The next slot may already be in the past, after an outage of two days or a late finish report. A poller that claimed such a window would fire every missed run back to back. It would burn the remaining runs of the campaign in minutes and fill a compliance report with measurements of one afternoon. The service therefore steps forward one period at a time until the instant is in the future. The daily rhythm resumes at the next real slot, and the missed ones are lost. That is what a daily test means. The loop is capped at ten years of steps, so a corrupt start instant gives one warning and a run tomorrow instead of a spin. |
The planner re-checks the remaining run count, the same predicate the state machine evaluated. A disagreement means an operator edited the campaign in between. A planned run the campaign does not owe would measure longer than configured, so the service logs a warning and plans nothing.
The planned row is claimed by its poller when the window opens, and the dispatch re-takes the settings snapshot. See A planned run re-takes its snapshot.
A skipped dispatch closes the row
A dispatch that answers no does not leave the row alone.
The poller closes it as stopped with the reason WATCHDOG, inside the transaction that holds the claim.
A refused dispatch means the campaign no longer expects the run. It was stopped, paused or activated again while the row waited, or its settings rows are gone. None of that changes back.
A planned row with an open window is claimed by every following tick, and every later plan adds another one. An abandoned row is therefore an unbounded leak of poller work.
The reason is WATCHDOG and not ERROR, and the state machine already uses the constant in that sense.
It records that the closing decision was local.
Nothing failed here: the ACS was never involved, and a local poller closes a run its campaign moved on from.
An error would put a fault into the history of a campaign running perfectly well.
Only a row still in the planned state is closed, and the service re-checks that state. A dispatch also answers no for a row somebody else moved on, and such a row is not the poller to close.
What the watchdog closes
Any remote report may never arrive. The ACS restarted, another cluster drained the queue, or the message was unreadable. A run nobody closes stays open forever: its campaign never reactivates and never completes, and its window sits open in every report.
| Pass | Claim | Outcome |
|---|---|---|
Window expiry |
A running run whose window ended before the finish grace |
The run finishes with the reason |
Stop grace |
A stopping run whose stop instant is older than the stop grace |
The run moves to stopped, whatever it still owes. The campaign is left alone after a user stop. Logged at info level with the in-flight figure, because that is the only record of how many measurements still arrive for a closed run. |
|
The two graces are separate settings and are not interchangeable.
One setting for both would mean that a longer stop also delays every watchdog close. Both default to 15 minutes, and that is a coincidence of the defaults. The stop grace is not purely local. Every activate command carries it to the ACS, so a change also changes what the ACS does on the next run. The finish grace travels nowhere. |
Both bounds are computed in Java and passed as parameters. No statement therefore depends on the date arithmetic of a vendor or on the clock of the database.
Device states
The device state queue carries batches, and each batch becomes rows of fcc_device_state.
Those rows are the current position of each device of a run, and the device status endpoint reads them.
The service uses one statement per message, never one per device. A batch can carry the whole fleet of a campaign, up to twenty thousand devices. It resolves the runs of the batch in one query and writes the states in one database batch.
A row is written only when the service can key it and attach it. The two rejections are counted apart.
| Rejection | Counter | Meaning |
|---|---|---|
A missing run id, device id or state |
|
A malformed message, logged at debug level. The check sits inside a loop over a whole fleet, so a warning per row could produce twenty thousand lines from one message. The first two fields are the unique key and the third is mandatory, so this points at the ACS. An operator needs the aggregate count, and the per-row detail is available at debug level. |
A run id this service does not know |
|
Not malformed, logged at debug level. It is the mirror image of the |
The upsert is documented column by column in fcc_device_state. The four counters only grow, and the newest observation wins for the serial number, the state and the reason. Each vendor uses its own native statement. A read and then a write would lose a parallel update from a second instance on the same queue.
An absent observation instant falls back to the batch instant and finally to the current instant. A row with an invented timestamp merges by arrival order. That is wrong and recoverable. A refused row leaves a device in its initial state on the screen forever.
After the upsert every stopping run of the batch gets its drain recount. See The stop drain is recounted, never decremented.
The nine device states
The state column stores the wire vocabulary with no local copy, because the ACS owns it end to end. A second dictionary would only add a mapping able to drift.
The nine states are INITIAL, OFFLINE, SKIPPED, WAN_CHECK, CROSS_TALK, SENT, FINISHED, ERROR and STOPPED.
The state STOPPED means a stop halted the device between steps, so its WAN sample or its diagnostic was never sent.
It is not a failure and not an error.
It is its own state, exactly as cross talk is, and neither is ever counted as a failure.
The drain recount ignores both, and the six counters of the device status endpoint fold STOPPED into not sent and cross talk into skipped.
Device state reasons
The reason qualifies a state where the state alone does not say why. The wire carries free text, and this service maps it to a closed list.
| Reason | Usual state | Meaning |
|---|---|---|
|
|
The device does not implement the diagnostic of the run. |
|
|
The device is busy with another diagnostic. |
|
|
The device did not answer inside the configured diagnostic timeout. |
|
|
No WAN interface could be resolved for the measurement. |
|
|
The device reported a fault of its own. |
|
|
The ACS no longer holds the run of this device, so the device could not run. This is explicitly not a device fault. |
|
|
The operator stopped the run before this device had a diagnostic in flight. Also not a fault. |
|
any |
Anything this version does not recognise. The ACS never sends it. |
The service trims and upper-cases the wire text and falls back to UNKNOWN.
A new constant on one side must not break the other side, because the message package is frozen and shared.
A screen with an unknown reason is better than an ACS upgrade that makes the whole queue unreadable.
The transactional outbox
A queue offer cannot take part in a database transaction.
The service therefore writes the command into fcc_acs_outbox in the same transaction as the run row and the sequence number.
See fcc_acs_outbox for the columns.
The dispatcher ticks every ft.fcc.outbox.dispatch-interval, 5 seconds by default.
It claims up to ft.fcc.outbox.batch-size rows, 100 by default, with a two-statement claim.
It offers each payload to the command queue and marks the row as sent only after a successful offer.
A timed-out offer never drops the message. The row stays pending with a later attempt instant, and that is the whole reason this table exists.
A timed-out offer does end the tick. A full queue means the consumer is behind, so the remaining claimed rows wait for the next tick. Otherwise the transaction would hold its row locks and a pooled connection for one second per row.
The claim, the offer and the state update run in one transaction, so a second instance skips the locked rows instead of sending twice.
Both a fresh publication and a republication share the failure path.
Each failed attempt raises the attempt count and sets the next attempt instant.
The delays are fixed: 5 seconds, 15 seconds, 45 seconds, 2 minutes, 5 minutes, 15 minutes, then 30 minutes.
After ft.fcc.outbox-max-attempts attempts, 10 by default, the row becomes abandoned and nothing retries it.
|
An abandoned row fails the run in the same transaction. The run fails with a reason naming the exhausted row, the campaign moves to the error state, and a fresh stop goes to the outbox. The stop exists because a row sent at least once may have reached an ACS that is now measuring. The path is idempotent by state, so a run that meanwhile started or closed is left alone. The age-based check normally fires first with the shipped defaults. The first six waits total about 23 minutes, and the three later ones add 30 minutes each, so an abandoned row takes about 113 minutes. That is well past the 30-minute ceiling of the age check. The two paths are independent on purpose. The abandoned path covers an installation with a much higher delay. The age check covers an ACS that never answers. |
Result ingest
The listener takes each result batch off the queue and hands it to the ingest service. That service counts and logs a result naming no run, de-duplicates the rest across the cluster, and buffers them.
The service resolves the run and computes the verdict at flush time, not on arrival. A queue read is destructive, so every step between the read and the buffer is a path where one failure costs the whole batch. The flush is retried.
Routing by direction happens at flush time
A ping is buffered exactly like a download. Both are measurements of the same run and share one key space and one buffer. The service splits the batch only after it resolved the runs.
| Direction | Destination |
|---|---|
|
The latency table, judged by the latency rules. |
|
The speed table, judged by the speed rules. |
Empty |
The speed table, with the empty direction that column has always carried. An empty direction is not a ping, and an invented ping would land in a table whose latency block it cannot fill. |
The two inserts are two independent attempts, each with its own half of the rows. They write different tables, from disjoint sets of measurements, under different natural keys. No row of one is the counterpart of a row of the other. A half-written flush is therefore not a corrupt state: the speed measurements are stored, and the ping measurements are still owed.
|
A retry of the written half would insert it a second time, and that is the defect this split prevents. A duplicate in ClickHouse cannot be taken back. There is no uniqueness to violate, a reader collapses it on the natural key, and every extra copy skews the regulatory report. One table blocked by a schema mismatch rewrote the healthy rows of the other table. At the longest retry delay that happened about forty-eight times a day. The first failure is the one reported in the error field of the batch. One flush counts as one failed attempt, whether one table failed or both. Counting it twice would double the backoff on every tick of a whole outage. |
|
The backoff is still shared across both tables, and that is a known limitation. The failure count and the next attempt instant are one counter and one instant for the whole flush. The latency table alone can be unwritable. The healthy speed rows in the same buffer then wait for the next attempt too, up to 30 minutes. No row is lost or duplicated by this, only delayed. |
De-duplication is one atomic write
The natural key is the run, the serial number, the direction and the iteration. The service joins them into one string and stores it in a Hazelcast map.
The store and the check are one single write. Only one caller can store a given key, so two instances on the same batch keep one measurement and not two.
The lifetime is ft.fcc.dedup.ttl, one hour by default.
That is long enough to cover the retry window of the ACS and short enough to bound the map.
A failed Hazelcast call answers not a duplicate, and the service stores the row. A row a reader can collapse on the natural key is recoverable, and a dropped measurement is not.
The service writes the marker before the ClickHouse write, so every path that drops the row releases the marker again. Those paths are the buffer overflow, the exhausted requeue and the shutdown flush.
The rule is one invariant: a key may only outlive a row the service did write. Otherwise a recoverable drop becomes a permanent loss. The key holds the slot for its whole lifetime, and the service skips a second delivery inside that time. The first attempt of a key therefore wins. If the ACS retries the iteration and the retry passes, the report does not show the retry. A device that errors and then passes inside the lifetime shows other. The map lives on the cluster, so the invariant must hold across a restart of this service. Each buffered row therefore carries its own key.
Batching and the retry path
Rows that pass the de-duplication go onto an in-memory queue, still in wire form.
The bound is ft.fcc.result.queue-capacity, 10000 by default.
The service flushes the buffer on the first of two triggers.
-
the buffer holds
ft.fcc.result.batch-sizerows, 100 by default -
ft.fcc.result.flush-intervalhas passed, 5 seconds by default
A flush resolves the run context, judges the rows and writes one database batch per table. A shutdown flush drains the buffer once more. It runs after the consumer threads are stopped, so nothing is still arriving, and the shutdown phase timeout leaves room for it.
The same buffer is the retry queue. A failed flush offers every retryable row back onto the queue and computes the next attempt from the same ladder as the outbox. The count is per consecutive failure, not per row. Retryable is the whole batch except the late arrivals, because those already left for the dead letter table.
A row leaves the buffer only when the buffer is full. The service logs an error with the row count, counts it, and marks the result store as unavailable. It does not mark it as schema behind, because a full buffer says nothing about the cause. The health check refines the status on its next probe.
Either status closes the result gate, and every gated endpoint refuses new work until a batch is written again. The gated endpoints are the activation, the four report endpoints, the dead letter resend and the legacy import start. A resend feeds the ingest path the outage already broke, and the import would read millions of rows only to fail every insert.
A row leaving the buffer is not dropped. The service parks it in the dead letter table. See The dead letter table. The error level stays, because a full buffer needs a human whatever happens to the row.
The shutdown flush parks whatever it could not write, for the same reason. A rolling deployment during a ClickHouse outage is the likely way to meet that branch, and it is the one moment without a next tick.
|
Three places write the degraded state of the result store. Those three are the health check, the migration at startup and its retry, and the result ingest. The ingest writes the state after a failed insert or a full buffer. Any one of them can turn the service degraded, and clearing it is not the job of the health check alone. The ingest service clears it after every successful flush, and the migration runner clears it after a successful migration, including its 60-second retry. A ClickHouse outage that resolves through either path therefore clears the state without a wait. The health check is the only one of the three that runs unconditionally on a timer. See Health for the three states and why an unavailable store and a schema behind are told apart. |
The service resolves the context of a batch once per flush, never per row. The context carries the campaign id, the cross-talk thresholds, the success criteria, the domain, the hub id and the stop instant. It is deliberately never cached across batches. A stale threshold would silently change a verdict, and a compliance report cannot tolerate that. Every batch therefore re-reads the snapshot. That is what keeps an edited campaign measured against the settings frozen at activation time.
Results after a stop
The stop instant of a run defines two boundaries, and they mean different things.
| Boundary | Effect | Meaning |
|---|---|---|
The arrival is at or after the stop instant |
The row is marked as taken after the stop |
The service stores the measurement normally, in the table of its direction. |
The arrival is after the stop instant plus the stop grace |
The row goes to the dead letter table with the reason |
The service excludes the measurement from the run and writes nothing to ClickHouse. |
For the mark the wire flag wins when it is set, because the ACS knows when it issued the diagnostic. The local comparison is the backstop for an ACS without the flag. Without the backstop an older ACS would have every after-stop result indistinguishable from the rest.
|
A late measurement is parked, never discarded and never resent. That is the regulatory rule. A compliance export must be able to exclude what was measured after the stop. The measurement therefore has to live somewhere it cannot be counted by accident. Throwing it away would also destroy the evidence that it happened. A resend would put it back into the export the rule keeps it out of. A late row is therefore written straight as discarded, and the resend query filters the reason as well. See A late row is parked as discarded. |
Two details of the comparison matter:
-
It uses the arrival instant the row carries from the start, never the instant of the flush. After a long outage every buffered row would look late, and a whole run would be parked instead of stored.
-
A row whose run cannot be resolved is not late. Unknown run and after the run ended are different statements, and one treatment would park rows that only lost their context.
The dead letter table
Four paths write to the dead letter table, with one of two reasons.
| Path | Reason | Counter |
|---|---|---|
The buffer refused a row |
|
|
A failed flush could not put every row back |
|
|
The shutdown flush left rows behind |
|
|
The measurement arrived past the stop grace |
|
|
|
There is no counter for dropped results any more, and the absence is deliberate. The old counter meant results lost because the buffer was exhausted, so alerts read it as data loss. Every path that incremented it now parks the row instead. Two counters carry the two meanings: |
The dead letter write runs in its own transaction and never throws. The ingest path is already failing and must not roll back the record of that failure. It must also not receive a second exception in the middle of a flush.
Only when even that insert fails is the row gone, and only then does the lost counter rise.
Rows are parked grouped by their arrival instant, because that instant belongs to the row and not to the call. A retry batch mixes measurements of several arrivals, and one instant for all of them would rewrite when they arrived.
Every path that parks an unavailable row releases the de-duplication key, for two reasons. The general invariant applies, and a parked row is replayed on a resend and must pass the check again. A key left behind would make the resend do nothing and turn a recoverable outage into silent loss.
A late row is the one exception and keeps its key. It is durably recorded, it is never resent, and a retransmission of the same key would be judged late again.
Where the domain and the hub id come from
A result carries its own domain and hub id. The ingest path takes both from the result and falls back to the snapshot of the run only when the wire value is absent.
Absent is not the same test for the two fields.
| Field | Which values count as absent |
|---|---|
The domain |
An empty value, and any value not above zero. A zero is not a domain, and a zero is also the sentinel this service writes when neither source yields one. A wire zero is therefore indistinguishable from the ACS could not resolve one, and it must not beat a snapshot value that does resolve. |
The hub id |
An empty value only. An empty text is a legitimate value, because a campaign may genuinely have no hub id. Treating it as absent would let the snapshot overwrite an ACS that said none. |
The domain on the wire is not a guess of the ACS. This service puts the campaign domain on the activate command, and the ACS echoes it back.
The snapshot resolve stays in place in any case. It supplies the campaign id, the thresholds and the success criteria, and no batch can be judged without it. The wire fields only remove the dependency of those two label columns on the snapshot.
|
A row written by an older ACS may carry another domain than a row written by a current one, for the same kind of campaign. The older value was plausibly the domain of the device, not the domain of the campaign. The two differ by design when a super-domain operator builds a campaign out of sub-domain devices. Do not assume the domain column means the same thing across that boundary in a long report. |
Pass and fail rules
This section is the single definition for both repositories. It has two halves, speed and latency. Both share one resolution order, one status list and one rule: cross talk is never a failure.
The four statuses are SUCCESS, FAILED, CROSS_TALK and OTHER.
|
The ACS evaluates the same predicate internally, as a private input for its own retry decision. It never publishes the verdict. The status this service stores is the only verdict that reaches a report. That is why the result message on the wire carries no status field at all. |
The speed half
FILE_BASED (the window the device transferred the file in)
speed_kbps = total_bytes * 8.0 / duration_ms // duration_ms = eom - bom
TIME_BASED (the full-loading window of TR-143)
speed_kbps = test_bytes_under_full_loading * 8.0 * 1000.0 / period_of_full_loading_micros
both
speed_ok = speed_kbps >= tier_kbps * speedSuccessPercent / 100.0
cross_talk = wan_usage_dl_kbps >= thresholdDlKbps || (thresholdUlKbps != null && wan_usage_ul_kbps >= thresholdUlKbps)
The duration is in milliseconds and the whole chain uses floating-point arithmetic. The tier is compared directly in Kbps, with no division by 1024.
Two formulas, one verdict
The snapshot of the run decides which formula applies, never the current campaign. A finished run must keep reporting what it measured after somebody switches the campaign to the other mode. An absent mode reads as the file-based one, because that is what every older run was.
|
The window from the begin to the end of the measurement is not the denominator of a time-based test. That window spans the whole configured duration, including the ramp-up of the connection. The full-loading window of TR-143 exists precisely to exclude the ramp-up. A division by the wrong window under-reports every time-based measurement and fails compliant lines. The report would then accuse a provider of breaching a tier it meets. This is the one arithmetic mistake here that produces a plausible number instead of an error. |
The units of the second formula deserve a sentence, because a factor of a thousand also looks plausible. Bytes times eight are bits. The full-loading period is in microseconds, so a division by it and a multiplication by a thousand is a division by milliseconds. Bits over milliseconds are Kbps, and the tier, the thresholds and the stored column are already in Kbps.
A worked example: 12500000 bytes under full loading over 10000000 microseconds give 10000 Kbps. That is ten megabits, and 12.5 MB in ten seconds.
Everything that decides a verdict is shared. Only the numerator and the denominator differ by mode. A device error is still answered first, then cross talk, then an unmeasurable iteration is other, and only then is the rate compared. The two modes therefore cannot drift into two definitions of success.
A time-based iteration without a full-loading block is other with no speed. The guard covers an absent or non-positive period and absent or non-positive bytes. A device can run a time-based transfer and still answer the TR-143 parameters as zero, on an older or trimmed model. A judgement against an invented window would be worse than no judgement. The ACS agrees on these inputs and answers indeterminate instead of falling back to the wrong window.
Three rules matter more than the arithmetic.
No integer division and no division by 1024. The legacy formula truncates through integer division and divides by 1024 where it must not. It is wrong and must not be copied.
A duration of zero or less is *other, never an infinite rate.* Some devices report the two instants at whole-second precision, and a small fast file completes inside one reported second. Unmeasurable is broader than the duration: an absent or non-positive byte count, and an absent or zero tier, map to other the same way.
A byte count of zero is the case that looks measurable and is not. A device can report a completed diagnostic with a plausible multi-second window and nothing transferred. An upload to a URL that accepts the request and discards it does exactly that. The arithmetic then gives zero. That is below every tier, so a report said the line is slower than contracted where the truth was nothing was transferred. One transferred byte is still a measurement, and still a breach below the tier. Only zero means nothing happened.
Cross talk is a reporting category, not a failure. With a WAN already busy above the threshold the iteration carries no usable figure. It must not count against the success percentage in either direction.
The outcomes are checked in a fixed order, because more than one condition can be true.
-
A device error first: the result carries a description.
-
Cross talk second, whatever else the iteration would have been.
-
Unmeasurable third, once the first two are ruled out.
-
The speed comparison last, only for a measurable iteration that is not cross talk.
A description on the result is the DiagnosticsState text of a test that did not complete, for example Error_TransferFailed.
A blank description means no error.
Any DiagnosticsState other than Completed counts as not completed, for example the vendor value Success.
The service then stores other with no speed, whatever the counters say.
A device can leave stale counters behind an error, so the counters are not trusted.
Because this check runs before the cross talk check, a test cancelled after the stop is other and not cross talk.
The service still stores the raw byte count, the begin and end instants and the description as the device reported them.
The report therefore shows them unchanged, and they can be stale.
The success percentage falls back to the runtime default of 80 when the snapshot carries no value.
The service still computes and stores the speed figure for a cross talk verdict or an other verdict from unmeasurable inputs. It needs the duration and the byte count for that. The order decides the verdict only. Where there is nothing to compute from, the column carries zero. That is the correct result of the arithmetic. A device error is the exception: the speed column carries zero, because the service does not compute a speed.
The latency half
ping_ok = avg_ms < latencySuccessMs && success_count > 0
cross_talk = wan_usage_dl_kbps >= thresholdDlKbps || (thresholdUlKbps != null && wan_usage_ul_kbps >= thresholdUlKbps)
The latency bound falls back to the runtime default of 100 milliseconds.
The upload threshold is always empty for a latency run, because the snapshot writes the upload columns empty for that type. The cross-talk clause handles it anyway, so the two calculators stay literally the same predicate.
The resolution order is identical to the speed half, and that is a hard rule.
-
A device error first: the result carries a description.
-
Cross talk second.
-
Unmeasurable third: an absent average or an absent success count.
-
The criterion last.
For a device error the service stores other with no average, minimum or maximum. It also stores zero for both packet counts and invents none. The rule is the same as for speed, see device error.
A compliance report reads the two tables as one set of iterations. A measurement that would be cross talk as a download must not come out as a failure because it was a ping. A reordering here would make one line condition mean two different things.
|
A success count of zero is a failure, not other. Unmeasurable means an absent average or an absent count, and nothing else. A count of zero means every packet was lost. That is the worst outcome a ping has. Confusing the two would move the most severe result into a category no report counts. The count is part of the rule for the same reason. A ping that lost every packet reports no average, and an absent average must never read as a fast one. |
The packet count is reconstructed as the sum of the successes and the failures, never from the configured repetitions. An absent counter contributes zero, because the two packet columns are mandatory. The three round-trip values pass an empty value through, because their columns are nullable.
A result also carries what the device used: the repetition count and the data block size. The service stores both as they came and falls back to the snapshot when the wire value is absent. Neither feeds the packet count. The sum is what the device did, and the repetition column is what it was asked for. A run that ended early must not be able to claim otherwise.
The Technical Report 181 (TR-181) object is IPPing.
The service reads three of its parameters.
Device.IP.Diagnostics.IPPing.SuccessCount
Device.IP.Diagnostics.IPPing.FailureCount
Device.IP.Diagnostics.IPPing.AverageResponseTime
TR-181 guarantees that the two counts add up to the number of repetitions.
WAN usage sampling
The WAN usage is a rate over two byte counters:
wan_usage_kbps = (bytes_2 - bytes_1) * 8.0 / gap_ms
A wraparound of the 32-bit counter discards the sample pair, and the ACS samples again. The gap comes from the own clock of each side, never from a database column.
This sampling runs on the ACS. This service receives the two figures and compares them against the cross-talk thresholds. It does that for a latency run too. That is why the latency settings carry a threshold at all.
Sequence diagrams
Stop and drain
The diagram shows the closing half. That is a user stop, the stop command, the acknowledgement with an in-flight count and the device states draining that count. The stop grace is the other branch. A pause is the same diagram with the pause reason and the campaign in the paused state.
The message compatibility contract
Both sides hold the same message shapes.
The 25 message records now live once, in the shared library com.friendly:shared-dto, version 0.0.19, classifier plain.
Both services depend on this library.
Neither service holds its own copy of the records anymore.
The records keep the package name com.friendly.fcc.dto.
The queues carry Java serialisation.
Java serialisation writes the fully qualified class name into the message stream.
The package name is part of the wire format.
The unchanged name lets an old build and a new build read each other’s messages.
It keeps messages already in the queues readable.
No coordinated deploy is needed for this migration.
No queue drain is needed for this migration.
These two sentences describe this migration only.
They do not describe every future change.
The add-only rule still holds.
The enum-append rule still holds.
The deployment order below still holds.
The shared library changes none of them.
Sharing one library has a cost.
Before this change, the two services released independently of each other.
shared-dto is now a third component in an FCC release.
A contract change must publish shared-dto first.
Only then can either service build.
Raising the version in the ACS is not one edit.
ft-fcc-service holds a single <shared-dto.version> property.
oneiot_backend declares shared-dto in eleven poms.
fcc-core is one of them.
The other ten modules pin the dependency themselves.
No dependencyManagement entry centralises the pin.
A left-behind module still builds green on its own.
The assembled WAR then fails with NoClassDefFoundError.
Sharing one library also has a gain. One definition now replaces two copies. A reviewer used to enforce the byte-for-byte match between the copies. The compiler now enforces it. There is only one copy left to compile.
This compiler guarantee excludes FccQueueNames.
Its five constants are compile-time literals.
Each consumer inlines them at its own build.
An unrecompiled consumer keeps the old values.
The build gives no error for this case.
Contract tests in shared-dto pin the class names.
The tests also pin the serialVersionUID.
The tests also pin the enum order and the queue name literals.
| Rule | Reason |
|---|---|
A field may be added. It may never be renamed, retyped or removed. |
An old consumer then reads a new producer, and a new consumer reads an old producer. No deployment has to be coordinated. |
Each of the 25 records implements |
The add-only rule above depends on this fixed value. A fixed value keeps an added field readable in both directions. Without it, any class change breaks deserialisation on the other side. |
An enumeration value may only be appended. |
An appended value is new work for an old reader. See Deployment order. |
The 25 records and |
The ACS and this service run different major Jackson versions. The queues carry plain Java serialisation, not JSON. A framework dependency inside the contract classes would tie them to one side’s version. |
The same shapes are stored as JSON in the database columns. |
A stored string must survive a deployment that changes the shape, and only JSON degrades gracefully. The add only rule therefore also governs the stored payload. |
Deployment order
An added field is safe in both directions. An old reader ignores a new field, and a new reader reads an absent field as empty.
An added enumeration value is not safe in that direction. An instance with the older shapes cannot read a value it does not know, and the queue read already removed the message. The service treats an unreadable message as not retryable, so it discards the whole batch and counts it as unreadable.
|
Deploy this service first and the ACS second. An ACS ahead of this service emits values the older instances cannot read. During a rolling deployment of this service, old and new instances consume the same device state queue. A batch with a new value reaches an old instance and is lost whole, not only the one row. That is a real cost of a mixed window, and it argues for a short one. This does not require drained queues.
The loss is bounded to device state batches with the new value.
A device state is current state and not history, so the next batch reports it again.
Watch |