Back to blogDeutsche Version
AI Automation

Industrial Counter Features: Distinguish Reset, Wrap and Missing Samples

Distinguish industrial counter resets, wraps and missing samples with an executed validity gate. Reject ambiguous deltas before deriving AI features.

10 min readUpdated
Detailed industrial counting wheels and encoder with a red reset lever, showing the distinction between wrap and reset. INDUSTRIAL AI — RESET OR WRAP? PROVE THE DELTA.

BLUF: A lower cumulative counter is not automatically a reset, and a higher counter does not prove uninterrupted growth. Derive an industrial rate only when source identity, discontinuity evidence, acquisition time, counter width and a defensible maximum increment rate leave exactly one possible delta. Otherwise emit an unavailable feature with a reason—not a negative rate, a clamped zero or a guessed wrap.

The executed example below uses synthetic eight-bit counters. It distinguishes a unique wrap from a reset, rejects duplicate or reversed timestamps and demonstrates why a long observation gap can hide multiple wraps. It is an in-memory policy fixture, not a production sensor integration or evidence of manufacturing accuracy. Keep its output outside the physical-control path.

Define what the counter actually counts

A raw register needs more than a numeric type. Record its asset lifecycle, channel, unit per increment, unsigned width, rollover modulus, reset semantics and acquisition quality. Establish whether it counts pulses, completed cycles, accepted parts or another event. A pulse count becomes a production count only with a separately validated mapping. Bidirectional position, inventory and signed accumulators require different contracts; this policy assumes increments are nonnegative between explicit discontinuities.

Extend the industrial data-contract foundation with a coherent observation envelope: raw integer, acquisition timestamp and clock identity, source boot identity, counter-discontinuity identity, quality, contract version and arrival timestamp. Retain the raw envelope before deriving features. The source lifecycle is not the collector process ID, and arrival time is not acquisition time for a buffered reconnect burst.

The epoch must change whenever a counter reset or replacement breaks continuity, including an operator reset without a device reboot. A boot ID alone is insufficient. Read the value and metadata coherently using the source's supported snapshot or sequence mechanism. If a reset can occur between separate reads without detection, unchanged metadata is not proof of continuity. The algorithm cannot recover evidence the source never exposes.

Borrow the discontinuity principle, not a sensor standard

RFC 2863, the Interfaces Group MIB, provides a useful networking example. It specifies ifCounterDiscontinuityTime and requires management applications to discard a difference when that value changes between polls, in addition to checking sysUpTime for agent reinitialisation. An interface index alone does not establish uninterrupted counter history.

This is not an industrial-sensor standard or an instruction to invent an SNMP field for a PLC. Apply the principle through the actual device contract: a reset generation, durable lifecycle identity or equivalent trustworthy evidence. Consider metadata rollover, reuse and gaps long enough to conceal a restart. Unknown continuity should remain unknown, not become a default epoch string shared by every observation.

Prove that exactly one delta is admissible

Let a and b be two raw values, M = 2^bits the declared modulus and dt the positive elapsed acquisition time in one clock domain. With verified continuity, the smallest nonnegative delta is d = (b − a) modulo M. All possible increments are d + kM for nonnegative integer k. A physical upper bound R limits admissible increments to at most R·dt.

The decision is exact under those assumptions: if d exceeds R·dt, no increment is admissible; reject a bound violation. If d + M is at most R·dt, multiple increments are admissible; reject ambiguity. Otherwise accept d and compute the interval-average rate d/dt. A falling value then represents one unique wrap; a rising value represents unique growth without a wrap. This does not identify the instantaneous rate inside the interval.

Use an actual upper bound in counts per second, accounting for counting edges, scaling and operating modes—not a typical historical rate. If a burst process needs an allowance B, use a justified envelope such as B + R·dt and re-test the uniqueness rule. Too small a bound rejects valid production; too large a bound admits more ambiguity. Clock uncertainty must expand the elapsed-time envelope conservatively for the admissibility test and qualify the reported rate. The fixture deliberately assumes exact integer acquisition seconds.

For its eight-bit modulus of 256 and bound of 20 counts/s, 250 → 4 in one second admits only 10 counts. Plain subtraction gives −246. Across thirty seconds the same endpoints admit 10, 266 or 522 counts: modulo arithmetic alone cannot choose. Even 10 → 20 across that gap is ambiguous. A sufficient general uniqueness condition is R·dt < M; here dt must be less than 12.8 seconds. That is not a universal polling recommendation: source capability, uncertainty and freshness impose additional limits.

Decision table: feature validity before numerical output

EvidenceFeature decisionBaseline action
Same epoch; exactly one deltaEmit delta and interval rateAdvance to valid endpoint
Epoch changedUnavailable: discontinuityStart valid new epoch
Missing epoch or bad qualityUnavailable: untrusted inputClear; validate a new baseline
Duplicate or reversed timeUnavailable: nonforward timeKeep prior baseline
More than one possible deltaUnavailable: ambiguous gapAdvance; do not fill lost interval
No delta within rate boundUnavailable: bound violationClear; investigate contract

A valid zero needs the same checks as a nonzero result. Unchanged endpoints across a short bounded interval may mean zero increments; unchanged endpoints across a sufficiently long interval may conceal a full revolution. At an allowed budget of exactly one modulus, zero and one complete wrap are both possible. The implementation tests that equality boundary explicitly.

Implement the gate as state, not a dataframe shortcut

1. Partition by asset lifecycle and counter channel. Validate integer range, width, quality, clock identity and continuity metadata before subtraction. Do not convert a wide raw counter through floating point and then cast it back; lost low-order increments cannot be restored. Bind policy and source schema versions to stored state.

2. Establish a first valid observation as a baseline without emitting a rate. Compare subsequent observations in acquisition order. In this fixture, a duplicate or older timestamp is rejected and does not replace the baseline. Production ingestion also needs event identity and a conflict policy for different values bearing the same timestamp; quarantine the conflict rather than treating it as a legitimate extra sample.

3. On a documented epoch change, emit discontinuity and establish a new baseline from the valid new-epoch observation. Do not estimate the missing production across reset. On a long but otherwise valid gap, emit ambiguity and allow its endpoint to become the baseline for the next interval. The rejected gap remains unavailable even if the next interval succeeds.

4. On invalid quality, unknown epoch, changed clock/width or an impossible increment, clear continuity state and require a validated fresh baseline. This conservative policy reduces availability but avoids chaining later calculations through an untrusted sample. A production wrapper must validate even the first sample; the small fixture's baseline branch assumes an already-validated input envelope.

5. Persist output and baseline consistently with source offsets. Include both endpoint references, interval boundaries, delta, rate, validity reason and policy version. Checkpoint/restore and concurrent writers require integration tests beyond this in-memory class. A process restart must not convert uncommitted history into an invented uninterrupted interval.

Late-data revision is a separate problem. The feature-finalisation contract determines whether an old observation can revise a window. Replaying a counter trace should produce a versioned reconciled result, not silently replace what an earlier model actually consumed or replay a maintenance action.

Executed mutation suite and reset–wrap–gap timeline

The run used Python 3.14.9, exact integer arithmetic for admissibility and rational arithmetic for reported fixture rates. Fourteen pair cases passed: growth, wrap, reset, duplicate timestamp, out-of-order timestamp, long gap, a rising counter hiding wraps, bound violation, missing epoch, bad quality, changed clock, changed width, invalid range and an unchanged value. Two additional assertions checked the exact one-modulus ambiguity boundary.

An exhaustive small-domain oracle independently enumerated every allowed increment for bit widths one through four, all endpoint values and budgets from zero through twice the modulus. All 9,700 comparisons matched the constant-time decision rule. This checks the arithmetic over that finite domain, not the trustworthiness of real device metadata. The retained fixture.py and fixture-results.json record the implementation and outcomes.

Time; value; epochExecuted resultDelta
0 s; 250; AInitial baseline—
1 s; 4; AUnique wrap10
1 s; 7; ADuplicate time rejected—
2 s; 14; AGrowth from previous valid value 410
3 s; 2; BReset; establish new baseline—
4 s; 12; BGrowth within new epoch10
34 s; 22; BLong gap; ambiguous—
35 s; 32; BNext short interval valid10

This timeline is one eight-observation state test. The conflicting observation at t=1 does not poison the t=2 calculation. The reset at t=3 breaks the old interval but allows a fresh delta at t=4. The gap ending at t=34 remains unresolved; the next short interval can be valid without retroactively repairing that gap. Tests use synthetic counts, not measured parts or maintenance outcomes.

Prometheus rates answer a different question

The Prometheus metric-type documentation defines a counter as monotonically increasing except for resets to zero on restart. Its query-function documentation explains that rate and increase adjust breaks in monotonicity; increase extrapolates over the requested range and can return non-integer values even for integer increments.

Those functions are useful for observability. They are not proof that a falling finite-width hardware register wrapped rather than reset, nor an exact ledger of business events. Do not feed an unqualified wrapping register into a counter series and assume reset adjustment reconstructs device semantics. Normalise and validate at the adapter boundary, expose validity and discontinuity metrics separately, and keep exact accepted increments in a suitable durable record if reconciliation requires them. This article checked the documentation; it did not execute a Prometheus server or compare runtime query results.

QuestionSuitable evidenceImportant limit
Average accepted interval rateUnique delta divided by elapsed timeNot an instantaneous rate
Service activity trendPrometheus rate or increase on valid countersReset adjustment and extrapolation
Exact accepted incrementsDurable validated interval recordsMissing intervals remain unresolved
Production quantityValidated event-to-product mapping and reconciliationRaw pulses alone are insufficient

Release checklist and operational cost

Before release, require the register specification, reset/rollover behavior, coherent metadata acquisition, maximum increment envelope and clock uncertainty budget. Reproduce normal growth, wrap, operator reset, reboot, duplicate delivery, timestamp conflict, reconnect gaps and metadata loss. Then test crash recovery, source-offset replay, policy upgrades and device replacement on the actual adapter. Preserve rejected intervals and their reasons; a zero rejection rate can mean missing validation rather than excellent data.

Monitor valid-interval coverage, ambiguous-gap duration, discontinuities and bound violations with explicit denominators. Store detailed sample references in governed evidence, not high-cardinality metric labels. Strict rejection costs feature availability and may require abstention; more frequent acquisition costs bandwidth and state writes. A wider counter reduces wrap ambiguity but cannot resolve resets, acquisition faults or uncertain identity.

Keep this issue separate from waveform downsampling and anti-aliasing. That article concerns frequency information lost while reducing a waveform's sample rate. Here the decision is whether two cumulative observations identify a unique increment at all. Neither a smoother graph nor interpolated missing rows supplies the lost evidence.

For an implementation review, bring one counter register specification, its reset metadata and a raw reconnect trace. I can help turn them into an executable admissibility gate and a feature-consumer contract that distinguishes measured zero, unavailable rate and unresolved production totals before a model is allowed to act on them.

#enterprise-ai#industrial-ai

Building AI into your operations?

I help teams design and ship compliant AI automation — production agents with n8n and LangGraph, RAG systems, and the evals to keep them reliable.

A

Written by

Ade Christanto

AI Automation Specialist and former network engineer focused on practical AI implementation for German B2B and Mittelstand companies.