# Diff for migration 0019

Migration file: `0019_add_kv_last_updated.sql`

## Table Changes

### `kv_store` — column added

```diff
@@
- kv_store(instance_id, key, value, execution_id)
+ kv_store(instance_id, key, value, execution_id, last_updated_at_ms)
```

### `kv_store` — migration statement

```sql
ALTER TABLE SCHEMA.kv_store ADD COLUMN last_updated_at_ms BIGINT NOT NULL DEFAULT 0;
```

## Function Changes

### `fetch_orchestration_item` — body modified (baseline: 0018)

```diff
@@
-                SELECT COALESCE(jsonb_object_agg(ks.key, ks.value), '{}'::jsonb)
+                SELECT COALESCE(
+                    jsonb_object_agg(
+                        ks.key,
+                        jsonb_build_object('value', ks.value, 'last_updated_at_ms', ks.last_updated_at_ms)
+                    ),
+                    '{}'::jsonb
+                )
                 INTO v_kv_snapshot
                 FROM SCHEMA.kv_store ks
                 WHERE ks.instance_id = v_instance_id;
```

### `ack_orchestration_item` — body modified (baseline: 0018)

```diff
@@
-                        INSERT INTO SCHEMA.kv_store (instance_id, key, value, execution_id)
-                        VALUES (v_instance_id, v_kv_item->>'key', v_kv_item->>'value', v_current_execution_id)
+                        INSERT INTO SCHEMA.kv_store (instance_id, key, value, execution_id, last_updated_at_ms)
+                        VALUES (v_instance_id, v_kv_item->>'key', v_kv_item->>'value', v_current_execution_id, (v_kv_item->>'last_updated_at_ms')::BIGINT)
                         ON CONFLICT (instance_id, key)
-                        DO UPDATE SET value = EXCLUDED.value, execution_id = EXCLUDED.execution_id;
+                        DO UPDATE SET value = EXCLUDED.value, execution_id = EXCLUDED.execution_id, last_updated_at_ms = EXCLUDED.last_updated_at_ms;
```

### `prune_executions` — body modified (baseline: 0018)

```diff
@@
                 DELETE FROM SCHEMA.history h
                 WHERE h.instance_id = p_instance_id
                   AND h.execution_id = v_exec_id;
                 GET DIAGNOSTICS v_count = ROW_COUNT;
                 v_events_deleted := v_events_deleted + v_count;
-
-                -- Delete KV entries whose last-writing execution matches the pruned one
-                DELETE FROM SCHEMA.kv_store
-                WHERE instance_id = p_instance_id AND execution_id = v_exec_id;
             END LOOP;
```
