Pattern 1: Access Synchronization¶
When to Use¶
Your device supports offline access control (stores credentials, schedules, access levels locally).
access-model.yaml Structure¶
Define entities in dependency order (leaves first):
model:
# Layer 0 - leaves (no dependencies)
- type_id: Schedule
updatable: inplace
properties:
address: uint
periods: SchedulePeriod[]
range: [1, 255]
# Layer 0 - embedded in Schedule
- type_id: SchedulePeriod
properties:
day_mask: uint
start_time: uint
end_time: uint
# Layer 1 - references Schedule
- type_id: AccessLevel
updatable: inplace
properties:
address: uint
door_schedules: DoorSchedule[]
range: [1, 32000]
# Layer 1 - embedded in AccessLevel
- type_id: DoorSchedule
properties:
door_id: uint
schedule: Schedule # object reference, resolved at command time
# Layer 2 - root (references AccessLevel)
- type_id: Cardholder
properties:
card_number: uint
access_levels: AccessLevel[] # explicit entity references
valid_from: uint
valid_until: uint
Key rules:
- Tracked entities have
addressproperty (stored in mapping DB) - Embedded entities have no
address(nested in parents) - Define
rangefor address allocation - Cross-entity references MUST use object references (
EntityName/EntityName[]), not address integers (see pitfall below)
Person Profiles¶
Use person_profiles when the device requires per-person settings that are not
credentials and are not access grants. Typical examples are alarm user level, menu
type, group-selection permission, dual-code mode, bypass permissions, or similar
panel-specific user flags.
Declare profile fields in access-model.yaml next to model:
model:
- type_id: User
properties:
address: uint
name: string
pin: string
user_level: int
can_select_group: bool
range: [1, 999]
person_profiles:
- slot_type: User
fields:
- name: user_level
type: int
default: 0
range: [0, 3]
category: alarm
description: "Alarm user level"
- name: can_select_group
type: bool
default: false
category: alarm
description: "Allows group selection"
- name: menu_type
type: enum
values: ["Quick", "Full"]
category: alarm
description: "Panel menu: Quick or Full. When not set, the panel gets Quick."
Profile fields use the same property shape as device properties where applicable:
type, required, default, range, pattern, category, description, and
sensitive.
A closed set of choices is type: enum with a values: list and no default:. The
operator picks one value in the person's profile; the generated profile property is a
string? holding the chosen value, null when nothing is chosen. The adapter maps the
value to the panel's code and applies its own default for null or an unknown value:
private static int ResolveMenuType(string? value) => value switch
{
"Full" => 1,
_ => 0, // Quick — also when the operator chose nothing
};
State the default in the field description, so the operator sees what an empty choice
means.
The source generator creates one typed profile record per slot_type, named from the
adapter and slot type, for example VendorPanelUserProfile. YAML defaults become
property initializers. Required profile fields are validated by the generated mapper
before Transform() runs.
When profiles are declared, the generated Transform signature uses generated access
input:
protected override AccessModel.AccessModel Transform(AccessModel.PersonAccess[] persons)
{
foreach (var person in persons)
{
var profile = person.UserProfile;
var user = new AccessModel.User(
Name: person.Name,
UserLevel: profile?.UserLevel ?? 0,
CanSelectGroup: profile?.CanSelectGroup ?? false);
}
}
Do not parse raw profile JSON in adapter code. The generated typed profile on
person is the supported adapter API. Profile data is per person for the current
adapter transform; do not try to select a different profile from individual devices.
Selective Sync Ownership: Person-Owned Roots vs Shared Tables¶
Selective sync synchronizes only a subset of persons. To do that safely it must know, for each allocator-addressed entity (address + range, no id), whether a record belongs to one specific person or is a shared table that many persons reference. The framework infers this from the model's reference graph — you write nothing:
- An entity that is the target of any entity-typed property anywhere in the model — directly (
Schedule,AccessLevel?,Door[]) or through an embedded type (DoorSchedule.schedule: Schedule) — is a shared derived table. - An entity that nothing references is a person-owned root.
Plain-language test:
- Person-owned root — "the record exists because of a specific person and disappears with them" (a cardholder / user slot).
- Shared — "a derived table persons merely reference" (a schedule, access level, holiday, door).
What each kind does during selective sync¶
- Person-owned roots pair by person, as a set.
Transform()mustResolveAsthe person on every root record — and the credential as well when the record is per-credential (one panel record per card / PIN). The person is the unit of exchange: all of a selected person's stored records are re-paired against all of their desired records, so records whose content is unchanged keep their own panel address, changed records take over the remaining ones, and only a genuine surplus is deleted. A person whose credential set grows or shrinks therefore reshapes their existing records instead of leaving the previous card/PIN active on the panel next to the new one. The resolved credential does not pair records; it attributes an uploaded record to a credential in sync reporting. - Shared tables are additive-only during selective sync and must never resolve a person. Resolving a person on a shared-table record is a projection error; the framework rejects such a record rather than uploading it.
This resolution obligation is enforced as RULE-056.
The optional owner override¶
owner: person | shared in access-model.yaml is an optional override of the inference, for exceptional models only — a model with more than one legitimate person-owned root, or a genuinely unreferenced shared table. Normal models declare nothing; the author never has to reason about ownership.
The generator warns when it infers more than one root, because the usual cause is a real relationship flattened into an integer or bit mask (see RULE-040), which orphans a shared table into a false root. Fix the flattened relationship first; reach for owner: only when the multiple roots are genuinely intended (declaring owner: person on each silences the warning). Any explicit owner: declaration is exceptional by definition and is always audited at review.
Natural-id entities (id: <property>) must not declare owner.
First-ever selective sync¶
The very first selective sync on a device runs as a full sync until the device store is initialized. Until the framework has the complete panel picture it cannot safely diff a subset, so the first run synchronizes everything; once the store is initialized, later runs honor the selected subset.
PQ owns its address range; synchronization does not read records back¶
Within the access-model.yaml ranges the device holds what PQ wrote there, and nothing else counts:
- The initial cleanup (first sync, reset) empties the range. From then on the mapping store is the complete picture of the range.
- A normal synchronization writes only the difference between the desired state and the mapping store. It never reads record content back to verify it. A read-back would roughly double the synchronization time and find nothing the store does not already know.
- An interrupted synchronization leaves no hidden state. The store records every confirmed write, so a person whose records were not written still shows the grant as not uploaded, and the next synchronization writes them. A write whose confirmation was lost is sent again to the same address with the same content.
- A record changed outside PQ (keypad, installer software) inside the range is not PQ's concern. PQ overwrites it at the next write to that address; a reset rewrites the whole range.
Do not add a read-back or "consistency check" of record content to a synchronization. A device-specific read before a write is valid only when it protects a record PQ must not overwrite (for example a technician record in the range).
Address Ownership Contract (Critical)¶
Address is framework-owned state for diffing. Treat it as write-once sync metadata.
Transform()MUST construct entities withAddress == null.- Never call
SetAddress()insideTransform(). - Never read
entity.AddressinsideTransform()to build references. - Never encode tracked-entity references as raw address integers when object references are available.
SetAddress()in adapter code is valid only for true device-assigned flows (device response returns the address).- Predefined built-in device records may be address-pinned only when the model handles them explicitly so the differ will not reassign or duplicate them.
If this contract is broken, repeated sync can fail with InvalidOperationException: Address already assigned when differ processes UNCHANGED entities.
Implementation¶
Create Capabilities/AccessSynchronization.cs by inheriting the generated AccessSynchronizationBase. The generated base supplies synchronization orchestration and command dispatch; the adapter normally implements only Transform(...) and protocol command objects.
The generated base exposes one device-memory cleanup hook:
protected virtual IEnumerable<IProtocolCommand> ClearDeviceMemory(
IReadOnlyList<OccupiedDeviceMemory> occupied, bool initialCleanup) => [];
The framework calls it in the initial cleanup: the first full sync of a device whose mapping store is not initialized. pq.command.access.synchronize.reset clears the mapping store and its initialized flag, then runs that same full sync, so reset and first sync share one cleanup path:
- build
occupiedwith the fullaccess-model.yamladdress range of every range-based entity type (id-based types get an empty group), ordered for delete (roots -> leaves) - execute every command from
ClearDeviceMemory(occupied, initialCleanup: true) - all commands succeeded → mark the device initialized, upload holidays and entities
- any command failed → end the sync as Failed (summary reason
InitialCleanupFailed, eventpq.event.access.synchronization.failed); the device is not marked initialized and nothing is uploaded
Override this method when the device keeps credentials from a previous system or from an earlier adapter instance.
Clear command contract:
- A clear command throws only when the device was not cleared.
- A record that does not exist, or a slot that is already empty, is success. Do not throw for it.
- Do not catch and swallow protocol errors. A swallowed failure marks a dirty device as clean, and PQ never removes what it left behind.
- A connection loss (
ConnectionError, timeout, I/O error) stops the cleanup at once; the framework resumes the sync after reconnect. - Any other failure ends the sync as Failed after all clear commands ran. The framework does not resume it; the operator re-runs the sync or reset after fixing the cause.
To distinguish mixed address spaces, route by group EntityType (not numeric ranges). Each group carries Slots (IReadOnlyList<AddressMapping>) for one type, and groups are already emitted in delete-oriented order (roots -> leaves), so adapter code does not need to compute type ordering.
Choose one clear strategy per adapter reset path: either authoritative bulk wipe or targeted delete from occupied. Avoid naive combination of both unless the protocol explicitly guarantees idempotent delete-after-wipe behavior.
Shared objects of protected users stay (RULE-061). The initial cleanup also deletes schedules/time zones and groups. It must keep those that a protected user (installer, master, technician — a slot GetReservedDeviceMemory returns) still references. Read those references before the cleanup and skip the delete for them. If the device still refuses a delete because the object is in use, log the object and skip it: the clear command returns success for that object, and the cleanup does not abort.
Holiday dates are installation-wide. The configured PQ holiday calendar defines which dates are holidays for the installation. Configure it for the installation before synchronization. The adapter may replace the device's shared holiday dates; they do not need position reservations for another system. Keep a protected user's referenced schedule or other object that selects or interprets holidays, and preserve its meaning. See RULE-061.
Vendor Configuration Tool Overwrites the Device¶
A vendor configuration tool can write its own full configuration to the device. It can replace users, credentials, the integration account and partitions or doors that the adapter wrote. The mapping store then describes a device that no longer exists, and an incremental sync writes against wrong slots. Intake asks the vendor whether the tool does this and how the device signals it (_intake-shared-doctrine.md, "Standard vendor question"). If the device signals it (a history row, a configuration version or change counter), the adapter detects the signal and runs pq.command.access.synchronize.reset. If the device gives no signal, the adapter CLAUDE.md states that an operator runs the reset after every save from the vendor tool.
Evidence (Dominus, lab 2026-11-13): one save from the vendor tool removed all ~990 PQ users and cards, changed the API account password, and removed partitions.
The Synchronized Device¶
Every step of a run (BeforeTransform, Transform, TransformHolidays, GetReservedDeviceMemory,
ClearDeviceMemory, AfterTransform and the entity commands, whose context is the synchronization
instance) can read SynchronizedDevice: the device Thing the run synchronizes, typed as the device type
that carries AccessSynchronization. Do not copy the device or values derived from it into a field.
// write to the RS485 address of the module this run synchronizes
private byte TargetAddress => SynchronizedDevice.Address;
The command dispatcher creates a new synchronization instance for every sync or reset command, so the
reference lives for one run. SynchronizedDevice is set when the run starts; outside a run it is null.
Device State Around Transform¶
Transform() is synchronous and does no I/O. If its output depends on device state (for example
the PIN length the panel accepts), read that state in BeforeTransform and store it in a field.
private PinMode? _pinMode;
protected override async ValueTask<bool> BeforeTransform(CancellationToken cancellationToken)
{
_pinMode = await protocol.ReadPinSettings(cancellationToken);
return _pinMode.HasValue;
}
The generated base calls the two hooks in this order:
BeforeTransform(ct)runs before the sync reads authorizations and before any write to the device.Transform(persons)builds the device model.AfterTransform(accessModel, ct)runs before the diff and before any write to the device.
Both hooks return true by default. If a hook returns false, the sync fails as "device not ready"
and nothing is written to the device. If your adapter can work without the value, handle the failed
read inside the hook and return true.
Multi-Credential Projection And Determinism (Critical)¶
When a person has multiple credentials of supported types, Transform() must project all supported credentials, not only the first one.
The wire types are Pin, PersonCard, Biometric and LicensePlate, and every enabled credential of
an authorized person is shipped to every device in the access model — there is no per-device filtering
by type. Filter on CredentialEntry.Type and ignore what the hardware cannot store. For plates see
concepts/license-plate-credentials.md.
Rules¶
- Never use
FirstOrDefault()as the only source for a credential type that can appear multiple times. - Iterate persons in deterministic order (for example by
PersonId). - Iterate each supported credential type in deterministic order (for example by
CredentialId, then value-specific secondary key). - If one device record carries multiple credential fields, use a deterministic index-based projection strategy.
- Process leftover credentials deterministically according to the device model.
- Never rely on incidental source enumeration order.
Deterministic ordering (critical)¶
Transform() output must be stable for identical input to avoid incremental-sync churn.
Anti-pattern: unsorted person or credential iteration that can reshuffle equivalent mappings between sync runs.
Record Shape Selection¶
Before projecting, decide the record shape from the panel record's credential capacity, not from what the record is called (RULE-055):
- Person-root — the panel person record carries credential lists (multiple identifiers of a type per record, e.g. an array of cards): emit one record per person embedding all of that person's credentials.
- Credential-root — the panel record carries fixed single-credential fields (one card slot, one code): fan out one record per credential using the stable pairing below.
A record named user may be either — read its capacity. Modeling person-root over a fixed-capacity record (taking one credential and dropping the person's remaining credentials of that type) is a violation.
Stable Pairing Example (cards[] + pins[])¶
For sorted arrays cards[] and pins[]:
- Create paired records for
i < min(cards.Length, pins.Length):cards[i] + pins[i] - Create card-only records for remaining cards
- Create pin-only records for remaining pins
This is one model-specific example. Apply the same deterministic projection principle to other credential sets (including biometrics) based on the device record shape.
Identity Mapping¶
Each produced record must resolve identities that were actually projected into it:
- paired record:
ResolveAs(person) + ResolveAs(cardCredential) + ResolveAs(pinCredential) - card-only record:
ResolveAs(person) + ResolveAs(cardCredential) - pin-only record:
ResolveAs(person) + ResolveAs(pinCredential)
Do not attach unrelated credentials to a projected record.
namespace Pq.Adapter.Vendor.Product.Capabilities;
/// <summary>
/// Transforms PQ access model to device-specific entities.
/// </summary>
internal sealed class AccessSynchronization(Protocol protocol) : AccessSynchronizationBase
{
public Protocol Protocol => protocol;
/// <summary>
/// Transform PQ PersonAccess to device-specific access model.
/// </summary>
protected override AccessModel Transform(PersonAccess[] persons)
{
var schedules = new List<Schedule>();
var accessLevels = new List<AccessLevel>();
var cardholders = new List<Cardholder>();
foreach (var person in persons)
{
var personAccessLevels = new List<AccessLevel>();
// extract schedules from person's device access
foreach (var deviceAccess in person.Devices)
{
var schedule = CreateSchedule(deviceAccess.TimeRestrictions);
schedules.Add(schedule);
var accessLevel = CreateAccessLevel(deviceAccess.DoorIds, schedule);
accessLevels.Add(accessLevel);
personAccessLevels.Add(accessLevel);
}
// create cardholder with credentials
var cardholder = CreateCardholder(person, personAccessLevels);
cardholders.Add(cardholder);
}
return new AccessModel(
Schedules: schedules.Distinct(),
AccessLevels: accessLevels.Distinct(),
Cardholders: cardholders
);
}
private Schedule CreateSchedule(TimeRestriction[] restrictions)
{
var periods = restrictions.Select(r => new SchedulePeriod
{
DayMask = ConvertDayMask(r.Days),
StartTime = (uint)r.Start.TotalMinutes,
EndTime = (uint)r.End.TotalMinutes
}).ToArray();
return new Schedule { Periods = periods };
}
private AccessLevel CreateAccessLevel(uint[] doorIds, Schedule schedule)
{
var doorSchedules = doorIds.Select(doorId => new DoorSchedule
{
DoorId = doorId,
Schedule = schedule // object reference, address resolved at command time
}).ToArray();
return new AccessLevel { DoorSchedules = doorSchedules };
}
private Cardholder CreateCardholder(PersonAccess person, List<AccessLevel> levels)
{
var card = person.Credentials.FirstOrDefault(c => c.Type == "card");
return new Cardholder
{
CardNumber = card != null ? ParseCardNumber(card.Data) : 0,
AccessLevels = levels.Distinct().ToArray(),
ValidFrom = (uint)person.ValidFrom.ToUnixTimeSeconds(),
ValidUntil = (uint)person.ValidUntil.ToUnixTimeSeconds()
};
}
}
Protocol Commands¶
Create Capabilities/ProtocolCommand.cs:
namespace Pq.Adapter.Vendor.Product.Capabilities;
/// <summary>
/// Wraps device SDK calls as IProtocolCommand for access upload.
/// </summary>
internal sealed class ProtocolCommand(Func<AccessSynchronization, CancellationToken, ValueTask> execute)
: IProtocolCommand
{
public async Task Execute(object context, CancellationToken cancellationToken)
{
if (context is not AccessSynchronization sync)
throw new ArgumentException("Expected AccessSynchronization context");
await execute(sync, cancellationToken);
}
}
Entity Command Methods¶
Implement IUploadProtocolCommands on generated entities:
// in Capabilities/Access/Schedule.cs
internal sealed partial record Schedule
{
public IEnumerable<IProtocolCommand> CreateCommands()
{
yield return new ProtocolCommand(async (sync, ct) =>
{
await sync.Protocol.AddSchedule(Address!.Value, Periods, ct);
});
}
public IEnumerable<IProtocolCommand> UpdateCommands() => CreateCommands();
public static IEnumerable<IProtocolCommand> DeleteCommands(uint address)
{
yield return new ProtocolCommand(async (sync, ct) =>
{
await sync.Protocol.DeleteSchedule(address, ct);
});
}
}
Holidays¶
ACS and alarm system protocols frequently support holiday calendars. Holidays are independent leaf entities (no dependencies) allocated from a device slot range — typically [1, 64] or [1, 255]. Schedules often reference holidays via a bitmask that overrides the normal weekly window when the day matches a holiday.
When the vendor protocol documents holiday slot write/delete commands, the entity must be fully implemented — stub CreateCommands() => [] is not acceptable (RULE-035).
access-model.yaml¶
# Layer 0 — holiday (leaf, no dependencies)
- type_id: Holiday
properties:
address: uint
day: uint
month: uint
range: [1, 64]
updatable: replace
# Layer 1 — schedule references holidays via mask
- type_id: Schedule
properties:
address: uint
periods: SchedulePeriod[]
holiday_mask: uint # bitmask of holiday types that override this schedule
range: [1, 64]
updatable: replace
If the device uses typed holiday groups (like an Acme
type_mask) rather than positional bitmasks, add atype_mask: uintproperty and wire it throughCreateCommands().
Holiday.cs¶
// in Capabilities/Access/Holiday.cs
public sealed partial record Holiday
{
/// <inheritdoc/>
public IEnumerable<IProtocolCommand> CreateCommands()
{
var addr = Address ?? throw new InvalidOperationException("Address not assigned");
yield return new ProtocolCommand<AccessSynchronization>(async (ctx, ct) =>
await ctx.Protocol.WriteHoliday(addr, Day, Month, ct));
}
/// <inheritdoc/>
public IEnumerable<IProtocolCommand> UpdateCommands() => CreateCommands();
/// <summary>Creates delete commands for the holiday at the given address.</summary>
/// <param name="address">Allocated holiday slot address.</param>
public static IEnumerable<IProtocolCommand> DeleteCommands(uint address)
{
yield return new ProtocolCommand<AccessSynchronization>(async (ctx, ct) =>
await ctx.Protocol.DeleteHoliday(address, ct));
}
}
Transform¶
Holidays are projected from DeviceAccessAuthorization.Holidays (provided by the framework). Each holiday maps to one entity instance:
protected override AccessModel.AccessModel Transform(AccessModel.PersonAccess[] persons)
{
var model = new AccessModel.AccessModel();
foreach (var holiday in Holidays)
{
model.AddHoliday(new Holiday
{
Day = (uint)holiday.Date.Day,
Month = (uint)holiday.Date.Month,
});
}
// ... cards, schedules, etc.
return model;
}
When holidays are not supported by the protocol¶
If the vendor protocol has no documented holiday slot write command, leave CreateCommands() => [] and document the gap explicitly in the adapter's design-notes:
## Known Implementation Gaps
- **Holidays:** Protocol does not define a holiday write command; holiday rows in Block 7
are always written as empty. Customers must pre-program holidays on the device directly.
Interrupted Synchronization and Restart (Critical)¶
A synchronization can stop at any point: the adapter process ends, or the link drops. The framework resumes it, but one gap stays for the adapter to close (RULE-062). Reference implementation: Dominus, Communication/Protocol.Leftovers.cs.
What the framework does¶
- It stores an entity's record after the entity's last command succeeds. Every entity is stored on its own, so a resumed run does not repeat an entity that is already stored.
- After a restart or a reconnect it resumes the interrupted synchronization by itself (log:
Resuming interrupted pq.command.access.synchronize on <device> (automatic attempt 1/3)). After three failed automatic attempts in a row an operator must start the synchronization. - The entity that was in flight runs again from its first command, on the same position.
The gap¶
The device stored the entity, and PQ did not store its record. The next run sends the same create again. The device already holds the record (a user on the slot, maybe some of its cards), so the create meets an existing record.
Decide per create command¶
| The device operation… | What the adapter does |
|---|---|
| writes onto a position (upsert: "write slot N") | Nothing. The repeated write overwrites the leftover. |
| only inserts and refuses a duplicate key ("already exists") | Handle the "already exists" answer as below. |
Find every key the device refuses as a duplicate. It can be the position (slot, IdExt), and it can also be a value the device keeps unique: a card number, a keypad code, a zone name. Check each one on the rig; do not guess it from the vendor docs (Dominus: a card number another user holds is refused, lab 2026-11-09; duplicate user numbers are accepted, lab 2026-11-07).
Store the device id with the record¶
When the device assigns its own id to a created object, return that id from the create with ProtocolCommand<TContext>.ReportingExternalId. The framework stores it with the record, and AccessSynchronizationFunction.ExternalIdOf(entityType, address) returns it. Only then can the adapter tell a leftover from a record PQ keeps:
- A leftover is a device object that is not protected, sits on a position inside the adapter's range, and the PQ record at that position does not name it (no record, or a record that names another device id).
- Every other holder is a record PQ keeps: a protected user (master, technician, system), an object outside the range, or an object the PQ record names.
On "already exists"¶
The refused key decides what the adapter may touch.
A credential value (card number, PIN, QR code). PQ owns every credential: when PQ assigns it to a person, the person gets it, whoever holds it on the device — a leftover, another PQ person whose device record is not yet updated, a user of another system, a master or technician user.
- Delete only the credential, by its value, in one call (Dominus:
RemoveUserIdentificatorByCardNumberAsync). Who held it does not matter, so do not read the device to find out. - Create the credential again. If the device still refuses it, let the create fail. Never swallow the second answer.
The holder keeps its position and every other record. A credential that moves between two persons in one run lands on the receiving person in that run.
A position (slot, user id the adapter allocates). The position belongs to the record PQ stores there, so here the holder matters.
- Read the record on the position from the device.
- Compare the key in the form the device reads it back. A device can store a key in another form than PQ uploads it (Dominus pads a card number with leading zeros to 20 characters:
9100006reads00000000000009100006). An exact string compare finds nothing. - If no record is found, throw an exception that names the position. Never treat a missing holder as success.
- If the record is one PQ keeps (protected, outside the range, or named by the PQ record), delete nothing and throw an exception that names it.
- Otherwise delete the leftover with its dependents, log it, and create again.
- If the PQ store cannot be read (the device disconnects), throw. A missing answer never counts as "no PQ record", so a record PQ keeps is never deleted.
Never swallow "already exists" on a create. A dependent record that the same command creates on the object it just created (a door grant, a partition right) cannot meet an earlier record and needs no handling.
Example¶
/// <summary>Creates a user; a leftover of an interrupted create on the slot is deleted first.</summary>
private async Task<long> CreateUser(uint slot, UserDetail user)
{
try
{
return await AddUser(user);
}
catch (AlreadyExists)
{
var owners = (await ReadAllUsers()).Where(u => u.Slot == slot).ToArray();
if (owners.Length == 0)
throw new InvalidOperationException($"Device refused slot {slot} as existing, yet no user holds it");
await RemoveLeftovers(owners, $"user slot {slot}");
return await AddUser(user);
}
}
/// <summary>Deletes the holders when all of them are leftovers; otherwise deletes nothing and fails.</summary>
private async Task RemoveLeftovers(DeviceUser[] holders, string held)
{
var kept = holders.FirstOrDefault(u => !IsLeftoverUser(u, IsProtected(u), StoredDeviceIdOf(u)));
if (kept is not null)
throw new InvalidOperationException($"{held} belongs to device user {kept.Id} (slot {kept.Slot}), which PQ keeps; nothing is deleted");
foreach (var user in holders)
{
await RemoveUserWithDependents(user.Id);
Logger.LogInformation("{Held} was held by device user {UserId} left by an interrupted synchronization; the user is deleted", held, user.Id);
}
}
/// <summary>Creates a card; PQ owns it, so a card another user holds is taken from that user first.</summary>
private async Task CreateCard(CardDetail card)
{
try
{
await AddCard(card);
}
catch (AlreadyExists)
{
await RemoveCardByNumber(card.Number);
await AddCard(card);
}
}
StoredDeviceIdOf reads ExternalIdOf and throws when the store cannot be reached. Keep IsLeftoverUser a pure static function with unit tests.
Verify on the rig¶
- Seed persons with every credential shape the adapter uploads: two cards, a PIN, one door without a schedule and one door with a schedule.
- Kill the adapter the moment the device confirms the create: on the trace line of the SDK answer (Dominus:
RX CreateUserAsync), not on the[sync] Add …line, which is logged before the command runs.lab teardownandtail -freact in about two seconds, and one person takes about 0.2 s, so the kill lands after the record is stored. Use a watcher that reads the trace every few milliseconds and stops the adapter process at once. This test is the one exception to "never force-kill the adapter". It is safe on a direct TCP or TLS link; do not run it through an RS232-to-TCP converter. - Start the adapter again. Expect the framework's
Resuming interrupted …line, the adapter's leftover line, andAccess synchronization completed: … 0 failed. Check in the sync dump that the person has every card, the PIN and both door grants. - Move a credential from a person on a higher position to a person on a lower position in one run, so the receiver is processed first. Expect 0 failed in that run, and the credential on the receiver only. This proves that the delete by value works in the form PQ uploads the value.
- Give a master or technician user a card on the device, then assign the same card to a PQ person. Expect 0 failed, the card on the PQ person, and the master or technician user still on its slot.
What Framework Handles¶
Framework automatically handles:
- Dependency ordering (Schedule → AccessLevel → Cardholder)
- Address allocation and persistence
- Differential sync (detect add/update/delete)
- Hash-based change detection
- Error handling and retry
Best-Effort Synchronization (Critical)¶
Access sync must be best-effort: the failure or ineligibility of one item (a person, card, credential, or entity) must never abort or degrade the sync of the remaining items. One invalid card must not stop 4,999 other employees from starting their shift in the morning (RULE-039).
Skip what you cannot represent, keep going. A credential the transform cannot represent — unparseable value, value out of the device's representable range, empty PIN — is skipped. The person's other credentials and every other person still synchronize.
var card = ParseCard(person);
if (card is null)
{
Log.Warning("Skipping card for person {PersonId}: value not representable", person.PersonId);
continue; // remaining credentials and persons still sync
}
Capacity exhaustion is per-item, not fatal. When the address range fills up, the items that already fit stay uploaded; the overflow items are the ones that failed. Never let a "range full" condition throw out of Transform() or command execution and abandon the whole batch.
if (!allocator.TryReserve(out var address))
{
Log.Warning("Capacity reached for {Type}; person {PersonId} not uploaded", typeId, person.PersonId);
continue; // batch is not abandoned; the site runs with whoever fits
}
A device rejecting one write is a per-item failure. Remaining commands still execute.
Never degrade silently. If an internal limit forces you to drop a capability of an item you do upload — for example uploading a user without some of their door permissions because an access-level cap was hit — that drop must be logged or reported. A user that appears synced but is quietly missing their access rights is worse than one that was skipped: doors reject them and nobody knows why.
if (accessLevels.Count > MaxAccessLevels)
{
Log.Warning("Person {PersonId}: {Dropped} access levels exceed device limit and were not uploaded",
person.PersonId, accessLevels.Count - MaxAccessLevels);
accessLevels = accessLevels.Take(MaxAccessLevels).ToList();
}
Don't:
- Let a capacity/range-full exception propagate and abort the entire sync batch.
- Hit an internal access-level limit and silently upload users without their door access.
- Throw from
Transform()on the first unrepresentable credential (see RULE-006) instead of skipping it.
Pitfall: Cross-Entity References in Transform¶
Problem: Transform() builds the access model BEFORE the framework allocates addresses.
Entity .Address is null during Transform -- it gets assigned by the differ after Transform returns.
Wrong -- using address in embedded type:
// in Transform():
var schedule = GetOrCreateSchedule(ranges, scheduleMap);
doorSchedules.Add(new DoorSchedule(DoorId: doorId, ScheduleAddress: schedule.Address ?? 0));
// BUG: Address is always null here -> 0 -> wrong schedule reference
Correct -- using object reference:
// in Transform():
var schedule = GetOrCreateSchedule(ranges, scheduleMap);
doorSchedules.Add(new DoorSchedule(DoorId: doorId, Schedule: schedule));
// in CreateCommands() -- address is available here:
config.schedule_id = (short)(doorSchedule.Schedule.Address ?? 0);
"Always active" / empty references: use a static empty singleton instead of null:
public partial record Schedule
{
public static readonly Schedule Empty = new(Periods: [], HolidayMask: 0);
public bool IsEmpty => Periods.Length == 0;
}
Empty is not added to the entity map, so it never gets uploaded to the device.
Its Address stays null, which resolves to 0 (typically "always active" in device firmware).
Reserved Address Positions¶
Some devices keep certain address slots permanently occupied by firmware entries (admin accounts, remote-access slots, built-in schedules). The framework must not allocate into those slots and must not delete them during Reset.
Override GetReservedDeviceMemory on your AccessSynchronization class to declare them:
protected override IEnumerable<uint> GetReservedDeviceMemory(string typeId)
=> typeId == "User" ? [1u, 2u] : [];
For runtime reservations (slots derived from device configuration read at startup), return the live values:
protected override IEnumerable<uint> GetReservedDeviceMemory(string typeId)
=> typeId == "User"
? [(uint)protocol.Panel.PositionAdmin,
(uint)protocol.Panel.PositionTechnician,
(uint)protocol.Panel.PositionRemoteAccess]
: [];
Framework behavior:
- Reserved slots are marked in the allocator before
Diff()runs, so new entities are never assigned to them. ClearDeviceMemory(first synchronization, Reset) never receives a slotGetReservedDeviceMemoryreturns, even when a stale PQ record sits on it. It receives an installer-reserved slot only when PQ stored a record there: that slot is PQ's and arrives with its stored record, so the adapter deletes what PQ wrote. An installer-reserved slot without a PQ record is never passed. The framework never assigns a reserved slot to an entity.- If an adapter returns reserved slots from
GetReservedDeviceMemory, itsClearDeviceMemorydeletes only the slots inoccupied. A bulk wipe or a walk over its own range deletes the reserved slots too. - A record PQ stored on a slot that is now reserved moves on the next full synchronization. The differ clears the reserved slot (an evicted delete) and uploads the record on a free slot. Records that reference it by slot get the new slot and are uploaded again. No Reset runs and no adapter code is required.
- The evicted delete runs first in the batch and is not reported as a removal. The upload on the free slot depends on it: when the delete fails, the upload is skipped, the mapping stays on the reserved slot, and the next full synchronization tries again. A confirmed delete forgets the record's mapping, because the reserved slot no longer holds it: when the upload on the free slot then fails, the next full synchronization uploads the record again and repoints the records that reference it. When no free slot is left, the delete still runs and the record is reported as failed.
- A selective synchronization does not move unchanged records; they move on the next full synchronization. It never rewrites a changed record into a reserved slot: the record gets a free slot and the reserved one is deleted.
- When
GetReservedDeviceMemorythrows (the adapter cannot tell yet which slots are reserved), the synchronization ends as Failed withDeviceNotReadybefore any write.
A failed read is not an empty set. When GetReservedDeviceMemory returns slots read from the device (protected users: installer, master, technician), persist the last set read. If a later read fails, return the persisted set. Never return an empty set for a failed read: the allocator would then hand master or technician slots to PQ users, and the cleanup would delete them. If no set was ever read, throw from GetReservedDeviceMemory, so the synchronization ends as Failed with DeviceNotReady.
What not to do:
// Wrong: skip logic in Transform or commands
if (address == 1 || address == 2)
continue; // the framework owns this — don't encode it here
Manual skip logic is fragile (must be maintained in multiple places, missed during Reset) and conflicts with the framework's allocation authority. Use GetReservedDeviceMemory exclusively.
Scope: reserved positions apply only to entity types with range: [min, max] in access-model.yaml. Natural-id entities (id: property_name) are out of scope.
Positions the device holds¶
Some panels refuse a write because the record at that position is not PQ's: an installer-locked group, a technician
card. Do not read the device memory up front to find them. Return PanelCommandResult.HeldByDevice(position) from the
write command, with the access-sync address of the refused position:
if (CredentialRecordCodec.IsProtected(table, stored))
return PanelCommandResult.HeldByDevice(CredentialRecordCodec.Address(table, number), new() { ["reason"] = "protected_record" });
The framework reserves the position for good and moves the record to a free position in the same synchronization, together with every record that references it. See Device-Held Positions.
Return it only when the panel proves the record is not PQ's. For any other refusal return Rejected: a held position
is lost to PQ for good.
Installer Reservations¶
The installer reserves panel memory positions for another system (building automation, a second access system) in
the Synchronization tab of the panel. The framework stores them in the device property reserved_device_memory, one
TypeId:from-to or TypeId:position entry per range.
Framework behavior:
- The generator adds the property to every device type with access synchronization whose
access-model.yamlhas an entity type withrange: [min, max]. Its allowed segments are those ranges. Natural-id entity types have no positions and are not offered. - The server refuses an entry outside the segment of its entity type and a set that leaves no free position.
- The generated synchronization merges the entries with
GetReservedDeviceMemory, clamped to the declared range. An entry the adapter cannot parse or whose type it does not know is logged and ignored. - A change takes effect after the device restarts; the next full synchronization moves PQ records off newly reserved positions.
- Removing a reservation leaves the data on the released positions. PQ overwrites a position completely when it assigns it.
Adapter obligation: ClearDeviceMemory deletes only the positions in occupied, and wipes a table in bulk only
when they cover its whole device memory range (compliance rule RULE-061). No other adapter code is involved.
Device Memory Range¶
range: [min, max] in access-model.yaml is the address space of the protocol. A connected panel can have less memory, and many panels report their size only after they connect. Override GetDeviceMemoryRange to report it:
protected override AccessModel.DeviceMemoryRange? GetDeviceMemoryRange(string typeId)
=> typeId == "User"
? protocol.PanelUserCount is > 0 and var count ? new(1, (uint)count) : null
: base.GetDeviceMemoryRange(typeId);
Framework behavior:
- The default returns the declared range, so an adapter whose panel always has the full range overrides nothing.
- The allocator, the initial cleanup and the occupancy report use the returned range. Positions outside it are never assigned and never cleared.
nullmeans the device has not reported the range yet. The framework refuses synchronization and Reset before it clears anything or forgets a mapping. The framework asks beforeBeforeTransformruns, so read the size when the device connects.- A record PQ stored above a range that has since shrunk moves inside the range on the next full synchronization, the same way as a record on a reserved slot.
- A range outside the declared one is an adapter defect. The synchronization throws
InvalidOperationException.
What not to do: do not report positions above the panel capacity as reserved. Reserved positions exist on the panel and belong to someone else; positions outside the device memory range do not exist.
See Also¶
- Pattern 7: Address Resolution - Address allocation strategies
- Pattern 10: Error Handling - Handling sync failures