Test iOS Bluetooth fragment reassembly: retries, order and timeouts
Just before a release, a long message from a peripheral occasionally arrives with a chunk missing, yet the app still reports “Sync successful.” What you need first is a set of tests that reliably reproduces missing fragments, retransmissions and timeouts—not another round of reconnecting the device and hoping to catch the problem. On a cloud Mac, extract the message reassembly logic that runs after Bluetooth callbacks into a pure Swift type. Every regression run can then use the same inputs and compare the results directly.
Define the fragment contract—notifications are not messages
A Bluetooth notification boundary does not necessarily match an application message boundary. Before deciding how to assemble fragments, agree on a transfer ID, total length and byte offset between the app and firmware. This example uses strictly ordered delivery: each new fragment must start at the current end of the buffer. Only exact retransmissions of complete, previously accepted fragments are allowed.
The total length must be between 1 and 4096 bytes, and empty fragments are rejected. Partial overlaps, gaps in offsets and changed content at an existing offset are all errors. This limit is the example protocol’s size budget, not a Bluetooth payload limit. Derive the actual fragment size from the current link’s capabilities and protocol header overhead rather than hard-coding a commonly used value.
This article validates the application-layer reassembly contract; it does not simulate wireless transport. Connections, notification subscriptions, disconnections, reconnections and actual throughput still need acceptance testing on a physical iOS device with the peripheral.
Implement a reassembler with a size budget and deadline
Save the following as Reassembly.swift. It depends only on Foundation and runs on a cloud Mac with the Swift toolchain installed. Each instance handles one transfer, with the outer layer routing fragments by transfer ID. All calls must run serially; do not mutate the instance directly from multiple concurrent callbacks.
import Foundation
enum AssemblyError: Error {
case invalidHeader, expired, invalidFragment
}
struct Assembly {
let total: Int
let deadline: TimeInterval
private(set) var data = Data()
private var accepted: [Int: Data] = [:]
init(total: Int, now: TimeInterval, ttl: TimeInterval) throws {
guard (1...4096).contains(total),
now.isFinite, ttl.isFinite, ttl > 0,
(now + ttl).isFinite else {
throw AssemblyError.invalidHeader
}
self.total = total
self.deadline = now + ttl
}
mutating func append(
offset: Int, bytes: Data, now: TimeInterval
) throws -> Data? {
guard now.isFinite, now < deadline else {
throw AssemblyError.expired
}
guard offset >= 0, offset <= total,
!bytes.isEmpty,
bytes.count <= total - offset else {
throw AssemblyError.invalidFragment
}
if let previous = accepted[offset] {
guard previous == bytes else {
throw AssemblyError.invalidFragment
}
return nil
}
guard data.count < total, offset == data.count else {
throw AssemblyError.invalidFragment
}
accepted[offset] = bytes
data.append(bytes)
return data.count == total ? data : nil
}
}
var receiver = try Assembly(total: 4, now: 100, ttl: 5)
let first = try receiver.append(
offset: 0, bytes: Data([1, 2]), now: 101
)
assert(first == nil)
let duplicate = try receiver.append(
offset: 0, bytes: Data([1, 2]), now: 102
)
assert(duplicate == nil)
let complete = try receiver.append(
offset: 2, bytes: Data([3, 4]), now: 104
)
assert(complete == Data([1, 2, 3, 4]))
assert(receiver.data.count == 4)
Run swift Reassembly.swift. It exits silently on success. The code validates the offset before calculating the remaining length, avoiding potentially overflowing addition on untrusted input. Duplicate fragments neither advance the position nor cause the complete message to be delivered again. The outer layer should remove the instance as soon as it receives a non-nil result.
Test failure boundaries with fixed timestamps
Do not make the tests actually wait five seconds. In production, pass a reading from a monotonic clock, such as ProcessInfo.processInfo.systemUptime; in tests, pass fixed values directly. The deadline is calculated when the first fragment establishes the transfer. Duplicates must not extend it, or a device could keep a session alive indefinitely by retransmitting.
Append these boundary tests to the same file:
var timed = try Assembly(total: 2, now: 100, ttl: 5)
do {
_ = try timed.append(
offset: 0, bytes: Data([1]), now: 105
)
fatalError("Expected expiration")
} catch AssemblyError.expired {
}
var ordered = try Assembly(total: 4, now: 100, ttl: 5)
do {
_ = try ordered.append(
offset: 2, bytes: Data([3, 4]), now: 101
)
fatalError("Expected order rejection")
} catch AssemblyError.invalidFragment {
}
assert(ordered.data.isEmpty)
Add separate cases for a total length of zero or over budget, a negative offset, an empty fragment, a final fragment that exceeds the declared length, different content at the same offset, and an overlapping fragment starting at offset one after two bytes have already been received. Create a fresh instance for each case, assert the specific error type, and verify that the failure leaves the accepted data unchanged. Do not merely assert that “some error occurred”: a mistake in the test setup could otherwise count as a passing test.
Isolate connection generations when integrating Bluetooth callbacks
The receiving layer must first parse the complete protocol header and check that its length field can be safely converted to Int, then call the reassembler. This example does not include header parsing, so arbitrary notifications must not be passed straight in as valid fragments.
If a single connection supports multiple simultaneous transfers, the lookup key must include at least the connection generation and transfer ID. Clear the old generation on disconnection. Even if a new connection reuses an ID, callbacks from the old connection must not write into the new session. For rejected input, the recommendation here is for the outer layer to discard the entire transfer and wait for an explicit new transfer to begin, rather than guessing how to resume.
The reassembler has no background timer. The outer layer must periodically remove expired instances and release their buffers even if no more fragments arrive. Also cap the number of concurrent sessions and the total buffer budget: limiting the size of one message does not make it safe to create unlimited instances.
Connect offline results to physical-device evidence
Start by fixing the fragment bytes, order and timestamps in your cloud Mac automation. For failures, logging the transfer ID, offset, length and error category is enough. Do not save complete application payloads by default. Add these cases to the test target, then verify successful assembly, strict rejection of out-of-order fragments, no buffer growth on retransmission, and immediate invalidation at the deadline.
On physical hardware, check that the firmware really follows the strictly ordered delivery contract, record the negotiated fragment size, and test cleanup when disconnection occurs at the first, middle and final fragments. If the device explicitly supports out-of-order delivery, implement a separate protocol that tracks covered byte ranges; do not simply remove the offset check.
Acceptance is complete when every failure has a fixed input, every buffer has a release path, and each complete message is delivered exactly once. New problems found over the air should likewise be reduced to fragment sequences before becoming part of routine regression testing.
Frequently asked questions
Can offline tests replace Bluetooth tests on an iOS device?
No. They verify reassembly rules. Connection handling, subscriptions, negotiated payload limits and radio interference still require an iOS device and peripheral.
Should every duplicate fragment cause an error?
That depends on the protocol. This example accepts an identical fragment at the same offset without advancing the receive position. Changed content and overlaps are rejected.
A dedicated Mac for every test lane
Rent a full physical Mac mini by the day, week, month, or quarter, with isolated test environments. Track setup progress in the console; service stops at the end of your term unless you renew. Submit a support ticket in the console if you need help.
Rent a Cloud Mac