Repository navigation
Description
User story
As a team that rebuilds the twin graph from Data History (AdtPropertyEvents + AdtTwinLifeCycleEvents + AdtRelationshipLifeCycleEvents), I want Konnektr Graph to emit a property Delete event for every property of a twin/relationship that gets deleted — behind an opt-in flag — so that a twin recreated with the same id can no longer inherit property values from its previous incarnation.
Requested by Arcadis. ADT does not emit property deletion events on twin deletion either, so this must be off by default and stay ADT-compatible.
Background & motivation
Data History currently emits only the lifecycle Delete event when an entity is deleted; the property series simply stops at the last Update. Verified in CloudEventFactory.CreateDataHistoryEvents (src/AgeDigitalTwins.Events/Core/Events/CloudEventFactory.cs:347, anchor: main @ 6d60bc8):
EventType.TwinCreate or EventType.TwinDelete => CreateTwinLifeCycleEvents(...), // :357
EventType.RelationshipCreate or EventType.RelationshipDelete => CreateRelationshipLifeCycleEvents(...),
EventType.TwinUpdate or EventType.RelationshipUpdate => CreatePropertyEvents(...), // :494This is codified by a test that asserts exactly one event for a twin delete that still carries a property: src/AgeDigitalTwins.Events.Test/CloudEventFactoryTests.cs:262 (CreateDataHistoryEvents_HandlesTwinDeleteEventWithProperties). That test has to keep passing for the default (flag off) behaviour.
Why that leaves a hole
Any reconstruction that resolves node/edge property values from the latest property row per (Id, Key) — the documented LatestPropertyValues pattern (.summarize arg_max(TimeStamp, *) by Id, Key in ADX, DISTINCT ON/array_agg in Postgres) — keeps resolving to the pre-delete value after the entity is gone, because no newer row was ever written for those keys. Two symptoms follow:
- Resurrection on re-create with the same id. If the twin is re-created with only some of its old properties (partial create, PATCH-based re-creation, a property dropped by a model change, or a re-import that writes a subset), only the properties present on the new write get fresh
Createrows. Every other key still resolves to the previous incarnation's value — exactly the reported defect: property events from before the deletion reappear in the recreated graph. - Values for entities that no longer exist. After a plain delete (no re-create), the property series still answers for that
Idat anytargetTimeafter the delete; consumers that do not join against the lifecycle tables will happily read them.
The reporter's ADX helper is what surfaces (1). The lifecycle CTEs are correct — they drop the deleted entity — but the node properties are joined from AdtPropertyEvents, which has no terminal row:
.create-or-alter function with (skipvalidation = "true") AdtGraph() {
let twins = materialize(AdtTwinLifeCycleEvents
| summarize arg_max(TimeStamp, *) by TwinId
| where Action != 'Delete');
let twinIds = twins | project TwinId;
let relationships = AdtRelationshipLifeCycleEvents
| summarize arg_max(TimeStamp, *) by Source, Target
| where Source in (twinIds) and Target in (twinIds)
| where Action != 'Delete';
relationships
| make-graph Source-->Target with twins on TwinId
}Emitting property Delete rows at deletion time makes the property series self-terminating: arg_max per (Id, Key) resolves to Delete at the moment of deletion, and a later Create (re-creation) wins again because it is strictly newer. No tombstones or purge logic on the consumer side.
Why opt-in (default false)
- ADT parity. ADT emits only the twin/relationship lifecycle
Delete; a client that counts or replays property events must not suddenly see an extra class of event. - Volume. One row per property per deleted entity. A bulk delete of 10k twins × 20 properties turns into 200k extra property rows — fine for the team's historization, not something to force on every deployment.
Proposed implementation
Small, contained change: one config flag, one new factory method, no sink changes and no table/schema change (both data-history sinks already map the action column — see §3).
1. Opt-in flag
Mirror the existing TrackLastUpdatedBy plumbing (src/AgeDigitalTwins.Events/Program.cs:67 → SharedEventConsumer → CloudEventFactory.CreateDataHistoryEvents):
Parameters:EmitPropertyEventsOnDelete(bool, defaultfalse), envParameters__EmitPropertyEventsOnDelete=true.- Add a
bool emitPropertyEventsOnDelete = falseparameter toCreateDataHistoryEventsand thread it fromSharedEventConsumer.ProcessSingleEventData(src/AgeDigitalTwins.Events/Core/Services/SharedEventConsumer.cs:256). - No
KustoSinkOptions/PostgresSinkOptionsproperty is needed for this one (unlikeTrackLastUpdatedBy, it does not change any ingestion mapping) — keep the surface minimal.
2. Emit the events in the factory
Add CreatePropertyDeleteEvents(EventData, Uri source, Dictionary<SinkEventType,string> typeMapping, bool trackLastUpdatedBy) next to CreatePropertyEvents. Call it from CreateDataHistoryEvents in addition to (not instead of) the lifecycle event, when the flag is on and EventType is TwinDelete or RelationshipDelete:
EventType.TwinDelete => emitPropertyEventsOnDelete
? [.. CreateTwinLifeCycleEvents(...), .. CreatePropertyDeleteEvents(...)]
: CreateTwinLifeCycleEvents(...),(The existing CreatePropertyEvents requires both OldValue and NewValue; a delete has NewValue == null, so extending it would only add branches — a separate method keeps the delete path explicit.)
Source material: eventData.OldValue — the replication row's properties object (AgeDigitalTwinsReplication.ConvertRowToJsonAsync, src/AgeDigitalTwins.Events/Core/Services/AgeDigitalTwinsReplication.cs:572), for twins { "$dtId", "$metadata", <property>… }, for relationships { "$relationshipId", "$relationshipName", "$sourceId", "$targetId", "$metadata", <property>… }.
Per emitted event:
| Field | Value |
|---|---|
action |
"Delete" |
key |
the top-level property name (same convention as CreateCloudEventsFromPatch, :560 — one event per top-level property, object values kept whole, i.e. what a remove /prop patch produces today) |
value |
the removed value from OldValue — mirrors the existing property-delete row shape (OperationType.Remove → action: "Delete" in CreatePropertyCloudEvent, :604) |
id |
OldValue["$dtId"], or OldValue["$sourceId"] for a relationship (same resolution CreatePropertyCloudEvent does from NewValue, but read from OldValue) |
modelId |
OldValue["$metadata"]["$model"] |
relationshipId / relationshipTarget |
OldValue["$relationshipId"] / OldValue["$targetId"] (relationship deletes only) |
timeStamp |
eventData.Timestamp — the delete transaction's ServerClock. Never a DateTime.UtcNow fallback: the ordering guarantee against the pre-delete rows and a later re-create depends on the commit clock |
sourceTimeStamp |
omitted — a delete has no source write to attribute |
updatedBy |
only when TrackLastUpdatedBy is on: the twin/relationship-level $metadata.$lastUpdatedBy written by the deleting update. Use the twin-level value, not $metadata.<prop>.lastUpdatedBy — per #127 / PR #128 the per-property entry is not trustworthy for a delete |
subject |
<id> or <id>/relationships/<relationshipId>, matching the PropertyEvent convention |
Rules:
- Skip all keys starting with
$($dtId,$etag,$version,$metadata,$relationshipId,$relationshipName,$sourceId,$targetId) — same rule asCreateCloudEventsFromPatch. - Zero properties (a twin that is only
$dtId/$metadata) → zero extra events, no error. OldValueempty or missingproperties(replica identity notFULLon a table that predates the current client) → emit nothing and log; do not emit null-valuedDeleterows, which would be indistinguishable from a real value change.- Do not throw when the flag is off: current behaviour and event count stay byte-identical.
3. Relationship deletes, timestamps and sinks
-
Relationship deletes are explicit, separate calls — by design. AGE rejects a plain
DELETEof a vertex that still has edges, and the client deliberately issues exactly that (src/AgeDigitalTwins/AgeDigitalTwinsClient.DigitalTwins.cs:899—MATCH (t:Twin {$dtId: $twinId}) DELETE t); the contract is that the caller deletes the relationships first, then the twin. Verified on a throwaway pod of this project's own imageghcr.io/konnektr-io/age-pgvector:16-1.6.0-standard-trixie(2026-12-02):MATCH (a:V {id:'a'}) DELETE aon a vertex with one edge →ERROR: Cannot delete a vertex that has edge(s). Delete the edge(s) first, or try DETACH DELETE.Consequence for this feature: there is no implicit cascade to piggyback on, so
RelationshipDeletemust be handled in its own right (§2) — that is the path that produces the edge propertyDeleterows, one transaction per relationship delete. A twin delete then emits propertyDeleterows for the twin's own properties only. Do not switch toDETACH DELETEas part of this issue: it would silently change a documented operating contract. -
REPLICA IDENTITY FULLis set onTwin(src/AgeDigitalTwins/GraphInitialization.cs:23) and on every relationship table at creation (src/AgeDigitalTwins/AgeDigitalTwinsClient.Models.cs:467), soOldValuecarries the full property set for both deletes. -
Ordering. Each delete is its own transaction, so rows are stamped with that transaction's
ServerClock: relationship property deletes precede the twin's lifecycleDeleteand its property deletes. Within a transaction the events share oneServerClock, and cross-transaction ordering is monotonic (fixed in Rapid relationship delete→recreate emits lifecycle events in wrong TimeStamp order #111), soDelete(TimeStamp) < Create(TimeStamp)holds for a delete→re-create cycle. Test that invariant, not just the event shape. -
No sink work, no schema change. Both sinks already map the column:
KustoEventSink.BuildPropertyEventMappings→Action←$.action(src/AgeDigitalTwins.Events/Sinks/Kusto/KustoEventSink.cs:214),PostgresEventSink.BuildPropertyEventColumns→action(src/AgeDigitalTwins.Events/Sinks/Postgres/PostgresEventSink.cs:520). -
Pre-flight for the implementer: the ADX schema table in
docs/how-to-guides/data-history-kusto.mdx(~line 129) omitsAction, so a hand-createdAdtPropertyEventstable might not have the column. Confirm what queued ingestion does with a mapped-but-missing column and, if needed, note the.alter table AdtPropertyEvents add Action:stringstep in the docs.
4. Tests
src/AgeDigitalTwins.Events.Test/CloudEventFactoryTests.cs (unit):
- Flag off: twin delete with properties → still exactly 1 lifecycle event (existing
:262test unchanged). - Flag on: twin delete with 2 properties → 1 lifecycle
Delete+ 2 property events withaction=Delete, correctkey/value/id/modelId/subject,timeStamp == eventData.Timestamp. - System keys (
$dtId,$metadata,$etag, …) never produce events. - Relationship delete variant:
id == $sourceId,relationshipId/relationshipTargetset, relationship properties emitted. TrackLastUpdatedByon →updatedByfrom twin/relationship-level$metadata.$lastUpdatedBy; off → omitted.- Twin with no properties → no extra events;
OldValuewithoutproperties→ no extra events, no throw.
src/AgeDigitalTwins.Events.Test (integration, EventsTestBase/TestingEventSink, live replication):
- Create twin with 2 properties → delete it: captured events contain the lifecycle
Deleteand oneDeleteper property. - The actual defect: create twin with properties
a+b, delete it, re-create it withaonly → assert that resolving(Id, Key)by latestTimeStampyieldsDeleteforb, andCreatefora; and that the re-create'sTimeStampis strictly greater than the delete's. - Relationship-first flow (the documented contract): twin with one relationship that carries a property → delete the relationship, then the twin → the captured stream contains the relationship's
RelationshipDelete+ one propertyDeleteper edge property, then the twin's lifecycleDelete+ one propertyDeleteper twin property, with the relationship rows'TimeStampearlier than the twin's, and nothing emitted twice.
5. Documentation
docs/how-to-guides/data-history-kusto.mdx+docs/how-to-guides/data-history-postgres.mdx: the new flag, what it emits, that it is opt-in and not ADT behaviour, and thatLatestPropertyValues/ point-in-time queries can drop their tombstone workaround when it is on (they must keep it when off). AddActionto theAdtPropertyEventsschema table while there.CLAUDE.md: config surface (Parameters:EmitPropertyEventsOnDelete) and the event semantics for deletes, next to the existingTrackLastUpdatedBy/ property-event notes.
Acceptance criteria
-
Parameters:EmitPropertyEventsOnDelete(defaultfalse) is threaded to the Data History factory; with it off the emitted event stream is unchanged (existing tests unmodified and green). - With it on, a twin delete emits one
Deleteproperty event per non-$property of the deleted twin, in addition to the lifecycleDelete. - With it on, a relationship delete does the same for relationship properties — covered as its own event type, not relying on an implicit cascade (the contract is delete-relationships-first;
DETACH DELETEis out of scope and stays unimplemented). - All synthesized rows carry the delete transaction's
TimeStamp,action=Delete, the removed value, and the delete caller inupdatedBywhenTrackLastUpdatedByis on. - Retained for delete→re-create: latest row per
(Id, Key)is theDeletefor properties the re-created twin does not set, and the re-create'sCreatefor the ones it does. - Unit + integration tests from §4, running on the PG16/AGE 1.6 and PG18/AGE 1.8 matrix cells.
- Docs updated (both data-history guides +
CLAUDE.md). - No sink, table or migration change required — confirmed by the diff.
Open questions
- Flag name/scope —
Parameters:EmitPropertyEventsOnDeleteas a single global switch (recommended, matchesTrackLastUpdatedByand keeps one source of truth), or per-sink so one sink can opt in independently? Recommend global. - Value on the delete row — the removed value (recommended, matches the existing
remove-patch rows) ornull? Recommend the removed value: point-in-time readers then see the last known value right up to the delete, and theDeleteaction is what carries the semantics. - Event notifications — should
EventFormat.EventNotificationalso gain anything here? Recommend no: ADT emits only the twin delete notification, and this issue is about Data History reconstruction. - Out of scope, but worth naming — model deletion (
DeleteModelsAsyncissuesMATCH (m:Model) DETACH DELETE m) and import-job replaces go through the same client methods, so whatever they emit follows from this change; they are not analysed separately here. A retroactive purge of already-historized property rows is not part of this issue.
Filed on Niko's behalf — Hermes
Activity
feat(events): emit property Delete events on twin/relationship deleti…
nikoraes commentedon Dec 2, 2026
Implemented — PR #130
#130 (
feat/emit-property-delete-events-129, headc5acd10)What it does.
Parameters:EmitPropertyEventsOnDelete(Events service, defaultfalse) threadsProgram.cs→SharedEventConsumer→CloudEventFactory.CreateDataHistoryEvents, and with it on a twin/relationship delete emits one propertyDeleterow per non-$top-level property in addition to the lifecycleDelete. Rows are synthesized from the replication row's property image (OldValue), carry the delete'sTimeStampand the removed value, and use the twin/relationship-level$metadata.$lastUpdatedByforupdatedBy(the per-property entry still names the previous writer, #127). A missing/empty image emits nothing and logs a warning rather than a null-valuedDeleterow. No sink, table or migration change — both sinks already mapaction/Action.Aligned to the edited spec. The issue was updated at 13:01 while this was in flight: §3/§4/acceptance now say the delete-relationships-first contract stands and
DETACH DELETEis out of scope. I had implemented, measured and test-covered theDETACH DELETEvariant first; it is fully reverted — the PR touches no client code, and the relationship coverage is the explicitDeleteRelationshipAsyncpath (edgeRelationshipDelete+ one propertyDeleteper edge property, then the twin's own delete rows in TimeStamp order). The measurement is still worth having on record: a plainMATCH … DELETEon a still-connected vertex fails withCannot delete a vertex that has edge(s)onage-pgvector:16-1.6.0-standard-trixie, i.e. deleting edges first is genuinely mandatory, not merely conventional.One correction to the issue text (§3, "within a transaction the events share one
ServerClock"): measured, they are clustered but not bit-identical — the relationship delete's lifecycle row came out at…32.078716Zwhile its edge propertyDeleterow carried the same transaction's later per-row clock. The reconstruction invariant is ordering across transactions (Delete < Create), which holds; the integration test asserts a transaction window, not equality.Tests. 8 unit cases (flag off → exactly one event, i.e. the existing
:262test unchanged; flag on shape;$-keys; relationship variant;updatedBysource; empty image; delete→re-create ordering) and 3 integration cases over live replication (per-property deletes; latest-row-per-(Id, Key)terminates onDeleteafter a partial re-create; relationship-then-twin delete ordering). Verified locally onghcr.io/konnektr-io/age-pgvector:16-1.6.0-standard-trixie(PG 16.15 / AGE 1.6.0):AgeDigitalTwins.Events.Test117 passed / 0 failed,AgeDigitalTwins.Test358 passed / 8 skipped / 0 failed. The PG18 + apache/AGE cells are CI's.Docs. Both data-history guides (opt-in section + the reconstruction-query caveat),
configuration.mdx(Events service key),CLAUDE.md. While there: theAdtPropertyEventsschema table omittedActionalthough the sink has always mapped it — added, with the.alter-merge table AdtPropertyEvents add Action:stringstep for hand-created tables. I could not exercise ADX queued ingestion here, so the doc states the requirement rather than guessing at ingestion behaviour.Leaving this open for the PR's
Closes; card is In review.— Hermes
feat(#129): emit property Delete events on twin/relationship deletion (…
ci(sdk): publish to NuGet with trusted publishing (OIDC), not the sta…