Test iOS feature flags with stable buckets and snapshots

Test iOS feature flags with stable buckets and snapshots

The same iOS app package can open different screens after a test node restarts. The problem may lie not in the build, but in the feature flags: user bucketing may be unstable, or a single operation may read two different configuration versions. Setting every flag to “on” only exercises the new path; it does not prove that a gradual rollout works correctly. The following workflow uses cloud Macs to establish a stable bucketing contract, then checks configuration updates and account changes.

Define the contract

Start by separating flag evaluation into three layers: whether the configuration is valid, whether the current identity qualifies, and which configuration version the business operation uses. Record each conclusion separately in the test report, rather than saving a single Boolean.

For each flag, define a namespace, a stable user identifier, a salt, and an algorithm version. For anonymous users, use a persistent installation identifier; do not generate a new one on every launch. Whether signing in switches the input to an account identifier must also be an explicit rule.

This article represents rollout proportions using integer buckets 0...9999, with thresholds in 0...10000. The inclusion rule is always bucket < threshold. Increasing the threshold must preserve the previously included set. Changing the salt reshuffles assignments and must not be treated as an ordinary rollout expansion.

Stable bucketing guarantees the same result for the same input. It does not guarantee that the number of included users in a small sample will exactly match the target percentage. Do not judge the algorithm by the inclusion rate of a dozen or so test accounts.

Freeze the byte representation

Do not use Swift’s hashValue: it is not guaranteed to remain stable across processes. Nor is joining strings with a delimiter sufficient, because the fields themselves may contain that delimiter. Here, each field is encoded as “length, colon, content,” using its UTF-8 byte length and a fixed field order.

Save the following as flag-contract.swift. The code uses frameworks from the system SDK and requires no dependency downloads. The node should already have its development tools initialized.

import Foundation
import CryptoKit

func encode(_ fields: [String]) -> Data {
    var result = Data()
    for field in fields {
        let bytes = Data(field.utf8)
        result.append(contentsOf: "\(bytes.count):".utf8)
        result.append(bytes)
    }
    return result
}

func bucket(_ data: Data) -> Int {
    let digest = SHA256.hash(data: data)
    let prefix = digest.prefix(4).reduce(UInt64(0)) {
        ($0 << 8) | UInt64($1)
    }
    return Int(prefix % 10_000)
}

func enabled(bucket: Int, threshold: Int) -> Bool {
    precondition((0..<10_000).contains(bucket))
    precondition((0...10_000).contains(threshold))
    return bucket < threshold
}

func check(_ condition: Bool, _ name: String) {
    guard condition else {
        fatalError("Contract failed: \(name)")
    }
}

check(
    encode(["qa", "用户"]) == Data("2:qa6:用户".utf8),
    "utf8-length"
)
check(
    encode(["ab", "c"]) != encode(["a", "bc"]),
    "field-boundaries"
)
check(bucket(Data("abc".utf8)) == 2319, "sha256-prefix")

let input = encode(["checkout-v1", "test-user-42", "salt-v1"])
let assigned = bucket(input)

for value in 0..<10_000 {
    check(!enabled(bucket: value, threshold: 0), "zero")
    check(enabled(bucket: value, threshold: 10_000), "full")
    check(
        enabled(bucket: value, threshold: 1) == (value == 0),
        "first-bucket"
    )
    check(
        !enabled(bucket: value, threshold: 2500)
            || enabled(bucket: value, threshold: 5000),
        "monotonic"
    )
}

check(!enabled(bucket: 2500, threshold: 2500), "exclusive-boundary")
print("contract=pass bucket=\(assigned)")

Run xcrun swift flag-contract.swift and retain the output and exit code. Repeat the run on different nodes and in different processes: a fixed identity must always produce the same bucket number. The code interprets the first four bytes of the digest as a big-endian integer, then applies the modulo operation. This is a traffic allocation rule, not an exact quota allocator or an access-control mechanism.

If the other implementation uses a different byte order or Unicode normalization scheme, even text that looks identical may map to different buckets. Use identifiers agreed upon by both sides for test identities. Do not independently lowercase, strip spaces from, or normalize identifiers on the client.

Freeze the snapshot

Flag decisions must not change from one read to the next during a business operation. When a user starts checkout, capture an immutable snapshot containing at least the configuration version, identity generation, bucket number, and final decision. Subsequent screen rendering and request parameters must use that snapshot, rather than querying the global configuration again.

Control test timing with a fake configuration source that can be advanced manually, rather than relying on sleeps:

  1. Publish configuration A, let the operation capture a snapshot, and pause it at a controllable wait point.
  2. Publish configuration B, changing the decision for the same flag.
  3. Release the wait point and confirm that the current operation still uses A.
  4. Start the next operation and confirm that it uses B.

Fully decode the configuration and validate its thresholds and version before replacing the active configuration atomically. Invalid thresholds must not be silently clamped. Explicitly define and test whether a parsing failure retains the last valid version or falls back to the off state, based on the flag’s risk profile.

Isolate identities

Account changes create another asynchronous boundary. Add an incrementing generation counter to the identity context: increment it on sign-out or account changes, then compare generations when an old request returns. Discard the result if they do not match. Clearing the flag cache in the UI is not enough.

Set up three deterministic scenarios: signing in while an anonymous request is pending; switching from account A to B while A’s request is pending; and an old configuration request returning after sign-out. In each scenario, confirm that the old result does not overwrite the new identity’s state and that the next operation reevaluates the flag using the new identifier.

Two identities landing in the same bucket is a normal collision. Do not assert that changing accounts must change the bucket. The correct assertions concern the input identity, generation, and which identity the configuration belongs to. Use synthetic accounts in reports; do not record real user identifiers or sensitive fields from the full configuration.

Enforce the gate

Use the pure bucketing tests as a fast check, then add the snapshot and identity scenarios to the app’s test target. Run at least one test of the shared implementation on iOS to guard against a correct script paired with an app that has copied a different algorithm. Across nodes, record the commit ID, toolchain version, and a digest of the configuration sample.

Define emergency shutdown behavior separately: ordinary rollout updates affect only subsequent operations; an emergency shutdown can prevent new side effects, but a local flag cannot undo requests that have already been submitted. Use pause points to verify that “the next write request is not sent after shutdown,” rather than claiming to cancel completed writes.

Before merging, check four things: fixed test vectors match, threshold boundaries are correct, configuration replacement never exposes a mixed state, and results from an old identity cannot write back. Any failure must report the corresponding contract name and block the merge, rather than being rerun until it happens to pass. This ensures that adding nodes only increases execution scale, without changing the rollout decision itself.

Frequently asked questions

Can Swift hashValue assign users to rollout buckets?

No. hashValue is not stable across processes. Specify the input fields, UTF-8 encoding, hash algorithm and bucket calculation, then verify fixed vectors.

Will increasing the rollout percentage remove existing users?

Not when identity, salt and hashing stay unchanged and eligibility uses bucket < threshold. Changing the salt or identity fields can reassign users.

Run tests in parallel across multiple nodes

Choose a dedicated physical Mac mini for your workload. Rent by the day, with no renewal when the term ends. Check the model and node before scheduling regression tests.

Prepare for the next test run

Check the model and connection steps, then assign the test tasks.