Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,18 @@ When `TrackLastUpdatedBy` is enabled in the Events service (`Parameters:TrackLas

The `TrackLastUpdatedBy` flag must be set in **both** the API service (for writing `lastUpdatedBy` to twins) and the Events service (for reading it into events and Kusto column mappings).

### Property Delete events on entity deletion (GH #129)

By default a twin/relationship delete emits **only** the lifecycle `Delete` row — ADT parity, and pinned by `CloudEventFactoryTests` (a delete with properties must produce exactly one event). With `Parameters:EmitPropertyEventsOnDelete=true` (Events service, default `false`) `CloudEventFactory.CreatePropertyDeleteEvents` additionally emits one property `Delete` row per non-`$` top-level property of the deleted entity:

- source is `EventData.OldValue`, the replication row's property image (hence `REPLICA IDENTITY FULL` on the twin and relationship tables); a missing image emits nothing and `SharedEventConsumer` logs a warning, never a null-valued `Delete` row;
- every row carries the delete transaction's `TimeStamp` (`ServerClock`) and the removed value; `updatedBy` uses the twin/relationship-level `$metadata.$lastUpdatedBy` — the per-property entry names the previous writer (see above);
- no sink, table or migration change: both sinks already map `action`/`Action`.

The point is that the property series becomes self-terminating, so a latest-row-per-`(Id, Key)` reconstruction stops at the delete and a twin re-created with the same id cannot inherit the properties the new write omits. Note that rows of one transaction do **not** carry bit-identical `ServerClock` values (measured ~13 µs apart) — ordering is the invariant, not equality.

Deleting a twin is the caller's contract: the relationships go first (`DeleteRelationshipAsync`), because AGE rejects a plain `DELETE` of a vertex that still has edges. Each relationship delete is therefore its own `RelationshipDelete` event and gets its own property `Delete` rows — nothing relies on an implicit cascade, and `DETACH DELETE` is deliberately not used.

### Configuration keys (ApiService)

Key `Parameters:` prefixed values in configuration:
Expand Down
47 changes: 47 additions & 0 deletions docs/how-to-guides/data-history-kusto.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,40 @@ AdtPropertyEvents
| take 10
```

### Step 5 (Optional): Emit property `Delete` events on entity deletion

By default Konnektr emits **only** the lifecycle `Delete` row when a twin or relationship is
deleted, and the property series stops at the last `Update`. This is what Azure Digital Twins
does, so it stays the default.

It leaves a hole for any reconstruction that resolves node/edge values from the latest row per
`(Id, Key)` (the pattern in [Current State Reconstruction](#current-state-reconstruction)):
after a plain delete those keys keep resolving to the pre-delete value, and a twin re-created
with the same id inherits every property the new write does not set.

Switch on the opt-in flag to make the property series **self-terminating** — one property
`Delete` row per property of the deleted entity, written with the delete transaction's
`TimeStamp`, in addition to the lifecycle row:

```json
{
"Parameters": {
"EmitPropertyEventsOnDelete": true
}
}
```

or `Parameters__EmitPropertyEventsOnDelete=true` in the environment. It is a single global
switch (one source of truth, next to `Parameters:TrackLastUpdatedBy`); no sink or table change
is needed. Keep it **off** if you replay or count property events and must match ADT's stream
exactly, and note the volume: one extra row per property per deleted entity, so a 10 000-twin
bulk delete becomes 200 000 extra rows.

With the flag on, the `LatestPropertyValues` / point-in-time queries below need no tombstone
workaround; with it off they still do. The rows are synthesized from the deleted row's
replication image, so `REPLICA IDENTITY FULL` must be set on the twin and relationship tables —
without it the image is missing, nothing is emitted, and the events service logs a warning.

## Data Schema

### AdtPropertyEvents
Expand All @@ -142,6 +176,13 @@ Stores twin and relationship property changes over time.
| `Value` | dynamic | Property value (supports JSON) |
| `RelationshipId` | string | Relationship ID (empty for twin properties) |
| `RelationshipTarget` | string | Target twin ID (empty for twin properties) |
| `Action` | string | `Create`, `Update` or `Delete` |

> **Note:** The sink has always mapped `Action` (from the event's `action` field). If your
> `AdtPropertyEvents` table was created by hand from an older copy of this table, confirm the
> column exists — `.show table AdtPropertyEvents schema` — and add it with
> `.alter-merge table AdtPropertyEvents add Action:string`. A table missing it rejects the
> ingestion of every property event.

**Example data:**

Expand Down Expand Up @@ -206,6 +247,12 @@ AdtPropertyEvents
| project Id, Key, Value, LastUpdate=TimeStamp
```

> **Note:** this answers for every `Id` that ever wrote a property — including entities that were
> deleted, because by default the property series stops at the last `Update`. With
> `Parameters:EmitPropertyEventsOnDelete` enabled, append `| where Action != 'Delete'` and the
> series terminates at the delete; with the flag off, join against the lifecycle table instead
> (as the `AdtGraph()` function below does).

### Historical State at Specific Time

Reconstruct all property values as they existed at a specific timestamp:
Expand Down
28 changes: 28 additions & 0 deletions docs/how-to-guides/data-history-postgres.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,22 @@ Configured under `EventSinks:Postgres` as an array (one entry per sink).

Table and schema names are validated as plain SQL identifiers; anything that is not a valid identifier (spaces, quotes, semicolons, leading digits) is rejected at startup.

One setting is **global** rather than per-sink, because it changes the emitted event stream and
not the ingestion mapping:

| Key | Required | Default | Description |
|-----|----------|---------|-------------|
| `Parameters:EmitPropertyEventsOnDelete` | No | `false` | Emit one property `Delete` row per property of a deleted twin/relationship, in addition to the lifecycle `Delete` |

It is off by default because Azure Digital Twins does not emit property events on deletion
either. Enable it (`Parameters__EmitPropertyEventsOnDelete=true`) when you rebuild the graph from
Data History: it makes the property series self-terminating, so a twin re-created with the same id
cannot inherit the previous incarnation's values for the properties the new write does not set.
The cost is volume — one extra row per property per deleted entity. Rows are synthesized from the
deleted row's replication image, so `REPLICA IDENTITY FULL` must be set on the twin and
relationship tables (Konnektr sets it); without it nothing is emitted and the events service logs
a warning. No sink, table or migration change is required.

## Data Schema

All timestamps are `timestamptz` (stored in UTC). `value` is `jsonb`, so scalar values are stored as JSON scalars — use `value #>> '{}'` to read them as text.
Expand Down Expand Up @@ -170,6 +186,13 @@ Stores twin and relationship property changes over time.
| 2025-01-20 10:30:00+00 | sensor-temp-01 | dtmi:com:example:Sensor;1 | temperature | `72.5` |
| 2025-01-20 10:31:00+00 | sensor-temp-01 | dtmi:com:example:Sensor;1 | temperature | `73.2` |

By default a property keeps its last `Update` when its twin or relationship is deleted, and the
`Delete` appears only in the lifecycle table. With `Parameters:EmitPropertyEventsOnDelete`
enabled, the deletion also writes one `action = 'Delete'` row per property, carrying the removed
value and the delete transaction's `time_stamp` — so
`DISTINCT ON (id, key) … ORDER BY time_stamp DESC` terminates instead of resolving a deleted
entity's old value.

### adt_twin_lifecycle_events

Stores twin creation and deletion.
Expand Down Expand Up @@ -219,6 +242,11 @@ WHERE relationship_id = ''
ORDER BY id, key, time_stamp DESC;
```

> **Note:** without `Parameters:EmitPropertyEventsOnDelete` this also resolves for deleted
> entities, because the property series stops at the last `Update`. With the flag on, add
> `AND action <> 'Delete'` to drop them; with the flag off, join `adt_twin_lifecycle_events`
> instead (see [Historical Graph Reconstruction](#historical-graph-reconstruction)).

### Historical State at a Specific Time

"Where was the state at 03:00 last Tuesday?"
Expand Down
6 changes: 6 additions & 0 deletions docs/reference/configuration.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,12 @@ Falls back through this chain: `GetConnectionString("agedb")` → `ConnectionStr
|-----|---------|-------------|
| `Parameters:TrackLastUpdatedBy` | `false` | When `true`, includes `updatedBy` fields in DataHistory CloudEvents from the `$metadata.$lastUpdatedBy` value |

### EmitPropertyEventsOnDelete

| Key | Default | Description |
|-----|---------|-------------|
| `Parameters:EmitPropertyEventsOnDelete` | `false` | When `true`, a twin or relationship delete also emits one property `Delete` CloudEvent per property of the deleted entity, in addition to the lifecycle `Delete`. Off by default (Azure Digital Twins parity). See [Data History → Kusto](/docs/graph/how-to-guides/data-history-kusto) / [PostgreSQL](/docs/graph/how-to-guides/data-history-postgres). |

### Event Sinks

Event sinks are configured under the `EventSinks` section. Each sink type supports multiple instances (configured as arrays).
Expand Down
Loading