Skip to content

Subscriptions

Subscriptions, the notification listener, and where subscription records are kept.

py20305.subscription.manager

SubscriptionManager for IEEE 2030.5 subscription lifecycle.

Manages creating, cancelling, and tracking subscriptions via the Sep2Client. Stores notifications in a bounded deque to prevent unbounded memory growth. Supports automatic renewal of subscriptions before server-side expiry.

SubscriptionState dataclass

Tracks a single active subscription.

Source code in src/py20305/subscription/manager.py
@dataclass
class SubscriptionState:
    """Tracks a single active subscription."""

    subscription_uri: str
    subscribed_resource: str
    notification_uri: str
    resource_type: str
    status: str = "active"
    created_at: float = field(default_factory=time.time)
    is_list_subscription: bool = False
    unmanaged: bool = False
    #: The SubscriptionList the subscription was POSTed to. The server may give
    #: the subscription an href outside it, so it is kept rather than derived.
    sub_list_href: str | None = None
    #: Set on a subscription the server cancelled with status 1. No manager
    #: sharing the store subscribes to its resource again until a reconnect
    #: clears it (see :meth:`SubscriptionManager.suppress_resubscribe`).
    resubscribe_suppressed: bool = False

StoredNotification dataclass

A received notification record.

Source code in src/py20305/subscription/manager.py
@dataclass
class StoredNotification:
    """A received notification record."""

    subscribed_resource: str
    status: int
    subscription_uri: str
    created_at: float
    new_resource_uri: str | None = None

ReconcileResult dataclass

Summary of subscription reconciliation during rediscovery.

Source code in src/py20305/subscription/manager.py
@dataclass
class ReconcileResult:
    """Summary of subscription reconciliation during rediscovery."""

    kept: int = 0
    cancelled: int = 0
    created: int = 0
    renewed: int = 0
    cancel_errors: int = 0
    create_errors: int = 0

AdoptionResult dataclass

Summary of :meth:SubscriptionManager.adopt_existing.

Source code in src/py20305/subscription/manager.py
@dataclass
class AdoptionResult:
    """Summary of :meth:`SubscriptionManager.adopt_existing`."""

    #: True when the server returned its SubscriptionList. False means nothing
    #: was adopted and the client subscribes as it would without adoption.
    listed: bool = False
    #: Server subscriptions taken into local state.
    adopted: int = 0
    #: Further subscriptions of ours found for a resource already adopted or tracked.
    duplicates: int = 0
    #: Duplicates DELETEd from the server.
    removed: int = 0
    #: Duplicates whose DELETE failed. They stay on the server.
    remove_errors: int = 0

SubscriptionManager

Create, cancel, and track IEEE 2030.5 subscriptions.

Uses Sep2Client for HTTP operations. The subscription records live in a :class:~py20305.subscription.store.SubscriptionStore, by default a dict in this process; received notifications are kept in memory.

Source code in src/py20305/subscription/manager.py
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
class SubscriptionManager:
    """Create, cancel, and track IEEE 2030.5 subscriptions.

    Uses Sep2Client for HTTP operations. The subscription records live in a
    :class:`~py20305.subscription.store.SubscriptionStore`, by default a dict in
    this process; received notifications are kept in memory.
    """

    def __init__(
        self,
        client: Sep2Client,
        notification_uri: str,
        *,
        max_notifications: int = 1000,
        missing_location_fallback: bool = False,
        on_subscription_lost: Callable[[], Awaitable[None]] | None = None,
        renewal_method: RenewalMethod = "post",
        server_2018_compat: bool | None = None,
        adopt_on_connect: bool = False,
        remove_duplicates: bool = False,
        unsubscribe_on_close: bool = True,
        store: SubscriptionStore | None = None,
        maintains_set: bool = True,
    ) -> None:
        """
        Args:
            missing_location_fallback: Accept a created subscription whose 201
                response has no Location header, under a synthetic URI. Both
                editions require the header (2018 clause 5.5.2.4), so this is a
                workaround for a non-conforming server and is off by default.
            renewal_method: ``post`` re-POSTs a subscription to its list to
                renew it; ``put`` PUTs it to its own href (see :meth:`renew`).
            adopt_on_connect: Have the client call :meth:`adopt_existing` when
                it connects, before it creates subscriptions.
            remove_duplicates: When the client adopts, DELETE the further
                subscriptions of ours it finds for the same resource.
            unsubscribe_on_close: Have the client DELETE its subscriptions when
                it shuts down. Turn off for an instance that hands over to
                another instance with the same identity, which adopts them.
            store: Where the subscription records are kept. None keeps them in
                this process. Give several managers for one client the same
                store to share one subscription set; see
                :class:`~py20305.subscription.store.SubscriptionStore`.
            maintains_set: Whether this manager renews, reconciles and cancels
                the subscription set. False for every manager but one when
                several share a store. ``CsipClient.attach_subscriptions`` sets
                it to False in a client without own-EndDevice work. A manager
                that does not maintain the set still creates subscriptions for
                resources nobody has subscribed to, and records the ones it
                adopts, but it sends no renewal and no DELETE and removes no
                record another manager may need, whatever it is asked to do.

        Raises:
            ValueError: ``renewal_method`` is not ``post`` or ``put``, or
                ``remove_duplicates`` is set without ``adopt_on_connect``.
        """
        if renewal_method not in get_args(RenewalMethod):
            raise ValueError(f"renewal_method must be 'post' or 'put', got {renewal_method!r}")
        if remove_duplicates and not adopt_on_connect:
            raise ValueError("remove_duplicates requires adopt_on_connect")
        self.adopt_on_connect = adopt_on_connect
        self.remove_duplicates = remove_duplicates
        self.unsubscribe_on_close = unsubscribe_on_close
        #: Whether this manager renews, reconciles and cancels the subscription
        #: set; see the ``maintains_set`` argument.
        self.maintains_set = maintains_set
        self._renewal_method = renewal_method
        self._client = client
        self._notification_uri = notification_uri
        self._notification_key = notification_uri_key(notification_uri)
        if store is None:
            from py20305.subscription.store import MemorySubscriptionStore

            store = MemorySubscriptionStore()
        self._store: SubscriptionStore = store
        self._notifications: deque[StoredNotification] = deque(maxlen=max_notifications)
        # time.monotonic() of the last processed notification per resource. The
        # monotonic clock keeps a wall-clock step from stretching the window.
        self._dedup_cache: dict[str, float] = {}
        # Resources the server has cancelled (status=1) -- auto-subscribe skips
        # these so we honour the cancellation (poll-only) instead of immediately
        # re-subscribing. Persists across rediscovery; cleared only on a genuine
        # reconnect.
        self._resubscribe_suppressed: set[str] = set()
        if server_2018_compat is not None:
            warnings.warn(
                "SubscriptionManager(server_2018_compat=...) is deprecated; pass "
                "missing_location_fallback=True for a server that omits the Location header",
                DeprecationWarning,
                stacklevel=2,
            )
            missing_location_fallback = missing_location_fallback or server_2018_compat
        self._missing_location_fallback = missing_location_fallback
        # Invoked (fire-and-forget) when a renewal returns 401/404 -- the
        # server has forgotten our subscriptions and a full rediscovery is
        # needed to re-establish them. The caller (typically csip_client)
        # wires this to its trigger_rediscovery; the rediscovery primitive
        # has its own concurrency lock so duplicate firings collapse.
        self._on_subscription_lost = on_subscription_lost

    def _find_active_for_resource(self, subscribed_resource: str) -> SubscriptionState | None:
        """Find an existing active subscription for a resource href."""
        for state in self._store.values():
            if state.subscribed_resource == subscribed_resource and state.status == "active":
                return state
        return None

    def suppress_resubscribe(self, subscribed_resource: str) -> None:
        """Mark a resource as server-cancelled so auto-subscribe won't re-POST it.

        Set on a ``status=1`` (canceled, no additional info) termination: we
        honor the cancellation (poll the resource instead) rather than fighting
        the server by immediately re-subscribing. Persists across rediscovery;
        cleared by :meth:`clear_resubscribe_suppression` only on a genuine
        reconnect.

        The mark is also written to the resource's cancelled records in the
        store, so every manager sharing the store honors it.
        """
        self._resubscribe_suppressed.add(subscribed_resource)
        for state in self._store.values():
            if state.subscribed_resource == subscribed_resource and state.status != "active":
                state.resubscribe_suppressed = True
                self._store.put(state)

    def resubscribe_suppressed(self, subscribed_resource: str) -> bool:
        """True if auto-subscribe should skip this server-cancelled resource."""
        if subscribed_resource in self._resubscribe_suppressed:
            return True
        return any(
            state.resubscribe_suppressed and state.subscribed_resource == subscribed_resource
            for state in self._store.values()
        )

    def clear_resubscribe_suppression(self) -> None:
        """Clear all resubscribe suppression. Called only on a genuine reconnect
        (upstream restart), not on every rediscovery, so an honored status=1
        cancellation survives the rediscovery storm.

        A manager that maintains the set also removes the suppressed records
        from the store. One that does not clears only its own marks.
        """
        self._resubscribe_suppressed.clear()
        if not self.maintains_set:
            return
        for state in self._store.values():
            if state.resubscribe_suppressed:
                self._store.remove(state.subscription_uri)

    def _is_active(self, subscription_uri: str) -> bool:
        """Return whether the store holds an active record at ``subscription_uri`` now.

        Checked after an await, so that a cancellation or removal written in the
        meantime, by this process or another one, is not overwritten.
        """
        current = self._store.get(subscription_uri)
        return current is not None and current.status == "active"

    @staticmethod
    def _refuse(action: str) -> None:
        """Log that ``action`` was skipped because this manager does not maintain the set."""
        logger.info("Not %s: this manager does not maintain the subscription set", action)

    async def subscribe(
        self,
        sub_list_href: str,
        subscribed_resource: str,
        resource_type: str,
        *,
        encoding: int = 0,
        level: str = "+S1",
        limit: int = 1,
    ) -> SubscriptionState | None:
        """Create a subscription by POSTing to the server's SubscriptionList.

        Args:
            sub_list_href: Server path to SubscriptionList resource.
            subscribed_resource: Full resource path to subscribe to.
            resource_type: Human-readable type (e.g. "FSAList").
            encoding: 0=XML, 1=EXI.
            level: Schema level string.
            limit: Max list items in notification.

        Returns:
            SubscriptionState on success, None on failure.
        """
        # Dedup: return existing active subscription for the same resource
        existing = self._find_active_for_resource(subscribed_resource)
        if existing is not None:
            logger.debug(
                "Already subscribed to %s via %s, skipping POST",
                subscribed_resource,
                existing.subscription_uri,
            )
            return existing

        sub = Subscription(
            subscribed_resource=subscribed_resource,
            encoding=encoding,
            level=level,
            limit=limit,
            notification_uri=self._notification_uri,
        )

        try:
            location = await self._client.post(sub_list_href, sub)
        except Sep2ProtocolError as exc:
            from py20305.diagnostics import report

            report(
                "warnings",
                (
                    f"Server rejected subscription to {subscribed_resource} at "
                    f"{sub_list_href}: HTTP {exc.status_code}"
                ),
                source="subscription",
                dedup_key=f"subscribe:{subscribed_resource}",
                details={
                    "subscribed_resource": subscribed_resource,
                    "sub_list_href": sub_list_href,
                    "status_code": exc.status_code,
                },
            )
            return None
        except Exception as exc:
            from py20305.diagnostics import report

            report(
                "warnings",
                f"Failed to subscribe to {subscribed_resource} at {sub_list_href}: {exc}",
                source="subscription",
                dedup_key=f"subscribe:{subscribed_resource}",
                details={
                    "subscribed_resource": subscribed_resource,
                    "sub_list_href": sub_list_href,
                    "error": str(exc),
                },
                exc_info=True,
            )
            return None

        if not location:
            if self._missing_location_fallback:
                location = f"_synthetic:{subscribed_resource}"
                logger.info(
                    "No Location header, using a synthetic URI for %s (missing_location_fallback)",
                    subscribed_resource,
                )
                state = SubscriptionState(
                    subscription_uri=location,
                    subscribed_resource=subscribed_resource,
                    notification_uri=self._notification_uri,
                    resource_type=resource_type,
                    is_list_subscription=resource_type.endswith("List"),
                    unmanaged=True,
                )
                self._store.put(state)
                return state

            from py20305.diagnostics import report

            report(
                "warnings",
                f"No Location header for subscription to {subscribed_resource}",
                source="subscription",
                dedup_key=f"sub_no_location:{subscribed_resource}",
                details={"subscribed_resource": subscribed_resource},
            )
            return None

        state = SubscriptionState(
            subscription_uri=location,
            subscribed_resource=subscribed_resource,
            notification_uri=self._notification_uri,
            resource_type=resource_type,
            is_list_subscription=resource_type.endswith("List"),
            sub_list_href=sub_list_href,
        )
        self._store.put(state)
        logger.info("Subscribed to %s (%s) -> %s", subscribed_resource, resource_type, location)
        return state

    async def cancel(self, subscription_uri: str) -> bool:
        """Cancel a subscription by DELETEing it on the server.

        Returns True if the DELETE succeeded or the subscription was unknown.
        Always removes local state to prevent stale entries blocking re-subscription.
        Unmanaged subscriptions (2018 compat) skip the DELETE.

        Returns False and changes nothing in a manager that does not maintain
        the set (see :attr:`maintains_set`).
        """
        if not self.maintains_set:
            self._refuse(f"cancelling {subscription_uri}")
            return False
        state = self._store.get(subscription_uri)
        if state is not None and state.unmanaged:
            self._store.remove(subscription_uri)
            logger.info("Removed unmanaged subscription %s", subscription_uri)
            return True

        try:
            await self._client.delete(subscription_uri)
        except Exception:
            logger.warning("Failed to cancel subscription %s", subscription_uri, exc_info=True)
            self._store.remove(subscription_uri)
            return False

        self._store.remove(subscription_uri)
        logger.info("Cancelled subscription %s", subscription_uri)
        return True

    async def _cancel_one(self, subscription_uri: str) -> bool:
        """Cancel a single subscription (DELETE only, no dict mutation).

        Unmanaged subscriptions skip the DELETE.
        """
        state = self._store.get(subscription_uri)
        if state is not None and state.unmanaged:
            logger.info("Skipping DELETE for unmanaged subscription %s", subscription_uri)
            return True
        try:
            await self._client.delete(subscription_uri)
            logger.info("Cancelled subscription %s", subscription_uri)
            return True
        except Exception:
            logger.warning("Failed to cancel subscription %s", subscription_uri, exc_info=True)
            return False

    async def cancel_all(self, timeout: float | None = None) -> None:
        """Cancel all active subscriptions in parallel, tolerating individual errors.

        ``timeout`` bounds the whole call, in seconds; ``None`` waits for every
        DELETE. A DELETE still unanswered when it elapses is abandoned, and its
        subscription stays on the server, as it would after a crash. Without the bound, one
        server that accepts the connection and never answers holds the caller
        for the HTTP client's full read timeout, and one that cannot be reached
        for every connection attempt and retry: 15 to 30 s of a service stop
        spent waiting on a request whose outcome changes nothing locally.

        Does nothing in a manager that does not maintain the set (see
        :attr:`maintains_set`): the subscriptions belong to every process
        sharing the store.
        """
        if not self.maintains_set:
            self._refuse("cancelling the subscription set")
            return
        uris = [s.subscription_uri for s in self._store.values()]
        if not uris:
            return
        tasks = [asyncio.ensure_future(self._cancel_one(uri)) for uri in uris]
        try:
            _, pending = await asyncio.wait(tasks, timeout=timeout)
            if pending:
                logger.warning(
                    "Abandoned %d subscription cancellation(s) still unanswered after %.1f s",
                    len(pending),
                    timeout,
                )
        finally:
            # Also reached when the caller is cancelled: no DELETE outlives the call.
            for task in tasks:
                task.cancel()
            await asyncio.gather(*tasks, return_exceptions=True)
            # Always clear all local state -- stale entries block re-subscription
            for uri in uris:
                self._store.remove(uri)

    async def reconcile(
        self,
        sub_list_href: str,
        desired: set[tuple[str, str]],
        *,
        renew_kept: bool = True,
        cancel_unwanted: bool = True,
    ) -> ReconcileResult:
        """Diff-based subscription reconciliation.

        Compares active subscriptions against *desired* (a set of
        ``(subscribed_resource, resource_type)`` tuples) and issues the
        necessary CANCEL / CREATE calls.  When ``renew_kept`` is True,
        subscriptions present in both sets are renewed (re-POSTed) to verify
        they still exist on the server; if a renewal fails (e.g. the server was
        reset), the subscription is cancelled locally and recreated.

        Args:
            sub_list_href: Server SubscriptionList path for new POSTs.
            desired: Target subscription set after rediscovery.
            renew_kept: Re-POST kept subscriptions to verify server-side
                validity. Pass False from the rediscovery path: re-POSTing on
                every rediscovery provokes some servers to echo a current-state
                notification, which the client classifies as a structural
                change and rediscovers again -- an infinite loop. Subscription
                lifetime is the periodic renewal task's responsibility, not
                rediscovery's.
            cancel_unwanted: Cancel subscriptions for resources not in
                ``desired``. Pass False from a process that acts for only some
                of the client's EndDevices and shares the subscription set: a
                resource it does not want may be one another process needs.
                Such a subscription is then left as it is, and so is one whose
                resource type changed.

        A manager that does not maintain the set (see :attr:`maintains_set`)
        reconciles as if ``renew_kept`` and ``cancel_unwanted`` were both
        False, and removes no record. A resource whose subscription the server
        cancelled with status 1 is not subscribed again (see
        :meth:`suppress_resubscribe`).

        Returns:
            ReconcileResult with counts for each action taken.
        """
        result = ReconcileResult()
        if not self.maintains_set:
            renew_kept = False
            cancel_unwanted = False

        # Build lookup of active subs keyed by subscribed_resource
        old_by_resource: dict[str, SubscriptionState] = {}
        for state in self._store.values():
            if state.status != "active":
                # Clean up stale cancelled entries. A status=1 record stays: it
                # tells every manager sharing the store not to subscribe again.
                if self.maintains_set and not state.resubscribe_suppressed:
                    self._store.remove(state.subscription_uri)
                continue
            old_by_resource[state.subscribed_resource] = state

        desired_map: dict[str, str] = dict(desired)

        old_resources = set(old_by_resource)
        desired_resources = set(desired_map)

        # Partition into keep / cancel / create, accounting for type changes
        keep_resources: set[str] = set()
        cancel_resources: set[str] = set()
        create_resources: set[str] = set()

        for resource in old_resources & desired_resources:
            if old_by_resource[resource].resource_type == desired_map[resource]:
                keep_resources.add(resource)
            else:
                # Type changed: cancel old, create new
                cancel_resources.add(resource)
                create_resources.add(resource)

        cancel_resources |= old_resources - desired_resources
        create_resources |= desired_resources - old_resources
        if not cancel_unwanted:
            keep_resources |= cancel_resources & desired_resources
            create_resources -= cancel_resources
            cancel_resources = set()
        create_resources = {r for r in create_resources if not self.resubscribe_suppressed(r)}

        # CANCEL stale subscriptions (parallel)
        cancel_uris = [old_by_resource[r].subscription_uri for r in cancel_resources]
        if cancel_uris:
            cancel_outcomes = await asyncio.gather(
                *(self._cancel_one(uri) for uri in cancel_uris),
                return_exceptions=True,
            )
            for uri, ok in zip(cancel_uris, cancel_outcomes, strict=True):
                self._store.remove(uri)
                result.cancelled += 1
                if isinstance(ok, BaseException) or not ok:
                    result.cancel_errors += 1

        # KEEP stable subscriptions. When renew_kept, re-POST in parallel to
        # verify server-side validity (recreating any the server dropped);
        # otherwise keep them as-is without touching the wire.
        keep_list = [(r, old_by_resource[r]) for r in keep_resources]
        if keep_list and renew_kept:
            renew_outcomes = await asyncio.gather(
                *(self.renew(state.subscription_uri) for _, state in keep_list),
                return_exceptions=True,
            )
            for (resource, state), ok in zip(keep_list, renew_outcomes, strict=True):
                if isinstance(ok, BaseException) or not ok:
                    if not self._is_active(state.subscription_uri):
                        # Cancelled or removed while the renewal was in flight.
                        continue
                    # Renewal failed -- subscription is stale on server.
                    # Cancel local state and fall through to CREATE.
                    self._store.remove(state.subscription_uri)
                    create_resources.add(resource)
                    result.cancelled += 1
                else:
                    result.kept += 1
                    result.renewed += 1
        elif keep_list:
            result.kept += len(keep_list)

        # CREATE new subscriptions (parallel)
        create_list = [(r, desired_map[r]) for r in create_resources]
        if create_list:
            create_outcomes = await asyncio.gather(
                *(self.subscribe(sub_list_href, r, rtype) for r, rtype in create_list),
                return_exceptions=True,
            )
            for _, sub_state in zip(create_list, create_outcomes, strict=True):
                if isinstance(sub_state, BaseException) or sub_state is None:
                    result.create_errors += 1
                else:
                    result.created += 1

        logger.info(
            "Reconciled subscriptions: kept=%d cancelled=%d created=%d "
            "renewed=%d cancel_errors=%d create_errors=%d",
            result.kept,
            result.cancelled,
            result.created,
            result.renewed,
            result.cancel_errors,
            result.create_errors,
        )
        return result

    async def reconcile_with_server(
        self,
        sub_list_href: str,
        *,
        reestablish_missing: bool = True,
        resources: set[str] | None = None,
    ) -> int:
        """Reconcile local subscriptions against the server's SubscriptionList.

        GETs the server's SubscriptionList and:
        - **adopts the server's current URI** for any resource whose local URI has
          drifted (server dropped+recreated or renumbered the subscription) -- a
          local re-key, no wire writes; and
        - when ``reestablish_missing`` is True, **re-POSTs** any subscription that
          is active locally but absent from the server's list (e.g. dropped after
          a notification-delivery failure). Returns the number re-established.

        Pass ``reestablish_missing=False`` from the rediscovery path: re-POSTing
        during rediscovery can make some servers echo a current-state
        notification, which the client classifies as a structural change and
        rediscovers again -- an infinite loop. With
        ``reestablish_missing=False`` this method makes no POSTs: it adopts a
        drifted URI (local re-key) and, for a subscription the server no longer
        has at all, *drops* the stale local entry rather than re-POSTing it.
        Re-subscription of the (still-desired) resource is handled by
        ``_auto_subscribe`` after rediscovery, as a normal new subscription.

        Only subscriptions with this manager's notificationURI count, as for
        :meth:`adopt_existing`.

        One-way: server-side subscriptions we don't track are left untouched. Per
        IEEE 2030.5 this is meant to run at the SubscriptionList ``pollRate``
        (default 900s); the SubscriptionList isn't itself subscribed, so §8.9.3.4
        rule (r) doesn't prohibit polling it.

        ``resources`` limits the drop and the re-POST to the subscriptions for
        those resources. A record for any other resource is left for a later
        pass that re-establishes it. A record created, renewed or re-keyed while
        the GET was in flight is left as it is, because the list cannot show
        it. A manager that does not maintain the set (see
        :attr:`maintains_set`) does nothing and returns 0.
        """
        from py20305.diagnostics import report
        from py20305.models.sep.sep import SubscriptionList

        if not self.maintains_set:
            self._refuse("reconciling with the server's SubscriptionList")
            return 0
        # The records as they were when the GET was sent: href -> renewal time.
        before = {s.subscription_uri: s.created_at for s in self.active_subscriptions}
        try:
            pages = await self._client.get_list(sub_list_href, SubscriptionList)
        except Exception as exc:  # a poll-time GET must never throw out of the loop
            # Any GET failure (HTTP error, transport/OSError, malformed payload)
            # is a logged no-op; the next reconcile tick retries.
            status = getattr(exc, "status_code", None)
            report(
                "warnings",
                f"SubscriptionList reconcile GET failed at {sub_list_href}: {exc}",
                source="subscription",
                dedup_key=f"sub_reconcile_get:{sub_list_href}",
                details={"sub_list_href": sub_list_href, "status": status},
            )
            return 0

        # Track resource *presence* separately from the server's URI. A server
        # entry may carry a subscribedResource but an empty/missing href
        # (Resource.href is optional), and resource presence -- not href -- is what
        # gates re-establishment (matching the prior semantics). The href only
        # gates URI adoption: if the server dropped and recreated (or renumbered)
        # the subscription for a resource, it's still present but under a new URI,
        # and our stale local URI would 404 on a later cancel/renew.
        server_resources: set[str] = set()
        server_uri_by_resource: dict[str, str] = {}
        for page in pages:
            for sub in page.subscription or []:
                if not sub.subscribed_resource:
                    continue
                # Only our own subscriptions, as adoption counts them: another
                # client's subscription to the same resource is not ours to
                # re-key to, renew or DELETE.
                if notification_uri_key(sub.notification_uri) != self._notification_key:
                    continue
                server_resources.add(sub.subscribed_resource)
                if sub.href:
                    server_uri_by_resource[sub.subscribed_resource] = sub.href

        re_established = 0
        adopted = 0
        dropped = 0
        for state in list(self.active_subscriptions):
            if state.unmanaged:
                continue  # operator/externally-managed -- we don't own its lifecycle
            if before.get(state.subscription_uri) != state.created_at:
                continue  # created, renewed or re-keyed after the GET was sent
            if state.subscribed_resource in server_resources:
                # Resource is subscribed on the server. Adopt the server's URI only
                # when it gave us a non-empty href that differs from our local one,
                # so what we report/cancel/renew matches what the server holds.
                server_uri = server_uri_by_resource.get(state.subscribed_resource)
                if server_uri is not None and server_uri != state.subscription_uri:
                    self._store.remove(state.subscription_uri)
                    state.subscription_uri = server_uri
                    self._store.put(state)
                    adopted += 1
                continue
            if resources is not None and state.subscribed_resource not in resources:
                continue
            if not reestablish_missing:
                # Rediscovery path: don't re-POST (echo-loop risk). If the server
                # returned a *populated* SubscriptionList that omits this resource,
                # it genuinely dropped the subscription -- drop our stale local
                # entry so we don't keep reporting (or later cancel/renew) a URI
                # the server 404s on. The resource is still desired, so
                # _auto_subscribe (run at the end of rediscovery) re-subscribes it
                # with a fresh URI as a normal new subscription. We require a
                # non-empty list so an empty/unhelpful response can't wipe every
                # local subscription.
                if server_resources:
                    logger.info(
                        "Subscription for %s absent from a populated server "
                        "SubscriptionList; dropping stale local entry "
                        "(rediscovery re-subscribes)",
                        state.subscribed_resource,
                    )
                    self._store.remove(state.subscription_uri)
                    dropped += 1
                continue
            logger.info(
                "Subscription for %s missing from server SubscriptionList; re-establishing",
                state.subscribed_resource,
            )
            # Drop the stale entry so subscribe() actually re-POSTs (it dedups on
            # active local state). Restore it if the re-POST fails transiently, so
            # the next reconcile retries instead of silently forgetting the sub
            # (which, if it were the last one, would stop the reconcile poll).
            self._store.remove(state.subscription_uri)
            if await self.subscribe(sub_list_href, state.subscribed_resource, state.resource_type):
                re_established += 1
            else:
                self._store.put(state)
        if re_established:
            logger.info("Reconcile re-established %d dropped subscription(s)", re_established)
        if adopted:
            logger.info("Reconcile adopted %d server-side subscription URI(s)", adopted)
        if dropped:
            logger.info("Reconcile dropped %d stale subscription(s) absent from server", dropped)
        return re_established

    async def adopt_existing(
        self,
        sub_list_href: str,
        desired: set[tuple[str, str]],
        *,
        remove_duplicates: bool = False,
    ) -> AdoptionResult:
        """Take over subscriptions the server already holds for this client.

        For a client that takes over from another instance of itself: both use
        the same certificate, so the same EndDevice and SubscriptionList, and
        the same notificationURI. Without adoption the new instance POSTs a new
        subscription for each resource, and a server that does not treat that
        POST as a renewal keeps both, so every notification arrives twice.

        GETs every page of the SubscriptionList at ``sub_list_href`` (IEEE
        2030.5-2023 Annex A.2.7.1: GET is Mandatory). A listed Subscription is
        ours when its notificationURI equals this manager's and its
        subscribedResource is one of ``desired`` (``(subscribed_resource,
        resource_type)`` tuples, as for :meth:`reconcile`). Both are compared
        as exact strings. For each such resource the first listed subscription
        is adopted, unless one of them is already tracked locally, in which case
        that one is kept. A subscription without an href is skipped: it cannot
        be renewed or cancelled. The adopted subscription keeps its href, and
        :meth:`subscribe` then finds it and makes no POST for that resource.

        IEEE 2030.5-2023 §8.9.3.4 treats a second Subscription to the same
        resource from the same client as a renewal, so a server that follows
        it holds no duplicates. The others are what ``remove_duplicates`` is
        for: it DELETEs the further subscriptions of ours for an adopted or
        tracked resource (Annex A.2.7.2: DELETE is Mandatory).

        Never touched: a subscription with another notificationURI, and one of
        ours for a resource not in ``desired``.

        When the SubscriptionList cannot be read (an HTTP error, a transport
        failure or a malformed body), the failure is reported and nothing
        changes; the client then subscribes as it would without adoption.

        An adopted subscription's last renewal time is unknown. Under the
        ``put`` renewal method it is renewed at once, at its own href. Under
        ``post`` it is recorded as due and the renewal task renews it on its
        first pass: a re-POST to a server that does not apply the renewal rule
        would create the duplicate adoption avoids.

        A manager that does not maintain the set (see :attr:`maintains_set`)
        records what it adopts but renews and DELETEs nothing. The manager that
        maintains the set renews the adopted records when they fall due.
        """
        from py20305.diagnostics import report
        from py20305.models.sep.sep import SubscriptionList

        result = AdoptionResult()
        try:
            pages = await self._client.get_list(sub_list_href, SubscriptionList)
        except Exception as exc:  # adoption is optional: any failure falls back to POSTing
            status = getattr(exc, "status_code", None)
            report(
                "warnings",
                (
                    f"Cannot read the SubscriptionList at {sub_list_href} to adopt "
                    f"existing subscriptions ({exc}); creating subscriptions instead"
                ),
                source="subscription",
                dedup_key=f"sub_adopt_get:{sub_list_href}",
                details={"sub_list_href": sub_list_href, "status": status},
            )
            return result
        result.listed = True

        desired_types = dict(desired)
        # subscribedResource -> hrefs of our subscriptions to it, in server order.
        ours: dict[str, list[str]] = {}
        for page in pages:
            for sub in page.subscription or []:
                resource = sub.subscribed_resource
                # The server may echo our notificationURI in an equivalent form.
                if notification_uri_key(sub.notification_uri) != self._notification_key:
                    continue
                if not resource or resource not in desired_types or not sub.href:
                    continue
                hrefs = ours.setdefault(resource, [])
                if sub.href not in hrefs:
                    hrefs.append(sub.href)

        extras: list[str] = []
        adopted_hrefs: list[str] = []
        for resource, hrefs in ours.items():
            local = self._find_active_for_resource(resource)
            if local is not None and local.unmanaged:
                continue  # tracked under a synthetic URI; the server's hrefs cannot be matched
            if local is not None and local.subscription_uri in hrefs:
                keep = local.subscription_uri
            elif local is not None:
                # Tracked under an href the server no longer lists: re-key it.
                keep = hrefs[0]
                self._store.remove(local.subscription_uri)
                local.subscription_uri = keep
                local.sub_list_href = sub_list_href
                self._store.put(local)
                adopted_hrefs.append(keep)
                result.adopted += 1
            else:
                keep = hrefs[0]
                resource_type = desired_types[resource]
                self._store.put(
                    SubscriptionState(
                        subscription_uri=keep,
                        subscribed_resource=resource,
                        notification_uri=self._notification_uri,
                        resource_type=resource_type,
                        created_at=0.0,
                        is_list_subscription=resource_type.endswith("List"),
                        sub_list_href=sub_list_href,
                    )
                )
                adopted_hrefs.append(keep)
                result.adopted += 1
                logger.info("Adopted subscription %s for %s", keep, resource)
            extras.extend(h for h in hrefs if h != keep)

        result.duplicates = len(extras)
        if extras and remove_duplicates and not self.maintains_set:
            self._refuse("removing duplicate subscriptions")
        elif extras and remove_duplicates:
            outcomes = await asyncio.gather(
                *(self._client.delete(href) for href in extras), return_exceptions=True
            )
            for href, outcome in zip(extras, outcomes, strict=True):
                if isinstance(outcome, BaseException):
                    result.remove_errors += 1
                    logger.warning("Failed to remove duplicate subscription %s: %s", href, outcome)
                else:
                    result.removed += 1
                    logger.info("Removed duplicate subscription %s", href)
        elif extras:
            logger.info(
                "Found %d duplicate subscription(s) of ours on the server; left in place",
                len(extras),
            )

        if self._renewal_method == "put" and adopted_hrefs and self.maintains_set:
            await asyncio.gather(*(self.renew(h) for h in adopted_hrefs), return_exceptions=True)

        logger.info(
            "Subscription adoption: adopted=%d duplicates=%d removed=%d remove_errors=%d",
            result.adopted,
            result.duplicates,
            result.removed,
            result.remove_errors,
        )
        return result

    def record_notification(self, notification: StoredNotification) -> None:
        """Append a notification to the bounded store."""
        self._notifications.append(notification)

    def mark_cancelled(self, subscription_uri: str) -> None:
        """Mark a subscription as cancelled (server-initiated)."""
        state = self._store.get(subscription_uri)
        if state:
            state.status = "cancelled"
            self._store.put(state)

    def remove_notifications_for(self, subscribed_resource: str) -> None:
        """Remove all stored notifications for a given resource."""
        self._notifications = deque(
            (n for n in self._notifications if n.subscribed_resource != subscribed_resource),
            maxlen=self._notifications.maxlen,
        )

    @property
    def active_subscriptions(self) -> list[SubscriptionState]:
        """Return subscriptions with status 'active'."""
        return [s for s in self._store.values() if s.status == "active"]

    @property
    def notifications(self) -> list[StoredNotification]:
        """Return all stored notifications (oldest first)."""
        return list(self._notifications)

    def subscribed_resource_types(self) -> set[str]:
        """Return the set of resource_type values for active subscriptions."""
        return {s.resource_type for s in self._store.values() if s.status == "active"}

    @property
    def store(self) -> SubscriptionStore:
        """The store holding this manager's subscription records."""
        return self._store

    def to_checkpoint(self) -> dict[str, Any]:
        """Serialize subscription state for persistence."""
        from py20305.subscription.store import subscription_record

        return {"subscriptions": [subscription_record(s) for s in self._store.values()]}

    def restore_from_checkpoint(self, data: dict[str, Any]) -> None:
        """Replace the stored subscription records with those of a checkpoint."""
        from py20305.subscription.store import subscription_from_record

        for state in self._store.values():
            self._store.remove(state.subscription_uri)
        for entry in data.get("subscriptions", []):
            self._store.put(subscription_from_record(entry))

    async def validate_restored_subscriptions(self) -> tuple[int, int]:
        """Validate checkpoint-restored subscriptions by attempting renewal.

        Returns (valid_count, removed_count).  Subscriptions that fail
        renewal are removed from the active set. Returns (0, 0) without a
        request in a manager that does not maintain the set.
        """
        if not self.maintains_set:
            self._refuse("validating restored subscriptions")
            return 0, 0
        valid = 0
        removed = 0
        for uri in [s.subscription_uri for s in self._store.values()]:
            state = self._store.get(uri)
            if state is None or state.status != "active":
                continue
            if state.unmanaged:
                valid += 1
                continue
            if await self.renew(uri):
                valid += 1
            elif self._is_active(uri):
                self._store.remove(uri)
                removed += 1
                logger.info("Removed stale subscription %s (%s)", uri, state.resource_type)
        return valid, removed

    # ------------------------------------------------------------------
    # WP4b: Subscription renewal
    # ------------------------------------------------------------------

    async def renew(
        self,
        subscription_uri: str,
        *,
        encoding: int | None = None,
        level: str | None = None,
        limit: int | None = None,
    ) -> bool:
        """Renew a single subscription.

        Under the ``post`` renewal method the Subscription is re-POSTed to its
        SubscriptionList, which the server matches by notificationURI (IEEE
        2030.5 Annex C.9). Under ``put`` it is PUT to the subscription's own
        href (Annex A.2.7.2: PUT is Mandatory on a Subscription); a 404 or 405
        there means the server no longer holds that href, so a new
        subscription is POSTed to the list it was created on, without a
        rediscovery.

        Optional parameter overrides allow changing encoding, level, or limit
        during renewal (WP4c).

        The outcome is written back only if the record is still active when
        the server answers. A cancellation or removal made in the meantime, by
        this process or another one sharing the store, is kept.

        Returns True on success, False on failure. Returns False without a
        request in a manager that does not maintain the set.
        """
        if not self.maintains_set:
            self._refuse(f"renewing {subscription_uri}")
            return False
        state = self._store.get(subscription_uri)
        if state is None or state.status != "active":
            return False

        if state.unmanaged:
            state.created_at = time.time()
            self._store.put(state)
            logger.info("Renewed unmanaged subscription %s (timestamp only)", subscription_uri)
            return True

        sub = Subscription(
            subscribed_resource=state.subscribed_resource,
            encoding=encoding if encoding is not None else 0,
            level=level if level is not None else "+S1",
            limit=limit if limit is not None else 1,
            notification_uri=state.notification_uri,
        )

        # A subscription restored from a checkpoint written before the list
        # href was recorded falls back to its parent path.
        sub_list_href = state.sub_list_href or subscription_uri.rsplit("/", 1)[0]

        if self._renewal_method == "put":
            try:
                await self._client.put(subscription_uri, sub)
            except Sep2ProtocolError as exc:
                if exc.status_code not in _PUT_RENEWAL_FALLBACK_STATUSES:
                    return self._renewal_rejected(subscription_uri, exc)
                logger.info(
                    "PUT renewal of %s returned HTTP %d; creating a new subscription on %s",
                    subscription_uri,
                    exc.status_code,
                    sub_list_href,
                )
            except Exception as exc:
                return self._renewal_failed(subscription_uri, exc)
            else:
                if not self._is_active(subscription_uri):
                    return self._changed_during_renewal(subscription_uri)
                state.created_at = time.time()
                self._store.put(state)
                logger.info(
                    "Renewed subscription %s (%s) by PUT", subscription_uri, state.resource_type
                )
                return True

        try:
            location = await self._client.post(sub_list_href, sub)
        except Sep2ProtocolError as exc:
            return self._renewal_rejected(subscription_uri, exc)
        except Exception as exc:
            return self._renewal_failed(subscription_uri, exc)

        if not self._is_active(subscription_uri):
            return self._changed_during_renewal(subscription_uri)
        if location and location != subscription_uri:
            # Server returned a new URI on renewal
            self._store.remove(subscription_uri)
            state.subscription_uri = location

        state.created_at = time.time()
        self._store.put(state)
        logger.info("Renewed subscription %s (%s)", subscription_uri, state.resource_type)
        return True

    @staticmethod
    def _changed_during_renewal(subscription_uri: str) -> bool:
        """Log a renewal whose record was cancelled or removed meanwhile; return False."""
        logger.info(
            "Renewal of %s not recorded: the subscription was cancelled or removed meanwhile",
            subscription_uri,
        )
        return False

    def _renewal_rejected(self, subscription_uri: str, exc: Sep2ProtocolError) -> bool:
        """Report a renewal the server refused; returns False for ``renew``."""
        from py20305.diagnostics import report

        report(
            "warnings",
            f"Server rejected renewal of {subscription_uri}: HTTP {exc.status_code}",
            source="subscription",
            dedup_key=f"sub_renewal:{subscription_uri}",
            details={
                "subscription_uri": subscription_uri,
                "status_code": exc.status_code,
            },
        )
        if exc.status_code in _SUBSCRIPTION_LOST_STATUSES and self._on_subscription_lost:
            # Server forgot about this subscription (typical after a
            # server restart drops the in-memory subscription store).
            # Trigger rediscovery so a fresh subscribe cycle runs
            # against the server's current state; the rediscovery
            # primitive coalesces concurrent calls, so multiple
            # renewals firing this at once is safe.
            logger.info(
                "Renewal of %s returned HTTP %d -- server appears to have "
                "forgotten our subscription; triggering rediscovery",
                subscription_uri,
                exc.status_code,
            )
            callback = self._on_subscription_lost

            async def _fire() -> None:
                await callback()

            asyncio.create_task(  # noqa: RUF006 -- fire-and-forget by design
                _fire(),
                name="subscription-lost-rediscovery",
            )
        return False

    def _renewal_failed(self, subscription_uri: str, exc: Exception) -> bool:
        """Report a renewal that did not reach a server answer; returns False."""
        from py20305.diagnostics import report

        report(
            "warnings",
            f"Failed to renew subscription {subscription_uri}: {exc}",
            source="subscription",
            dedup_key=f"sub_renewal:{subscription_uri}",
            details={"subscription_uri": subscription_uri, "error": str(exc)},
            exc_info=True,
        )
        return False

    async def renew_all(self) -> int:
        """Renew all active subscriptions. Returns count of successful renewals."""
        if not self.maintains_set:
            self._refuse("renewing the subscription set")
            return 0
        count = 0
        for uri in [s.subscription_uri for s in self._store.values()]:
            state = self._store.get(uri)
            if state and state.status == "active" and await self.renew(uri):
                count += 1
        return count

    async def start_renewal_task(
        self,
        shutdown: asyncio.Event,
        interval_seconds: int = 86400,
    ) -> None:
        """Run subscription renewal loop until shutdown is signaled.

        Renews each subscription ``interval_seconds`` (default 24h) after it
        was created or last renewed. IEEE 2030.5 server-side subscriptions
        expire after 36h. The loop checks every ``interval_seconds / 24``, one
        hour at the default interval, and renews the subscriptions that are
        due. A subscription created or adopted at any time, also by another
        manager sharing the store, is therefore renewed at most one check late.
        The check interval also spaces out retries of a failed renewal
        (IEEE 2030.5-2023 8.9.3.4 a: renewals no more often than every hour).
        Returns at once in a manager that does not maintain the set.
        """
        if not self.maintains_set:
            return
        check_every = min(_RENEWAL_CHECK_SECONDS, interval_seconds / 24)
        while not shutdown.is_set():
            try:
                await asyncio.wait_for(shutdown.wait(), timeout=check_every)
                break  # shutdown signaled
            except TimeoutError:
                pass  # time to check

            now = time.time()
            for uri in [s.subscription_uri for s in self._store.values()]:
                state = self._store.get(uri)
                if state and state.status == "active":
                    age = now - state.created_at
                    if age >= interval_seconds:
                        await self.renew(uri)

    # ------------------------------------------------------------------
    # WP4d: Non-list vs list notification semantics
    # ------------------------------------------------------------------

    def should_process_notification(self, subscription_uri: str, resource_href: str) -> bool:
        """Check if a notification should be processed based on subscription type.

        Non-list resource subscriptions should not fire on ListLink attribute changes.
        """
        state = self._store.get(subscription_uri)
        if state is None:
            return True  # Unknown subscription, process anyway
        return state.is_list_subscription or resource_href == state.subscribed_resource

    def resource_type_for(self, subscription_uri: str) -> str | None:
        """Return the recorded resource_type for a subscription, or None.

        The type was assigned at subscribe time from the discovered topology
        (which link the client subscribed to), so it's independent of how the
        server names its URLs -- unlike inferring the type from the notification
        path. None when the subscription isn't tracked locally (callers fall back
        to a path heuristic).
        """
        state = self._store.get(subscription_uri)
        return state.resource_type if state is not None else None

    # ------------------------------------------------------------------
    # Duplicate notification suppression
    # ------------------------------------------------------------------

    _DEDUP_WINDOW: float = 5.0

    def is_duplicate_notification(self, resource_href: str) -> bool:
        """Return True if a notification for this resource was processed in the last 5 s.

        Otherwise record this notification as processed and return False. A
        suppressed notification may report a newer change than the one processed:
        call :meth:`followup_delay` to schedule the re-poll that picks it up.
        """
        now = time.monotonic()
        last = self._dedup_cache.get(resource_href)
        if last is not None and now - last < self._DEDUP_WINDOW:
            return True
        self._dedup_cache[resource_href] = now
        return False

    def followup_delay(self, resource_href: str) -> float | None:
        """Return the seconds until a suppressed notification's follow-up re-poll is due.

        The follow-up is due when the dedup window of ``resource_href`` ends.
        Return None when the resource has no dedup entry.

        An entry written by :meth:`record_notification_ancestry` gets a
        follow-up too. The targeted fetch behind it read the DERControlList,
        not the DERProgram, and the server may have changed the program or its
        default in the same burst. No resource version is available to prove
        the change was already read.
        """
        last = self._dedup_cache.get(resource_href)
        if last is None:
            return None
        return max(0.0, last + self._DEDUP_WINDOW - time.monotonic())

    def forget_notification(self, resource_href: str) -> None:
        """Forget that a notification for ``resource_href`` was seen.

        Called when acting on it failed, so a redelivery within the dedup
        window is processed rather than skipped as a duplicate.
        """
        self._dedup_cache.pop(resource_href, None)

    def record_notification_ancestry(self, resource_href: str) -> None:
        """Record program-scope parent paths in dedup cache after a targeted fetch.

        When a targeted fetch for /edev/1/derp/3/derc succeeds, record ancestor
        paths up to and including /derp (/edev/1/derp/3, /edev/1/derp) so that
        the server's same-batch DERProgram and DERProgramList notifications
        are not re-polled at once. Each one suppressed schedules a single
        follow-up re-poll when the window ends (see :meth:`followup_delay`), so
        a change to the program in the same burst is still read.

        Walk stops at /derp. FSAList (/edev/.../fsa, /edev/.../fsa/N) and
        EndDeviceList (/edev, /edev/N) ancestors represent independent structural
        changes that fire alongside /derc bursts during mid-test mutations
        (e.g. conformance test BASIC-003 remove_derp + add_fsa). Suppressing them would
        swallow legitimate full-rediscovery triggers.
        """
        now = time.monotonic()
        path = resource_href.rstrip("/")
        parts = path.strip("/").split("/")
        for i in range(len(parts) - 1, 0, -1):
            parent = "/" + "/".join(parts[:i])
            self._dedup_cache[parent] = now
            if parts[i - 1] == "derp":
                break
active_subscriptions property
active_subscriptions: list[SubscriptionState]

Return subscriptions with status 'active'.

notifications property
notifications: list[StoredNotification]

Return all stored notifications (oldest first).

store property
store: SubscriptionStore

The store holding this manager's subscription records.

suppress_resubscribe
suppress_resubscribe(subscribed_resource: str) -> None

Mark a resource as server-cancelled so auto-subscribe won't re-POST it.

Set on a status=1 (canceled, no additional info) termination: we honor the cancellation (poll the resource instead) rather than fighting the server by immediately re-subscribing. Persists across rediscovery; cleared by :meth:clear_resubscribe_suppression only on a genuine reconnect.

The mark is also written to the resource's cancelled records in the store, so every manager sharing the store honors it.

Source code in src/py20305/subscription/manager.py
def suppress_resubscribe(self, subscribed_resource: str) -> None:
    """Mark a resource as server-cancelled so auto-subscribe won't re-POST it.

    Set on a ``status=1`` (canceled, no additional info) termination: we
    honor the cancellation (poll the resource instead) rather than fighting
    the server by immediately re-subscribing. Persists across rediscovery;
    cleared by :meth:`clear_resubscribe_suppression` only on a genuine
    reconnect.

    The mark is also written to the resource's cancelled records in the
    store, so every manager sharing the store honors it.
    """
    self._resubscribe_suppressed.add(subscribed_resource)
    for state in self._store.values():
        if state.subscribed_resource == subscribed_resource and state.status != "active":
            state.resubscribe_suppressed = True
            self._store.put(state)
resubscribe_suppressed
resubscribe_suppressed(subscribed_resource: str) -> bool

True if auto-subscribe should skip this server-cancelled resource.

Source code in src/py20305/subscription/manager.py
def resubscribe_suppressed(self, subscribed_resource: str) -> bool:
    """True if auto-subscribe should skip this server-cancelled resource."""
    if subscribed_resource in self._resubscribe_suppressed:
        return True
    return any(
        state.resubscribe_suppressed and state.subscribed_resource == subscribed_resource
        for state in self._store.values()
    )
clear_resubscribe_suppression
clear_resubscribe_suppression() -> None

Clear all resubscribe suppression. Called only on a genuine reconnect (upstream restart), not on every rediscovery, so an honored status=1 cancellation survives the rediscovery storm.

A manager that maintains the set also removes the suppressed records from the store. One that does not clears only its own marks.

Source code in src/py20305/subscription/manager.py
def clear_resubscribe_suppression(self) -> None:
    """Clear all resubscribe suppression. Called only on a genuine reconnect
    (upstream restart), not on every rediscovery, so an honored status=1
    cancellation survives the rediscovery storm.

    A manager that maintains the set also removes the suppressed records
    from the store. One that does not clears only its own marks.
    """
    self._resubscribe_suppressed.clear()
    if not self.maintains_set:
        return
    for state in self._store.values():
        if state.resubscribe_suppressed:
            self._store.remove(state.subscription_uri)
subscribe async
subscribe(sub_list_href: str, subscribed_resource: str, resource_type: str, *, encoding: int = 0, level: str = '+S1', limit: int = 1) -> SubscriptionState | None

Create a subscription by POSTing to the server's SubscriptionList.

Parameters:

Name Type Description Default
sub_list_href str

Server path to SubscriptionList resource.

required
subscribed_resource str

Full resource path to subscribe to.

required
resource_type str

Human-readable type (e.g. "FSAList").

required
encoding int

0=XML, 1=EXI.

0
level str

Schema level string.

'+S1'
limit int

Max list items in notification.

1

Returns:

Type Description
SubscriptionState | None

SubscriptionState on success, None on failure.

Source code in src/py20305/subscription/manager.py
async def subscribe(
    self,
    sub_list_href: str,
    subscribed_resource: str,
    resource_type: str,
    *,
    encoding: int = 0,
    level: str = "+S1",
    limit: int = 1,
) -> SubscriptionState | None:
    """Create a subscription by POSTing to the server's SubscriptionList.

    Args:
        sub_list_href: Server path to SubscriptionList resource.
        subscribed_resource: Full resource path to subscribe to.
        resource_type: Human-readable type (e.g. "FSAList").
        encoding: 0=XML, 1=EXI.
        level: Schema level string.
        limit: Max list items in notification.

    Returns:
        SubscriptionState on success, None on failure.
    """
    # Dedup: return existing active subscription for the same resource
    existing = self._find_active_for_resource(subscribed_resource)
    if existing is not None:
        logger.debug(
            "Already subscribed to %s via %s, skipping POST",
            subscribed_resource,
            existing.subscription_uri,
        )
        return existing

    sub = Subscription(
        subscribed_resource=subscribed_resource,
        encoding=encoding,
        level=level,
        limit=limit,
        notification_uri=self._notification_uri,
    )

    try:
        location = await self._client.post(sub_list_href, sub)
    except Sep2ProtocolError as exc:
        from py20305.diagnostics import report

        report(
            "warnings",
            (
                f"Server rejected subscription to {subscribed_resource} at "
                f"{sub_list_href}: HTTP {exc.status_code}"
            ),
            source="subscription",
            dedup_key=f"subscribe:{subscribed_resource}",
            details={
                "subscribed_resource": subscribed_resource,
                "sub_list_href": sub_list_href,
                "status_code": exc.status_code,
            },
        )
        return None
    except Exception as exc:
        from py20305.diagnostics import report

        report(
            "warnings",
            f"Failed to subscribe to {subscribed_resource} at {sub_list_href}: {exc}",
            source="subscription",
            dedup_key=f"subscribe:{subscribed_resource}",
            details={
                "subscribed_resource": subscribed_resource,
                "sub_list_href": sub_list_href,
                "error": str(exc),
            },
            exc_info=True,
        )
        return None

    if not location:
        if self._missing_location_fallback:
            location = f"_synthetic:{subscribed_resource}"
            logger.info(
                "No Location header, using a synthetic URI for %s (missing_location_fallback)",
                subscribed_resource,
            )
            state = SubscriptionState(
                subscription_uri=location,
                subscribed_resource=subscribed_resource,
                notification_uri=self._notification_uri,
                resource_type=resource_type,
                is_list_subscription=resource_type.endswith("List"),
                unmanaged=True,
            )
            self._store.put(state)
            return state

        from py20305.diagnostics import report

        report(
            "warnings",
            f"No Location header for subscription to {subscribed_resource}",
            source="subscription",
            dedup_key=f"sub_no_location:{subscribed_resource}",
            details={"subscribed_resource": subscribed_resource},
        )
        return None

    state = SubscriptionState(
        subscription_uri=location,
        subscribed_resource=subscribed_resource,
        notification_uri=self._notification_uri,
        resource_type=resource_type,
        is_list_subscription=resource_type.endswith("List"),
        sub_list_href=sub_list_href,
    )
    self._store.put(state)
    logger.info("Subscribed to %s (%s) -> %s", subscribed_resource, resource_type, location)
    return state
cancel async
cancel(subscription_uri: str) -> bool

Cancel a subscription by DELETEing it on the server.

Returns True if the DELETE succeeded or the subscription was unknown. Always removes local state to prevent stale entries blocking re-subscription. Unmanaged subscriptions (2018 compat) skip the DELETE.

Returns False and changes nothing in a manager that does not maintain the set (see :attr:maintains_set).

Source code in src/py20305/subscription/manager.py
async def cancel(self, subscription_uri: str) -> bool:
    """Cancel a subscription by DELETEing it on the server.

    Returns True if the DELETE succeeded or the subscription was unknown.
    Always removes local state to prevent stale entries blocking re-subscription.
    Unmanaged subscriptions (2018 compat) skip the DELETE.

    Returns False and changes nothing in a manager that does not maintain
    the set (see :attr:`maintains_set`).
    """
    if not self.maintains_set:
        self._refuse(f"cancelling {subscription_uri}")
        return False
    state = self._store.get(subscription_uri)
    if state is not None and state.unmanaged:
        self._store.remove(subscription_uri)
        logger.info("Removed unmanaged subscription %s", subscription_uri)
        return True

    try:
        await self._client.delete(subscription_uri)
    except Exception:
        logger.warning("Failed to cancel subscription %s", subscription_uri, exc_info=True)
        self._store.remove(subscription_uri)
        return False

    self._store.remove(subscription_uri)
    logger.info("Cancelled subscription %s", subscription_uri)
    return True
cancel_all async
cancel_all(timeout: float | None = None) -> None

Cancel all active subscriptions in parallel, tolerating individual errors.

timeout bounds the whole call, in seconds; None waits for every DELETE. A DELETE still unanswered when it elapses is abandoned, and its subscription stays on the server, as it would after a crash. Without the bound, one server that accepts the connection and never answers holds the caller for the HTTP client's full read timeout, and one that cannot be reached for every connection attempt and retry: 15 to 30 s of a service stop spent waiting on a request whose outcome changes nothing locally.

Does nothing in a manager that does not maintain the set (see :attr:maintains_set): the subscriptions belong to every process sharing the store.

Source code in src/py20305/subscription/manager.py
async def cancel_all(self, timeout: float | None = None) -> None:
    """Cancel all active subscriptions in parallel, tolerating individual errors.

    ``timeout`` bounds the whole call, in seconds; ``None`` waits for every
    DELETE. A DELETE still unanswered when it elapses is abandoned, and its
    subscription stays on the server, as it would after a crash. Without the bound, one
    server that accepts the connection and never answers holds the caller
    for the HTTP client's full read timeout, and one that cannot be reached
    for every connection attempt and retry: 15 to 30 s of a service stop
    spent waiting on a request whose outcome changes nothing locally.

    Does nothing in a manager that does not maintain the set (see
    :attr:`maintains_set`): the subscriptions belong to every process
    sharing the store.
    """
    if not self.maintains_set:
        self._refuse("cancelling the subscription set")
        return
    uris = [s.subscription_uri for s in self._store.values()]
    if not uris:
        return
    tasks = [asyncio.ensure_future(self._cancel_one(uri)) for uri in uris]
    try:
        _, pending = await asyncio.wait(tasks, timeout=timeout)
        if pending:
            logger.warning(
                "Abandoned %d subscription cancellation(s) still unanswered after %.1f s",
                len(pending),
                timeout,
            )
    finally:
        # Also reached when the caller is cancelled: no DELETE outlives the call.
        for task in tasks:
            task.cancel()
        await asyncio.gather(*tasks, return_exceptions=True)
        # Always clear all local state -- stale entries block re-subscription
        for uri in uris:
            self._store.remove(uri)
reconcile async
reconcile(sub_list_href: str, desired: set[tuple[str, str]], *, renew_kept: bool = True, cancel_unwanted: bool = True) -> ReconcileResult

Diff-based subscription reconciliation.

Compares active subscriptions against desired (a set of (subscribed_resource, resource_type) tuples) and issues the necessary CANCEL / CREATE calls. When renew_kept is True, subscriptions present in both sets are renewed (re-POSTed) to verify they still exist on the server; if a renewal fails (e.g. the server was reset), the subscription is cancelled locally and recreated.

Parameters:

Name Type Description Default
sub_list_href str

Server SubscriptionList path for new POSTs.

required
desired set[tuple[str, str]]

Target subscription set after rediscovery.

required
renew_kept bool

Re-POST kept subscriptions to verify server-side validity. Pass False from the rediscovery path: re-POSTing on every rediscovery provokes some servers to echo a current-state notification, which the client classifies as a structural change and rediscovers again -- an infinite loop. Subscription lifetime is the periodic renewal task's responsibility, not rediscovery's.

True
cancel_unwanted bool

Cancel subscriptions for resources not in desired. Pass False from a process that acts for only some of the client's EndDevices and shares the subscription set: a resource it does not want may be one another process needs. Such a subscription is then left as it is, and so is one whose resource type changed.

True

A manager that does not maintain the set (see :attr:maintains_set) reconciles as if renew_kept and cancel_unwanted were both False, and removes no record. A resource whose subscription the server cancelled with status 1 is not subscribed again (see :meth:suppress_resubscribe).

Returns:

Type Description
ReconcileResult

ReconcileResult with counts for each action taken.

Source code in src/py20305/subscription/manager.py
async def reconcile(
    self,
    sub_list_href: str,
    desired: set[tuple[str, str]],
    *,
    renew_kept: bool = True,
    cancel_unwanted: bool = True,
) -> ReconcileResult:
    """Diff-based subscription reconciliation.

    Compares active subscriptions against *desired* (a set of
    ``(subscribed_resource, resource_type)`` tuples) and issues the
    necessary CANCEL / CREATE calls.  When ``renew_kept`` is True,
    subscriptions present in both sets are renewed (re-POSTed) to verify
    they still exist on the server; if a renewal fails (e.g. the server was
    reset), the subscription is cancelled locally and recreated.

    Args:
        sub_list_href: Server SubscriptionList path for new POSTs.
        desired: Target subscription set after rediscovery.
        renew_kept: Re-POST kept subscriptions to verify server-side
            validity. Pass False from the rediscovery path: re-POSTing on
            every rediscovery provokes some servers to echo a current-state
            notification, which the client classifies as a structural
            change and rediscovers again -- an infinite loop. Subscription
            lifetime is the periodic renewal task's responsibility, not
            rediscovery's.
        cancel_unwanted: Cancel subscriptions for resources not in
            ``desired``. Pass False from a process that acts for only some
            of the client's EndDevices and shares the subscription set: a
            resource it does not want may be one another process needs.
            Such a subscription is then left as it is, and so is one whose
            resource type changed.

    A manager that does not maintain the set (see :attr:`maintains_set`)
    reconciles as if ``renew_kept`` and ``cancel_unwanted`` were both
    False, and removes no record. A resource whose subscription the server
    cancelled with status 1 is not subscribed again (see
    :meth:`suppress_resubscribe`).

    Returns:
        ReconcileResult with counts for each action taken.
    """
    result = ReconcileResult()
    if not self.maintains_set:
        renew_kept = False
        cancel_unwanted = False

    # Build lookup of active subs keyed by subscribed_resource
    old_by_resource: dict[str, SubscriptionState] = {}
    for state in self._store.values():
        if state.status != "active":
            # Clean up stale cancelled entries. A status=1 record stays: it
            # tells every manager sharing the store not to subscribe again.
            if self.maintains_set and not state.resubscribe_suppressed:
                self._store.remove(state.subscription_uri)
            continue
        old_by_resource[state.subscribed_resource] = state

    desired_map: dict[str, str] = dict(desired)

    old_resources = set(old_by_resource)
    desired_resources = set(desired_map)

    # Partition into keep / cancel / create, accounting for type changes
    keep_resources: set[str] = set()
    cancel_resources: set[str] = set()
    create_resources: set[str] = set()

    for resource in old_resources & desired_resources:
        if old_by_resource[resource].resource_type == desired_map[resource]:
            keep_resources.add(resource)
        else:
            # Type changed: cancel old, create new
            cancel_resources.add(resource)
            create_resources.add(resource)

    cancel_resources |= old_resources - desired_resources
    create_resources |= desired_resources - old_resources
    if not cancel_unwanted:
        keep_resources |= cancel_resources & desired_resources
        create_resources -= cancel_resources
        cancel_resources = set()
    create_resources = {r for r in create_resources if not self.resubscribe_suppressed(r)}

    # CANCEL stale subscriptions (parallel)
    cancel_uris = [old_by_resource[r].subscription_uri for r in cancel_resources]
    if cancel_uris:
        cancel_outcomes = await asyncio.gather(
            *(self._cancel_one(uri) for uri in cancel_uris),
            return_exceptions=True,
        )
        for uri, ok in zip(cancel_uris, cancel_outcomes, strict=True):
            self._store.remove(uri)
            result.cancelled += 1
            if isinstance(ok, BaseException) or not ok:
                result.cancel_errors += 1

    # KEEP stable subscriptions. When renew_kept, re-POST in parallel to
    # verify server-side validity (recreating any the server dropped);
    # otherwise keep them as-is without touching the wire.
    keep_list = [(r, old_by_resource[r]) for r in keep_resources]
    if keep_list and renew_kept:
        renew_outcomes = await asyncio.gather(
            *(self.renew(state.subscription_uri) for _, state in keep_list),
            return_exceptions=True,
        )
        for (resource, state), ok in zip(keep_list, renew_outcomes, strict=True):
            if isinstance(ok, BaseException) or not ok:
                if not self._is_active(state.subscription_uri):
                    # Cancelled or removed while the renewal was in flight.
                    continue
                # Renewal failed -- subscription is stale on server.
                # Cancel local state and fall through to CREATE.
                self._store.remove(state.subscription_uri)
                create_resources.add(resource)
                result.cancelled += 1
            else:
                result.kept += 1
                result.renewed += 1
    elif keep_list:
        result.kept += len(keep_list)

    # CREATE new subscriptions (parallel)
    create_list = [(r, desired_map[r]) for r in create_resources]
    if create_list:
        create_outcomes = await asyncio.gather(
            *(self.subscribe(sub_list_href, r, rtype) for r, rtype in create_list),
            return_exceptions=True,
        )
        for _, sub_state in zip(create_list, create_outcomes, strict=True):
            if isinstance(sub_state, BaseException) or sub_state is None:
                result.create_errors += 1
            else:
                result.created += 1

    logger.info(
        "Reconciled subscriptions: kept=%d cancelled=%d created=%d "
        "renewed=%d cancel_errors=%d create_errors=%d",
        result.kept,
        result.cancelled,
        result.created,
        result.renewed,
        result.cancel_errors,
        result.create_errors,
    )
    return result
reconcile_with_server async
reconcile_with_server(sub_list_href: str, *, reestablish_missing: bool = True, resources: set[str] | None = None) -> int

Reconcile local subscriptions against the server's SubscriptionList.

GETs the server's SubscriptionList and: - adopts the server's current URI for any resource whose local URI has drifted (server dropped+recreated or renumbered the subscription) -- a local re-key, no wire writes; and - when reestablish_missing is True, re-POSTs any subscription that is active locally but absent from the server's list (e.g. dropped after a notification-delivery failure). Returns the number re-established.

Pass reestablish_missing=False from the rediscovery path: re-POSTing during rediscovery can make some servers echo a current-state notification, which the client classifies as a structural change and rediscovers again -- an infinite loop. With reestablish_missing=False this method makes no POSTs: it adopts a drifted URI (local re-key) and, for a subscription the server no longer has at all, drops the stale local entry rather than re-POSTing it. Re-subscription of the (still-desired) resource is handled by _auto_subscribe after rediscovery, as a normal new subscription.

Only subscriptions with this manager's notificationURI count, as for :meth:adopt_existing.

One-way: server-side subscriptions we don't track are left untouched. Per IEEE 2030.5 this is meant to run at the SubscriptionList pollRate (default 900s); the SubscriptionList isn't itself subscribed, so §8.9.3.4 rule (r) doesn't prohibit polling it.

resources limits the drop and the re-POST to the subscriptions for those resources. A record for any other resource is left for a later pass that re-establishes it. A record created, renewed or re-keyed while the GET was in flight is left as it is, because the list cannot show it. A manager that does not maintain the set (see :attr:maintains_set) does nothing and returns 0.

Source code in src/py20305/subscription/manager.py
async def reconcile_with_server(
    self,
    sub_list_href: str,
    *,
    reestablish_missing: bool = True,
    resources: set[str] | None = None,
) -> int:
    """Reconcile local subscriptions against the server's SubscriptionList.

    GETs the server's SubscriptionList and:
    - **adopts the server's current URI** for any resource whose local URI has
      drifted (server dropped+recreated or renumbered the subscription) -- a
      local re-key, no wire writes; and
    - when ``reestablish_missing`` is True, **re-POSTs** any subscription that
      is active locally but absent from the server's list (e.g. dropped after
      a notification-delivery failure). Returns the number re-established.

    Pass ``reestablish_missing=False`` from the rediscovery path: re-POSTing
    during rediscovery can make some servers echo a current-state
    notification, which the client classifies as a structural change and
    rediscovers again -- an infinite loop. With
    ``reestablish_missing=False`` this method makes no POSTs: it adopts a
    drifted URI (local re-key) and, for a subscription the server no longer
    has at all, *drops* the stale local entry rather than re-POSTing it.
    Re-subscription of the (still-desired) resource is handled by
    ``_auto_subscribe`` after rediscovery, as a normal new subscription.

    Only subscriptions with this manager's notificationURI count, as for
    :meth:`adopt_existing`.

    One-way: server-side subscriptions we don't track are left untouched. Per
    IEEE 2030.5 this is meant to run at the SubscriptionList ``pollRate``
    (default 900s); the SubscriptionList isn't itself subscribed, so §8.9.3.4
    rule (r) doesn't prohibit polling it.

    ``resources`` limits the drop and the re-POST to the subscriptions for
    those resources. A record for any other resource is left for a later
    pass that re-establishes it. A record created, renewed or re-keyed while
    the GET was in flight is left as it is, because the list cannot show
    it. A manager that does not maintain the set (see
    :attr:`maintains_set`) does nothing and returns 0.
    """
    from py20305.diagnostics import report
    from py20305.models.sep.sep import SubscriptionList

    if not self.maintains_set:
        self._refuse("reconciling with the server's SubscriptionList")
        return 0
    # The records as they were when the GET was sent: href -> renewal time.
    before = {s.subscription_uri: s.created_at for s in self.active_subscriptions}
    try:
        pages = await self._client.get_list(sub_list_href, SubscriptionList)
    except Exception as exc:  # a poll-time GET must never throw out of the loop
        # Any GET failure (HTTP error, transport/OSError, malformed payload)
        # is a logged no-op; the next reconcile tick retries.
        status = getattr(exc, "status_code", None)
        report(
            "warnings",
            f"SubscriptionList reconcile GET failed at {sub_list_href}: {exc}",
            source="subscription",
            dedup_key=f"sub_reconcile_get:{sub_list_href}",
            details={"sub_list_href": sub_list_href, "status": status},
        )
        return 0

    # Track resource *presence* separately from the server's URI. A server
    # entry may carry a subscribedResource but an empty/missing href
    # (Resource.href is optional), and resource presence -- not href -- is what
    # gates re-establishment (matching the prior semantics). The href only
    # gates URI adoption: if the server dropped and recreated (or renumbered)
    # the subscription for a resource, it's still present but under a new URI,
    # and our stale local URI would 404 on a later cancel/renew.
    server_resources: set[str] = set()
    server_uri_by_resource: dict[str, str] = {}
    for page in pages:
        for sub in page.subscription or []:
            if not sub.subscribed_resource:
                continue
            # Only our own subscriptions, as adoption counts them: another
            # client's subscription to the same resource is not ours to
            # re-key to, renew or DELETE.
            if notification_uri_key(sub.notification_uri) != self._notification_key:
                continue
            server_resources.add(sub.subscribed_resource)
            if sub.href:
                server_uri_by_resource[sub.subscribed_resource] = sub.href

    re_established = 0
    adopted = 0
    dropped = 0
    for state in list(self.active_subscriptions):
        if state.unmanaged:
            continue  # operator/externally-managed -- we don't own its lifecycle
        if before.get(state.subscription_uri) != state.created_at:
            continue  # created, renewed or re-keyed after the GET was sent
        if state.subscribed_resource in server_resources:
            # Resource is subscribed on the server. Adopt the server's URI only
            # when it gave us a non-empty href that differs from our local one,
            # so what we report/cancel/renew matches what the server holds.
            server_uri = server_uri_by_resource.get(state.subscribed_resource)
            if server_uri is not None and server_uri != state.subscription_uri:
                self._store.remove(state.subscription_uri)
                state.subscription_uri = server_uri
                self._store.put(state)
                adopted += 1
            continue
        if resources is not None and state.subscribed_resource not in resources:
            continue
        if not reestablish_missing:
            # Rediscovery path: don't re-POST (echo-loop risk). If the server
            # returned a *populated* SubscriptionList that omits this resource,
            # it genuinely dropped the subscription -- drop our stale local
            # entry so we don't keep reporting (or later cancel/renew) a URI
            # the server 404s on. The resource is still desired, so
            # _auto_subscribe (run at the end of rediscovery) re-subscribes it
            # with a fresh URI as a normal new subscription. We require a
            # non-empty list so an empty/unhelpful response can't wipe every
            # local subscription.
            if server_resources:
                logger.info(
                    "Subscription for %s absent from a populated server "
                    "SubscriptionList; dropping stale local entry "
                    "(rediscovery re-subscribes)",
                    state.subscribed_resource,
                )
                self._store.remove(state.subscription_uri)
                dropped += 1
            continue
        logger.info(
            "Subscription for %s missing from server SubscriptionList; re-establishing",
            state.subscribed_resource,
        )
        # Drop the stale entry so subscribe() actually re-POSTs (it dedups on
        # active local state). Restore it if the re-POST fails transiently, so
        # the next reconcile retries instead of silently forgetting the sub
        # (which, if it were the last one, would stop the reconcile poll).
        self._store.remove(state.subscription_uri)
        if await self.subscribe(sub_list_href, state.subscribed_resource, state.resource_type):
            re_established += 1
        else:
            self._store.put(state)
    if re_established:
        logger.info("Reconcile re-established %d dropped subscription(s)", re_established)
    if adopted:
        logger.info("Reconcile adopted %d server-side subscription URI(s)", adopted)
    if dropped:
        logger.info("Reconcile dropped %d stale subscription(s) absent from server", dropped)
    return re_established
adopt_existing async
adopt_existing(sub_list_href: str, desired: set[tuple[str, str]], *, remove_duplicates: bool = False) -> AdoptionResult

Take over subscriptions the server already holds for this client.

For a client that takes over from another instance of itself: both use the same certificate, so the same EndDevice and SubscriptionList, and the same notificationURI. Without adoption the new instance POSTs a new subscription for each resource, and a server that does not treat that POST as a renewal keeps both, so every notification arrives twice.

GETs every page of the SubscriptionList at sub_list_href (IEEE 2030.5-2023 Annex A.2.7.1: GET is Mandatory). A listed Subscription is ours when its notificationURI equals this manager's and its subscribedResource is one of desired ((subscribed_resource, resource_type) tuples, as for :meth:reconcile). Both are compared as exact strings. For each such resource the first listed subscription is adopted, unless one of them is already tracked locally, in which case that one is kept. A subscription without an href is skipped: it cannot be renewed or cancelled. The adopted subscription keeps its href, and :meth:subscribe then finds it and makes no POST for that resource.

IEEE 2030.5-2023 §8.9.3.4 treats a second Subscription to the same resource from the same client as a renewal, so a server that follows it holds no duplicates. The others are what remove_duplicates is for: it DELETEs the further subscriptions of ours for an adopted or tracked resource (Annex A.2.7.2: DELETE is Mandatory).

Never touched: a subscription with another notificationURI, and one of ours for a resource not in desired.

When the SubscriptionList cannot be read (an HTTP error, a transport failure or a malformed body), the failure is reported and nothing changes; the client then subscribes as it would without adoption.

An adopted subscription's last renewal time is unknown. Under the put renewal method it is renewed at once, at its own href. Under post it is recorded as due and the renewal task renews it on its first pass: a re-POST to a server that does not apply the renewal rule would create the duplicate adoption avoids.

A manager that does not maintain the set (see :attr:maintains_set) records what it adopts but renews and DELETEs nothing. The manager that maintains the set renews the adopted records when they fall due.

Source code in src/py20305/subscription/manager.py
async def adopt_existing(
    self,
    sub_list_href: str,
    desired: set[tuple[str, str]],
    *,
    remove_duplicates: bool = False,
) -> AdoptionResult:
    """Take over subscriptions the server already holds for this client.

    For a client that takes over from another instance of itself: both use
    the same certificate, so the same EndDevice and SubscriptionList, and
    the same notificationURI. Without adoption the new instance POSTs a new
    subscription for each resource, and a server that does not treat that
    POST as a renewal keeps both, so every notification arrives twice.

    GETs every page of the SubscriptionList at ``sub_list_href`` (IEEE
    2030.5-2023 Annex A.2.7.1: GET is Mandatory). A listed Subscription is
    ours when its notificationURI equals this manager's and its
    subscribedResource is one of ``desired`` (``(subscribed_resource,
    resource_type)`` tuples, as for :meth:`reconcile`). Both are compared
    as exact strings. For each such resource the first listed subscription
    is adopted, unless one of them is already tracked locally, in which case
    that one is kept. A subscription without an href is skipped: it cannot
    be renewed or cancelled. The adopted subscription keeps its href, and
    :meth:`subscribe` then finds it and makes no POST for that resource.

    IEEE 2030.5-2023 §8.9.3.4 treats a second Subscription to the same
    resource from the same client as a renewal, so a server that follows
    it holds no duplicates. The others are what ``remove_duplicates`` is
    for: it DELETEs the further subscriptions of ours for an adopted or
    tracked resource (Annex A.2.7.2: DELETE is Mandatory).

    Never touched: a subscription with another notificationURI, and one of
    ours for a resource not in ``desired``.

    When the SubscriptionList cannot be read (an HTTP error, a transport
    failure or a malformed body), the failure is reported and nothing
    changes; the client then subscribes as it would without adoption.

    An adopted subscription's last renewal time is unknown. Under the
    ``put`` renewal method it is renewed at once, at its own href. Under
    ``post`` it is recorded as due and the renewal task renews it on its
    first pass: a re-POST to a server that does not apply the renewal rule
    would create the duplicate adoption avoids.

    A manager that does not maintain the set (see :attr:`maintains_set`)
    records what it adopts but renews and DELETEs nothing. The manager that
    maintains the set renews the adopted records when they fall due.
    """
    from py20305.diagnostics import report
    from py20305.models.sep.sep import SubscriptionList

    result = AdoptionResult()
    try:
        pages = await self._client.get_list(sub_list_href, SubscriptionList)
    except Exception as exc:  # adoption is optional: any failure falls back to POSTing
        status = getattr(exc, "status_code", None)
        report(
            "warnings",
            (
                f"Cannot read the SubscriptionList at {sub_list_href} to adopt "
                f"existing subscriptions ({exc}); creating subscriptions instead"
            ),
            source="subscription",
            dedup_key=f"sub_adopt_get:{sub_list_href}",
            details={"sub_list_href": sub_list_href, "status": status},
        )
        return result
    result.listed = True

    desired_types = dict(desired)
    # subscribedResource -> hrefs of our subscriptions to it, in server order.
    ours: dict[str, list[str]] = {}
    for page in pages:
        for sub in page.subscription or []:
            resource = sub.subscribed_resource
            # The server may echo our notificationURI in an equivalent form.
            if notification_uri_key(sub.notification_uri) != self._notification_key:
                continue
            if not resource or resource not in desired_types or not sub.href:
                continue
            hrefs = ours.setdefault(resource, [])
            if sub.href not in hrefs:
                hrefs.append(sub.href)

    extras: list[str] = []
    adopted_hrefs: list[str] = []
    for resource, hrefs in ours.items():
        local = self._find_active_for_resource(resource)
        if local is not None and local.unmanaged:
            continue  # tracked under a synthetic URI; the server's hrefs cannot be matched
        if local is not None and local.subscription_uri in hrefs:
            keep = local.subscription_uri
        elif local is not None:
            # Tracked under an href the server no longer lists: re-key it.
            keep = hrefs[0]
            self._store.remove(local.subscription_uri)
            local.subscription_uri = keep
            local.sub_list_href = sub_list_href
            self._store.put(local)
            adopted_hrefs.append(keep)
            result.adopted += 1
        else:
            keep = hrefs[0]
            resource_type = desired_types[resource]
            self._store.put(
                SubscriptionState(
                    subscription_uri=keep,
                    subscribed_resource=resource,
                    notification_uri=self._notification_uri,
                    resource_type=resource_type,
                    created_at=0.0,
                    is_list_subscription=resource_type.endswith("List"),
                    sub_list_href=sub_list_href,
                )
            )
            adopted_hrefs.append(keep)
            result.adopted += 1
            logger.info("Adopted subscription %s for %s", keep, resource)
        extras.extend(h for h in hrefs if h != keep)

    result.duplicates = len(extras)
    if extras and remove_duplicates and not self.maintains_set:
        self._refuse("removing duplicate subscriptions")
    elif extras and remove_duplicates:
        outcomes = await asyncio.gather(
            *(self._client.delete(href) for href in extras), return_exceptions=True
        )
        for href, outcome in zip(extras, outcomes, strict=True):
            if isinstance(outcome, BaseException):
                result.remove_errors += 1
                logger.warning("Failed to remove duplicate subscription %s: %s", href, outcome)
            else:
                result.removed += 1
                logger.info("Removed duplicate subscription %s", href)
    elif extras:
        logger.info(
            "Found %d duplicate subscription(s) of ours on the server; left in place",
            len(extras),
        )

    if self._renewal_method == "put" and adopted_hrefs and self.maintains_set:
        await asyncio.gather(*(self.renew(h) for h in adopted_hrefs), return_exceptions=True)

    logger.info(
        "Subscription adoption: adopted=%d duplicates=%d removed=%d remove_errors=%d",
        result.adopted,
        result.duplicates,
        result.removed,
        result.remove_errors,
    )
    return result
record_notification
record_notification(notification: StoredNotification) -> None

Append a notification to the bounded store.

Source code in src/py20305/subscription/manager.py
def record_notification(self, notification: StoredNotification) -> None:
    """Append a notification to the bounded store."""
    self._notifications.append(notification)
mark_cancelled
mark_cancelled(subscription_uri: str) -> None

Mark a subscription as cancelled (server-initiated).

Source code in src/py20305/subscription/manager.py
def mark_cancelled(self, subscription_uri: str) -> None:
    """Mark a subscription as cancelled (server-initiated)."""
    state = self._store.get(subscription_uri)
    if state:
        state.status = "cancelled"
        self._store.put(state)
remove_notifications_for
remove_notifications_for(subscribed_resource: str) -> None

Remove all stored notifications for a given resource.

Source code in src/py20305/subscription/manager.py
def remove_notifications_for(self, subscribed_resource: str) -> None:
    """Remove all stored notifications for a given resource."""
    self._notifications = deque(
        (n for n in self._notifications if n.subscribed_resource != subscribed_resource),
        maxlen=self._notifications.maxlen,
    )
subscribed_resource_types
subscribed_resource_types() -> set[str]

Return the set of resource_type values for active subscriptions.

Source code in src/py20305/subscription/manager.py
def subscribed_resource_types(self) -> set[str]:
    """Return the set of resource_type values for active subscriptions."""
    return {s.resource_type for s in self._store.values() if s.status == "active"}
to_checkpoint
to_checkpoint() -> dict[str, Any]

Serialize subscription state for persistence.

Source code in src/py20305/subscription/manager.py
def to_checkpoint(self) -> dict[str, Any]:
    """Serialize subscription state for persistence."""
    from py20305.subscription.store import subscription_record

    return {"subscriptions": [subscription_record(s) for s in self._store.values()]}
restore_from_checkpoint
restore_from_checkpoint(data: dict[str, Any]) -> None

Replace the stored subscription records with those of a checkpoint.

Source code in src/py20305/subscription/manager.py
def restore_from_checkpoint(self, data: dict[str, Any]) -> None:
    """Replace the stored subscription records with those of a checkpoint."""
    from py20305.subscription.store import subscription_from_record

    for state in self._store.values():
        self._store.remove(state.subscription_uri)
    for entry in data.get("subscriptions", []):
        self._store.put(subscription_from_record(entry))
validate_restored_subscriptions async
validate_restored_subscriptions() -> tuple[int, int]

Validate checkpoint-restored subscriptions by attempting renewal.

Returns (valid_count, removed_count). Subscriptions that fail renewal are removed from the active set. Returns (0, 0) without a request in a manager that does not maintain the set.

Source code in src/py20305/subscription/manager.py
async def validate_restored_subscriptions(self) -> tuple[int, int]:
    """Validate checkpoint-restored subscriptions by attempting renewal.

    Returns (valid_count, removed_count).  Subscriptions that fail
    renewal are removed from the active set. Returns (0, 0) without a
    request in a manager that does not maintain the set.
    """
    if not self.maintains_set:
        self._refuse("validating restored subscriptions")
        return 0, 0
    valid = 0
    removed = 0
    for uri in [s.subscription_uri for s in self._store.values()]:
        state = self._store.get(uri)
        if state is None or state.status != "active":
            continue
        if state.unmanaged:
            valid += 1
            continue
        if await self.renew(uri):
            valid += 1
        elif self._is_active(uri):
            self._store.remove(uri)
            removed += 1
            logger.info("Removed stale subscription %s (%s)", uri, state.resource_type)
    return valid, removed
renew async
renew(subscription_uri: str, *, encoding: int | None = None, level: str | None = None, limit: int | None = None) -> bool

Renew a single subscription.

Under the post renewal method the Subscription is re-POSTed to its SubscriptionList, which the server matches by notificationURI (IEEE 2030.5 Annex C.9). Under put it is PUT to the subscription's own href (Annex A.2.7.2: PUT is Mandatory on a Subscription); a 404 or 405 there means the server no longer holds that href, so a new subscription is POSTed to the list it was created on, without a rediscovery.

Optional parameter overrides allow changing encoding, level, or limit during renewal (WP4c).

The outcome is written back only if the record is still active when the server answers. A cancellation or removal made in the meantime, by this process or another one sharing the store, is kept.

Returns True on success, False on failure. Returns False without a request in a manager that does not maintain the set.

Source code in src/py20305/subscription/manager.py
async def renew(
    self,
    subscription_uri: str,
    *,
    encoding: int | None = None,
    level: str | None = None,
    limit: int | None = None,
) -> bool:
    """Renew a single subscription.

    Under the ``post`` renewal method the Subscription is re-POSTed to its
    SubscriptionList, which the server matches by notificationURI (IEEE
    2030.5 Annex C.9). Under ``put`` it is PUT to the subscription's own
    href (Annex A.2.7.2: PUT is Mandatory on a Subscription); a 404 or 405
    there means the server no longer holds that href, so a new
    subscription is POSTed to the list it was created on, without a
    rediscovery.

    Optional parameter overrides allow changing encoding, level, or limit
    during renewal (WP4c).

    The outcome is written back only if the record is still active when
    the server answers. A cancellation or removal made in the meantime, by
    this process or another one sharing the store, is kept.

    Returns True on success, False on failure. Returns False without a
    request in a manager that does not maintain the set.
    """
    if not self.maintains_set:
        self._refuse(f"renewing {subscription_uri}")
        return False
    state = self._store.get(subscription_uri)
    if state is None or state.status != "active":
        return False

    if state.unmanaged:
        state.created_at = time.time()
        self._store.put(state)
        logger.info("Renewed unmanaged subscription %s (timestamp only)", subscription_uri)
        return True

    sub = Subscription(
        subscribed_resource=state.subscribed_resource,
        encoding=encoding if encoding is not None else 0,
        level=level if level is not None else "+S1",
        limit=limit if limit is not None else 1,
        notification_uri=state.notification_uri,
    )

    # A subscription restored from a checkpoint written before the list
    # href was recorded falls back to its parent path.
    sub_list_href = state.sub_list_href or subscription_uri.rsplit("/", 1)[0]

    if self._renewal_method == "put":
        try:
            await self._client.put(subscription_uri, sub)
        except Sep2ProtocolError as exc:
            if exc.status_code not in _PUT_RENEWAL_FALLBACK_STATUSES:
                return self._renewal_rejected(subscription_uri, exc)
            logger.info(
                "PUT renewal of %s returned HTTP %d; creating a new subscription on %s",
                subscription_uri,
                exc.status_code,
                sub_list_href,
            )
        except Exception as exc:
            return self._renewal_failed(subscription_uri, exc)
        else:
            if not self._is_active(subscription_uri):
                return self._changed_during_renewal(subscription_uri)
            state.created_at = time.time()
            self._store.put(state)
            logger.info(
                "Renewed subscription %s (%s) by PUT", subscription_uri, state.resource_type
            )
            return True

    try:
        location = await self._client.post(sub_list_href, sub)
    except Sep2ProtocolError as exc:
        return self._renewal_rejected(subscription_uri, exc)
    except Exception as exc:
        return self._renewal_failed(subscription_uri, exc)

    if not self._is_active(subscription_uri):
        return self._changed_during_renewal(subscription_uri)
    if location and location != subscription_uri:
        # Server returned a new URI on renewal
        self._store.remove(subscription_uri)
        state.subscription_uri = location

    state.created_at = time.time()
    self._store.put(state)
    logger.info("Renewed subscription %s (%s)", subscription_uri, state.resource_type)
    return True
renew_all async
renew_all() -> int

Renew all active subscriptions. Returns count of successful renewals.

Source code in src/py20305/subscription/manager.py
async def renew_all(self) -> int:
    """Renew all active subscriptions. Returns count of successful renewals."""
    if not self.maintains_set:
        self._refuse("renewing the subscription set")
        return 0
    count = 0
    for uri in [s.subscription_uri for s in self._store.values()]:
        state = self._store.get(uri)
        if state and state.status == "active" and await self.renew(uri):
            count += 1
    return count
start_renewal_task async
start_renewal_task(shutdown: Event, interval_seconds: int = 86400) -> None

Run subscription renewal loop until shutdown is signaled.

Renews each subscription interval_seconds (default 24h) after it was created or last renewed. IEEE 2030.5 server-side subscriptions expire after 36h. The loop checks every interval_seconds / 24, one hour at the default interval, and renews the subscriptions that are due. A subscription created or adopted at any time, also by another manager sharing the store, is therefore renewed at most one check late. The check interval also spaces out retries of a failed renewal (IEEE 2030.5-2023 8.9.3.4 a: renewals no more often than every hour). Returns at once in a manager that does not maintain the set.

Source code in src/py20305/subscription/manager.py
async def start_renewal_task(
    self,
    shutdown: asyncio.Event,
    interval_seconds: int = 86400,
) -> None:
    """Run subscription renewal loop until shutdown is signaled.

    Renews each subscription ``interval_seconds`` (default 24h) after it
    was created or last renewed. IEEE 2030.5 server-side subscriptions
    expire after 36h. The loop checks every ``interval_seconds / 24``, one
    hour at the default interval, and renews the subscriptions that are
    due. A subscription created or adopted at any time, also by another
    manager sharing the store, is therefore renewed at most one check late.
    The check interval also spaces out retries of a failed renewal
    (IEEE 2030.5-2023 8.9.3.4 a: renewals no more often than every hour).
    Returns at once in a manager that does not maintain the set.
    """
    if not self.maintains_set:
        return
    check_every = min(_RENEWAL_CHECK_SECONDS, interval_seconds / 24)
    while not shutdown.is_set():
        try:
            await asyncio.wait_for(shutdown.wait(), timeout=check_every)
            break  # shutdown signaled
        except TimeoutError:
            pass  # time to check

        now = time.time()
        for uri in [s.subscription_uri for s in self._store.values()]:
            state = self._store.get(uri)
            if state and state.status == "active":
                age = now - state.created_at
                if age >= interval_seconds:
                    await self.renew(uri)
should_process_notification
should_process_notification(subscription_uri: str, resource_href: str) -> bool

Check if a notification should be processed based on subscription type.

Non-list resource subscriptions should not fire on ListLink attribute changes.

Source code in src/py20305/subscription/manager.py
def should_process_notification(self, subscription_uri: str, resource_href: str) -> bool:
    """Check if a notification should be processed based on subscription type.

    Non-list resource subscriptions should not fire on ListLink attribute changes.
    """
    state = self._store.get(subscription_uri)
    if state is None:
        return True  # Unknown subscription, process anyway
    return state.is_list_subscription or resource_href == state.subscribed_resource
resource_type_for
resource_type_for(subscription_uri: str) -> str | None

Return the recorded resource_type for a subscription, or None.

The type was assigned at subscribe time from the discovered topology (which link the client subscribed to), so it's independent of how the server names its URLs -- unlike inferring the type from the notification path. None when the subscription isn't tracked locally (callers fall back to a path heuristic).

Source code in src/py20305/subscription/manager.py
def resource_type_for(self, subscription_uri: str) -> str | None:
    """Return the recorded resource_type for a subscription, or None.

    The type was assigned at subscribe time from the discovered topology
    (which link the client subscribed to), so it's independent of how the
    server names its URLs -- unlike inferring the type from the notification
    path. None when the subscription isn't tracked locally (callers fall back
    to a path heuristic).
    """
    state = self._store.get(subscription_uri)
    return state.resource_type if state is not None else None
is_duplicate_notification
is_duplicate_notification(resource_href: str) -> bool

Return True if a notification for this resource was processed in the last 5 s.

Otherwise record this notification as processed and return False. A suppressed notification may report a newer change than the one processed: call :meth:followup_delay to schedule the re-poll that picks it up.

Source code in src/py20305/subscription/manager.py
def is_duplicate_notification(self, resource_href: str) -> bool:
    """Return True if a notification for this resource was processed in the last 5 s.

    Otherwise record this notification as processed and return False. A
    suppressed notification may report a newer change than the one processed:
    call :meth:`followup_delay` to schedule the re-poll that picks it up.
    """
    now = time.monotonic()
    last = self._dedup_cache.get(resource_href)
    if last is not None and now - last < self._DEDUP_WINDOW:
        return True
    self._dedup_cache[resource_href] = now
    return False
followup_delay
followup_delay(resource_href: str) -> float | None

Return the seconds until a suppressed notification's follow-up re-poll is due.

The follow-up is due when the dedup window of resource_href ends. Return None when the resource has no dedup entry.

An entry written by :meth:record_notification_ancestry gets a follow-up too. The targeted fetch behind it read the DERControlList, not the DERProgram, and the server may have changed the program or its default in the same burst. No resource version is available to prove the change was already read.

Source code in src/py20305/subscription/manager.py
def followup_delay(self, resource_href: str) -> float | None:
    """Return the seconds until a suppressed notification's follow-up re-poll is due.

    The follow-up is due when the dedup window of ``resource_href`` ends.
    Return None when the resource has no dedup entry.

    An entry written by :meth:`record_notification_ancestry` gets a
    follow-up too. The targeted fetch behind it read the DERControlList,
    not the DERProgram, and the server may have changed the program or its
    default in the same burst. No resource version is available to prove
    the change was already read.
    """
    last = self._dedup_cache.get(resource_href)
    if last is None:
        return None
    return max(0.0, last + self._DEDUP_WINDOW - time.monotonic())
forget_notification
forget_notification(resource_href: str) -> None

Forget that a notification for resource_href was seen.

Called when acting on it failed, so a redelivery within the dedup window is processed rather than skipped as a duplicate.

Source code in src/py20305/subscription/manager.py
def forget_notification(self, resource_href: str) -> None:
    """Forget that a notification for ``resource_href`` was seen.

    Called when acting on it failed, so a redelivery within the dedup
    window is processed rather than skipped as a duplicate.
    """
    self._dedup_cache.pop(resource_href, None)
record_notification_ancestry
record_notification_ancestry(resource_href: str) -> None

Record program-scope parent paths in dedup cache after a targeted fetch.

When a targeted fetch for /edev/1/derp/3/derc succeeds, record ancestor paths up to and including /derp (/edev/1/derp/3, /edev/1/derp) so that the server's same-batch DERProgram and DERProgramList notifications are not re-polled at once. Each one suppressed schedules a single follow-up re-poll when the window ends (see :meth:followup_delay), so a change to the program in the same burst is still read.

Walk stops at /derp. FSAList (/edev/.../fsa, /edev/.../fsa/N) and EndDeviceList (/edev, /edev/N) ancestors represent independent structural changes that fire alongside /derc bursts during mid-test mutations (e.g. conformance test BASIC-003 remove_derp + add_fsa). Suppressing them would swallow legitimate full-rediscovery triggers.

Source code in src/py20305/subscription/manager.py
def record_notification_ancestry(self, resource_href: str) -> None:
    """Record program-scope parent paths in dedup cache after a targeted fetch.

    When a targeted fetch for /edev/1/derp/3/derc succeeds, record ancestor
    paths up to and including /derp (/edev/1/derp/3, /edev/1/derp) so that
    the server's same-batch DERProgram and DERProgramList notifications
    are not re-polled at once. Each one suppressed schedules a single
    follow-up re-poll when the window ends (see :meth:`followup_delay`), so
    a change to the program in the same burst is still read.

    Walk stops at /derp. FSAList (/edev/.../fsa, /edev/.../fsa/N) and
    EndDeviceList (/edev, /edev/N) ancestors represent independent structural
    changes that fire alongside /derc bursts during mid-test mutations
    (e.g. conformance test BASIC-003 remove_derp + add_fsa). Suppressing them would
    swallow legitimate full-rediscovery triggers.
    """
    now = time.monotonic()
    path = resource_href.rstrip("/")
    parts = path.strip("/").split("/")
    for i in range(len(parts) - 1, 0, -1):
        parent = "/" + "/".join(parts[:i])
        self._dedup_cache[parent] = now
        if parts[i - 1] == "derp":
            break

notification_uri_key

notification_uri_key(uri: str | None) -> str | None

Return a normalized form of uri for comparing notificationURIs.

A server may echo a notificationURI in a different but equivalent form. The key lowercases the scheme and host, drops the scheme's default port, normalizes percent-encodings, and ignores a trailing slash on the path. A URI that does not parse is returned unchanged.

Source code in src/py20305/subscription/manager.py
def notification_uri_key(uri: str | None) -> str | None:
    """Return a normalized form of ``uri`` for comparing notificationURIs.

    A server may echo a notificationURI in a different but equivalent form. The
    key lowercases the scheme and host, drops the scheme's default port,
    normalizes percent-encodings, and ignores a trailing slash on the path.
    A URI that does not parse is returned unchanged.
    """
    if uri is None:
        return None
    try:
        parts = urlsplit(uri.strip())
        port = parts.port
    except ValueError:
        return uri
    scheme = parts.scheme.lower()
    host = parts.hostname or ""
    if ":" in host:
        host = f"[{host}]"
    if port is not None and port != _DEFAULT_PORTS.get(scheme):
        host = f"{host}:{port}"
    userinfo = parts.netloc.rpartition("@")[0]
    if userinfo:
        host = f"{userinfo}@{host}"
    path = _normalize_percent_encoding(parts.path).rstrip("/")
    query = _normalize_percent_encoding(parts.query)
    return f"{scheme}://{host}{path}" + (f"?{query}" if query else "")

py20305.subscription.store

Where a subscription manager keeps its subscription records.

A client's subscriptions belong to its EndDevice at the server: one SubscriptionList, one notificationURI. A host application that runs several client processes for one certificate gives every process's :class:~py20305.subscription.manager.SubscriptionManager the same store, so the processes see one subscription set. A process then finds a subscription another process created and makes no POST for that resource, and classifies a notification by the subscription record another process wrote.

The default, :class:MemorySubscriptionStore, keeps the records in a dict in the process, which is how the manager has always held them.

A record has the same fields as an entry of :meth:SubscriptionManager.to_checkpoint. :func:subscription_record and :func:subscription_from_record convert between the two, so a store backed by a database can keep rows in the checkpoint format.

SubscriptionStore

Bases: Protocol

The subscription records of one client, keyed by subscription href.

The manager calls these methods from its event loop and does not await them, so each call must return quickly: a local database, or a cache the host keeps in step with a shared one.

get and values may return copies. The manager calls put after every change it makes to a record, so a store that copies on read loses nothing.

Concurrency: the library takes no lock across processes. One manager maintains the set: only it renews, reconciles and cancels subscriptions. Every other manager is built with maintains_set=False, which a client without own-EndDevice work sets when the manager is attached, and only adds subscriptions for resources nobody has subscribed to yet. A manager re-reads a record after each await before writing it back, so a cancellation or removal written in the meantime is kept. Two processes that subscribe to the same resource at the same moment can both POST, because the lookup, the POST and the put are not one atomic step; see the guide for how to avoid it.

Source code in src/py20305/subscription/store.py
@runtime_checkable
class SubscriptionStore(Protocol):
    """The subscription records of one client, keyed by subscription href.

    The manager calls these methods from its event loop and does not await them,
    so each call must return quickly: a local database, or a cache the host keeps
    in step with a shared one.

    ``get`` and ``values`` may return copies. The manager calls ``put`` after
    every change it makes to a record, so a store that copies on read loses
    nothing.

    Concurrency: the library takes no lock across processes. One manager
    maintains the set: only it renews, reconciles and cancels subscriptions.
    Every other manager is built with ``maintains_set=False``, which a client
    without own-EndDevice work sets when the manager is attached, and only adds
    subscriptions for resources nobody has subscribed to yet. A manager re-reads
    a record after each await before writing it back, so a cancellation or
    removal written in the meantime is kept. Two processes that subscribe to the
    same resource at the same moment can both POST, because the lookup, the POST
    and the ``put`` are not one atomic step; see the guide for how to avoid it.
    """

    def get(self, subscription_uri: str) -> SubscriptionState | None:
        """Return the record for ``subscription_uri``, or None."""
        ...

    def put(self, state: SubscriptionState) -> None:
        """Insert or replace the record keyed by ``state.subscription_uri``."""
        ...

    def remove(self, subscription_uri: str) -> None:
        """Delete the record for ``subscription_uri``. An unknown href is not an error."""
        ...

    def values(self) -> list[SubscriptionState]:
        """Return every record, in insertion order where the store keeps one."""
        ...
get
get(subscription_uri: str) -> SubscriptionState | None

Return the record for subscription_uri, or None.

Source code in src/py20305/subscription/store.py
def get(self, subscription_uri: str) -> SubscriptionState | None:
    """Return the record for ``subscription_uri``, or None."""
    ...
put
put(state: SubscriptionState) -> None

Insert or replace the record keyed by state.subscription_uri.

Source code in src/py20305/subscription/store.py
def put(self, state: SubscriptionState) -> None:
    """Insert or replace the record keyed by ``state.subscription_uri``."""
    ...
remove
remove(subscription_uri: str) -> None

Delete the record for subscription_uri. An unknown href is not an error.

Source code in src/py20305/subscription/store.py
def remove(self, subscription_uri: str) -> None:
    """Delete the record for ``subscription_uri``. An unknown href is not an error."""
    ...
values
values() -> list[SubscriptionState]

Return every record, in insertion order where the store keeps one.

Source code in src/py20305/subscription/store.py
def values(self) -> list[SubscriptionState]:
    """Return every record, in insertion order where the store keeps one."""
    ...

MemorySubscriptionStore

Subscription records in a dict, in this process. The default store.

Returns the stored objects themselves, not copies, so two managers given the same instance in one process share one set of records.

Source code in src/py20305/subscription/store.py
class MemorySubscriptionStore:
    """Subscription records in a dict, in this process. The default store.

    Returns the stored objects themselves, not copies, so two managers given the
    same instance in one process share one set of records.
    """

    def __init__(self) -> None:
        self._records: dict[str, SubscriptionState] = {}

    def get(self, subscription_uri: str) -> SubscriptionState | None:
        """Return the record for ``subscription_uri``, or None."""
        return self._records.get(subscription_uri)

    def put(self, state: SubscriptionState) -> None:
        """Insert or replace the record keyed by ``state.subscription_uri``."""
        self._records[state.subscription_uri] = state

    def remove(self, subscription_uri: str) -> None:
        """Delete the record for ``subscription_uri``, if present."""
        self._records.pop(subscription_uri, None)

    def values(self) -> list[SubscriptionState]:
        """Return every record, in insertion order."""
        return list(self._records.values())
get
get(subscription_uri: str) -> SubscriptionState | None

Return the record for subscription_uri, or None.

Source code in src/py20305/subscription/store.py
def get(self, subscription_uri: str) -> SubscriptionState | None:
    """Return the record for ``subscription_uri``, or None."""
    return self._records.get(subscription_uri)
put
put(state: SubscriptionState) -> None

Insert or replace the record keyed by state.subscription_uri.

Source code in src/py20305/subscription/store.py
def put(self, state: SubscriptionState) -> None:
    """Insert or replace the record keyed by ``state.subscription_uri``."""
    self._records[state.subscription_uri] = state
remove
remove(subscription_uri: str) -> None

Delete the record for subscription_uri, if present.

Source code in src/py20305/subscription/store.py
def remove(self, subscription_uri: str) -> None:
    """Delete the record for ``subscription_uri``, if present."""
    self._records.pop(subscription_uri, None)
values
values() -> list[SubscriptionState]

Return every record, in insertion order.

Source code in src/py20305/subscription/store.py
def values(self) -> list[SubscriptionState]:
    """Return every record, in insertion order."""
    return list(self._records.values())

subscription_record

subscription_record(state: SubscriptionState) -> dict[str, Any]

Return state as a checkpoint entry: a dict of JSON types.

Source code in src/py20305/subscription/store.py
def subscription_record(state: SubscriptionState) -> dict[str, Any]:
    """Return ``state`` as a checkpoint entry: a dict of JSON types."""
    return {
        "subscription_uri": state.subscription_uri,
        "subscribed_resource": state.subscribed_resource,
        "notification_uri": state.notification_uri,
        "resource_type": state.resource_type,
        "status": state.status,
        "created_at": state.created_at,
        "is_list_subscription": state.is_list_subscription,
        "unmanaged": state.unmanaged,
        "sub_list_href": state.sub_list_href,
        "resubscribe_suppressed": state.resubscribe_suppressed,
    }

subscription_from_record

subscription_from_record(entry: dict[str, Any]) -> SubscriptionState

Build a record from a checkpoint entry. Absent optional fields take their defaults.

Source code in src/py20305/subscription/store.py
def subscription_from_record(entry: dict[str, Any]) -> SubscriptionState:
    """Build a record from a checkpoint entry. Absent optional fields take their defaults."""
    from py20305.subscription.manager import SubscriptionState

    return SubscriptionState(
        subscription_uri=entry["subscription_uri"],
        subscribed_resource=entry["subscribed_resource"],
        notification_uri=entry["notification_uri"],
        resource_type=entry["resource_type"],
        status=entry.get("status", "active"),
        created_at=entry.get("created_at", 0.0),
        is_list_subscription=entry.get("is_list_subscription", False),
        unmanaged=entry.get("unmanaged", False),
        sub_list_href=entry.get("sub_list_href"),
        resubscribe_suppressed=entry.get("resubscribe_suppressed", False),
    )

py20305.subscription.notification_server

Async notification server for IEEE 2030.5 subscription callbacks.

Receives POST /notify from the IEEE 2030.5 server when subscribed resources change. Runs in the same asyncio event loop as the client.

NotificationServer

Async HTTPS server that receives IEEE 2030.5 notification POSTs.

Runs in the client's event loop using aiohttp.web. Dispatches parsed Notification objects to a callback for processing.

Source code in src/py20305/subscription/notification_server.py
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
class NotificationServer:
    """Async HTTPS server that receives IEEE 2030.5 notification POSTs.

    Runs in the client's event loop using aiohttp.web. Dispatches
    parsed Notification objects to a callback for processing.
    """

    def __init__(
        self,
        host: str = "0.0.0.0",
        port: int = 10443,
        tls: TlsConfig | None = None,
        on_notification: NotificationCallback | None = None,
        client_cert_mode: ClientCertMode = "warn",
        traffic_recorder: TrafficRecorder | None = None,
        shutdown_timeout: float = 2.0,
        forward: NotificationForwarder | None = None,
    ) -> None:
        self._host = host
        # How long stop() lets a request still being received finish. aiohttp's
        # own default is 60 s, so one peer that stalls part way through a POST
        # would hold the stop for a minute. A notification handler answers as
        # soon as the body is parsed (the work runs in a background task), so a
        # request that needs longer than this is not one worth waiting for.
        self._shutdown_timeout = shutdown_timeout
        self._port = port
        self._tls = tls
        self._on_notification = on_notification
        self._forward = forward
        self._client_cert_mode: ClientCertMode = client_cert_mode
        self._traffic_recorder = traffic_recorder
        self._app: web.Application | None = None
        self._runner: web.AppRunner | None = None
        self._site: web.TCPSite | None = None
        self._background_tasks: set[asyncio.Task[None]] = set()
        # Set while an operator-triggered comms-loss simulation is running:
        # notifications are still accepted on the wire but are not acted on.
        self._suspended = False
        #: Receives one exchange record and one connection event per
        #: notification request, and an anomaly for each one refused or dropped.
        self.observers: Observers = NO_OBSERVERS
        self._observer_guard = ObserverGuard("notification observer")

    @property
    def on_notification(self) -> NotificationCallback | None:
        """The coroutine invoked with each parsed, accepted notification."""
        return self._on_notification

    @on_notification.setter
    def on_notification(self, callback: NotificationCallback | None) -> None:
        self._on_notification = callback

    @property
    def forward(self) -> NotificationForwarder | None:
        """The coroutine each accepted notification's raw body is handed to, if set.

        When set, the listener does not process notifications. It parses and
        checks each one as before, then awaits ``forward(body)`` and answers
        201 only after it returns. If it raises, the listener answers 503 so the
        server knows the delivery failed. Use it to put each notification on a
        queue that the process acting for the affected EndDevice reads, and
        hand it to :meth:`CsipClient.process_notification` there.

        None, the default, processes each notification here, after answering
        201, as before.
        """
        return self._forward

    @forward.setter
    def forward(self, callback: NotificationForwarder | None) -> None:
        self._forward = callback

    @property
    def suspended(self) -> bool:
        """Whether accepted notifications are being dropped instead of handled."""
        return self._suspended

    async def suspend(self, *, drain_timeout: float = 5.0) -> bool:
        """Stop acting on notifications, and wait for any already running.

        Returns whether the in-flight handlers finished in time. The wait is the
        point: this server answers 201 and hands the notification to a
        background task, so one accepted moments earlier is still running and
        can apply a control *after* the caller believes the link is down -- a
        fresh setpoint landing on a DER the operator thinks is isolated.

        A False return means handlers were still running when the timeout
        elapsed. New notifications are dropped either way, from the moment this
        is called.
        """
        self._suspended = True
        if not self._background_tasks:
            return True
        pending = tuple(self._background_tasks)
        _, still_running = await asyncio.wait(pending, timeout=drain_timeout)
        return not still_running

    def resume(self) -> None:
        """Act on notifications again."""
        self._suspended = False

    @property
    def port(self) -> int:
        return self._port

    @property
    def running(self) -> bool:
        return self._site is not None

    def build_notification_uri(self, external_host: str) -> str:
        """Build the fully-qualified notification URI for subscription requests."""
        return f"https://{external_host}:{self._port}/notify"

    async def start(self) -> None:
        """Start the notification server."""
        if self._site is not None:
            return

        self._app = web.Application()
        self._app.router.add_post("/notify", self._handle_notify)

        self._runner = web.AppRunner(self._app, shutdown_timeout=self._shutdown_timeout)
        await self._runner.setup()

        ssl_ctx = self._create_server_ssl_context()
        # SO_REUSEADDR lets the listener rebind to a port still in TIME_WAIT
        # from a previous instance — matters most in the cert e2e suite where
        # multiple clients are torn down and recreated in a single pytest
        # session. Production restarts after a clean shutdown don't need it
        # but it's harmless: SO_REUSEADDR doesn't allow stealing an active
        # listener's port, only re-binding to a TIME_WAIT port.
        self._site = web.TCPSite(
            self._runner,
            self._host,
            self._port,
            ssl_context=ssl_ctx,
            reuse_address=True,
        )
        await self._site.start()

        if ssl_ctx is None:
            cert_status = "disabled (plain HTTP)"
        elif self._client_cert_mode == "enforce":
            cert_status = "enforce (mTLS required; no-cert peers rejected with 401)"
        elif self._client_cert_mode == "warn":
            cert_status = "warn (mTLS optional; no-cert peers logged but accepted)"
        else:  # off
            cert_status = "off (TLS without client-cert verification)"

        logger.info(
            "NotificationServer started on %s:%d  client_cert_mode=%s",
            self._host,
            self._port,
            cert_status,
        )

    async def stop(self) -> None:
        """Gracefully stop the notification server."""
        # Cancel background notification tasks
        for task in self._background_tasks:
            task.cancel()
        if self._background_tasks:
            await asyncio.gather(*self._background_tasks, return_exceptions=True)
            self._background_tasks.clear()

        if self._site is not None:
            await self._site.stop()
            self._site = None
        if self._runner is not None:
            await self._runner.cleanup()
            self._runner = None
        self._app = None
        logger.info("NotificationServer stopped")

    def _create_server_ssl_context(self) -> ssl.SSLContext | None:
        """Create a server-side SSL context from the client TLS config.

        Verification mode is selected by ``client_cert_mode``:

        - ``off``     → ``CERT_NONE``: no client-cert verification.
        - ``warn``    → ``CERT_OPTIONAL``: handshake succeeds with or without
          a client cert; a presented cert is still validated against the CA
          (a wrong-CA or malformed cert still fails the handshake). The
          app-layer handler logs a warning when no cert is presented.
        - ``enforce`` → same TLS handling as ``warn`` (``CERT_OPTIONAL``),
          but the app-layer handler rejects with HTTP 401 when no cert is
          presented.

        ``CERT_OPTIONAL`` is intentional in both warn and enforce: it keeps
        the handshake succeeding for old IEEE 2030.5 servers that don't yet
        present a device cert, while still failing fast on a presented but
        wrong-CA cert. The "no cert at all" case is handled at the app layer
        so we can return a structured response instead of an opaque TLS error.
        """
        if self._tls is None:
            return None

        ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        # Pin to TLS 1.2 only, matching the outbound client and IEEE 2030.5
        # §6.4. Without the upper bound, a TLS 1.3 handshake would silently
        # bypass set_ciphers() below -- set_ciphers() only controls TLS 1.2
        # suites and earlier; TLS 1.3 negotiates its own separate ciphersuite
        # list (TLS_AES_*_GCM_SHA*). That would defeat the IEEE 2030.5
        # baseline lockdown and contradict the spec's TLS-version requirement.
        ctx.minimum_version = ssl.TLSVersion.TLSv1_2
        ctx.maximum_version = ssl.TLSVersion.TLSv1_2
        # Pin the cipher list to the IEEE 2030.5 baseline (plus any operator
        # opt-ins via `additional_ciphers`). Without an explicit set_ciphers
        # call, OpenSSL would fall back to its system default list -- which
        # accepts suites the spec doesn't sanction. Sharing the same builder
        # as `client/tls.py` keeps inbound and outbound policy aligned so a
        # single config knob controls both directions of the connection.
        if self._tls.additional_ciphers:
            logger.warning(
                "Notification server cipher policy relaxed beyond IEEE 2030.5 "
                "baseline; additional ciphers: %s",
                ", ".join(self._tls.additional_ciphers),
            )
        ctx.set_ciphers(build_cipher_string(self._tls))
        ctx.load_cert_chain(str(self._tls.client_cert), str(self._tls.client_key))
        ctx.load_verify_locations(str(self._tls.ca_cert))
        if self._client_cert_mode == "off":
            ctx.verify_mode = ssl.CERT_NONE
        else:  # warn or enforce
            ctx.verify_mode = ssl.CERT_OPTIONAL
        return ctx

    def _connection_event(
        self, request: web.Request, pair: SocketPair, refused: str | None
    ) -> None:
        """Report one inbound notification request to the connection observer.

        Reported per request: aiohttp accepts the connection before any
        application code runs, so a request is the first point this listener
        can observe. A TLS handshake that fails never reaches it.
        """
        observer = self.observers.connection
        if observer is None:
            return
        local = endpoint(pair.local)
        self._observer_guard.deliver(
            observer,
            ConnectionEvent(
                role=ConnectionRole.LISTENER,
                direction=ConnectionDirection.INBOUND,
                outcome=ConnectionOutcome.ACCEPTED
                if refused is None
                else ConnectionOutcome.REFUSED,
                transport=ConnectionTransport.TLS if request.secure else ConnectionTransport.TCP,
                remote=endpoint(pair.remote),
                local=local,
                reason=refused or "",
                status=401 if refused is not None else None,
                tls_version=pair.tls_version,
                tls_cipher=pair.tls_cipher,
                peer_cert_sha256=pair.peer_cert_sha256,
            ),
        )

    def _anomaly(self, pair: SocketPair, exchange_id: str, code: AnomalyCode, message: str) -> None:
        """Report a notification refused or dropped to the anomaly observer."""
        observer = self.observers.anomaly
        if observer is None:
            return
        self._observer_guard.deliver(
            observer,
            ProtocolAnomaly.of(
                code,
                bounded(message),
                exchange_id=exchange_id,
                method="POST",
                path="/notify",
                peer=endpoint(pair.remote),
            ),
        )

    def _exchange(
        self,
        request: web.Request,
        pair: SocketPair,
        exchange: _Notification,
        response: web.StreamResponse,
    ) -> None:
        """Report one notification request and the response sent back to it."""
        observers = self.observers
        if observers.exchange is None:
            return
        received_at = time.time()
        received_monotonic = time.monotonic()
        response_body = getattr(response, "body", None)
        response_bytes = (
            bytes(response_body) if isinstance(response_body, (bytes, bytearray)) else None
        )
        request_headers = tuple(request.headers.items())
        response_headers = tuple(response.headers.items())
        request_valid, request_error = validate(exchange.body, request_headers, observers)
        capture = observers.capture_bodies
        self._observer_guard.deliver(
            observers.exchange,
            ExchangeRecord(
                exchange_id=exchange.exchange_id,
                direction=ExchangeDirection.NOTIFICATION,
                method=request.method,
                url=str(request.url),
                path=request.path_qs,
                request_headers=redact_headers(request_headers, observers.redacted_headers),
                request_body=exchange.body if capture else None,
                status=response.status,
                response_headers=redact_headers(response_headers, observers.redacted_headers),
                response_body=response_bytes if capture else None,
                sent_at=exchange.started_at,
                received_at=received_at,
                sent_monotonic=exchange.started_monotonic,
                received_monotonic=received_monotonic,
                duration=received_monotonic - exchange.started_monotonic,
                local=endpoint(pair.local),
                remote=endpoint(pair.remote),
                tls_version=pair.tls_version,
                tls_cipher=pair.tls_cipher,
                server_cert_sha256=pair.peer_cert_sha256,
                resource_type=root_element(exchange.body),
                request_valid=request_valid,
                request_validation_error=request_error,
            ),
        )

    async def _handle_notify(self, request: web.Request) -> web.StreamResponse:
        """Handle POST /notify, and report it to the observers."""
        exchange = _Notification()
        if not self.observers.any:
            return await self._handle_notification(request, exchange)
        pair = socket_pair_of(request.transport) if request.transport else SocketPair(None, None)
        response = await self._handle_notification(request, exchange)
        try:
            self._connection_event(request, pair, exchange.refused)
            if exchange.anomaly is not None:
                self._anomaly(pair, exchange.exchange_id, *exchange.anomaly)
            self._exchange(request, pair, exchange, response)
        except Exception:  # pylint: disable=broad-exception-caught
            logger.debug("Could not report a notification request", exc_info=True)
        return response

    async def _handle_notification(
        self, request: web.Request, exchange: _Notification
    ) -> web.Response:
        """Handle POST /notify from the IEEE 2030.5 server, noting what happened in ``exchange``."""
        # Client-cert mode check (warn/enforce). With CERT_OPTIONAL the
        # TLS layer accepts handshakes without a client cert, so the
        # "no cert presented" decision lives here at the app layer.
        from py20305.diagnostics import report

        if self._client_cert_mode in ("warn", "enforce"):
            transport = request.transport
            peercert = transport.get_extra_info("peercert") if transport else None
            if not peercert:
                remote = request.remote or "<unknown>"
                if self._client_cert_mode == "enforce":
                    report(
                        "warnings",
                        (
                            f"Rejecting notification from {remote}: no client certificate. "
                            "Configure outbound mTLS on the IEEE 2030.5 server "
                            "(per IEEE 2030.5-2023 §8.9.3.2 + Table 12)."
                        ),
                        source="notification",
                        dedup_key=f"notif_mtls_reject:{remote}",
                        details={"remote": remote},
                    )
                    exchange.refused = "No client certificate presented"
                    exchange.anomaly = (
                        AnomalyCode.REJECTED_NOTIFICATION,
                        f"Notification from {remote} refused: no client certificate",
                    )
                    return web.Response(status=401, text="client certificate required")
                # warn mode: log and accept
                report(
                    "warnings",
                    (
                        f"Notification from {remote} arrived without a client certificate. "
                        "Configure outbound mTLS on the IEEE 2030.5 server "
                        "(per IEEE 2030.5-2023 §8.9.3.2 + Table 12), or set "
                        "subscription.notification_client_cert_mode='off' to suppress."
                    ),
                    source="notification",
                    dedup_key=f"notif_mtls_warn:{remote}",
                    details={"remote": remote},
                )

        try:
            body = await request.read()
        except Exception as exc:  # pylint: disable=broad-exception-caught
            logger.warning("Failed to read notification request body")
            exchange.anomaly = (
                AnomalyCode.UNREADABLE_NOTIFICATION,
                f"Notification body could not be read: {exc}",
            )
            return web.Response(status=400, text="Bad Request")
        exchange.body = body

        remote = request.remote or "<unknown>"
        if self._traffic_recorder is not None:
            # Recorded before parse/validation, so the accept/reject outcome
            # isn't known yet -- leave status unset rather than implying 201.
            self._traffic_recorder.record_notification(
                path=request.path_qs, body=body, source_ip=remote, status=None
            )
        try:
            notification = parse_notification(body)
        except Exception as exc:
            report(
                "warnings",
                f"Failed to parse notification XML from {remote}: {exc}",
                source="notification",
                dedup_key=f"notif_parse:{remote}",
                details={"remote": remote, "error": str(exc)},
                exc_info=True,
            )
            exchange.anomaly = (
                AnomalyCode.REJECTED_NOTIFICATION,
                f"Notification from {remote} is not a valid Notification: {exc}",
            )
            return web.Response(status=400, text="Invalid notification XML")

        if not validate_notification(notification, body):
            report(
                "warnings",
                f"Notification xsi:type validation failed from {remote}",
                source="notification",
                dedup_key=f"notif_parse:{remote}",
                details={"remote": remote, "reason": "xsi:type mismatch"},
            )
            exchange.anomaly = (
                AnomalyCode.REJECTED_NOTIFICATION,
                f"Notification from {remote} failed the xsi:type check",
            )
            return web.Response(status=400, text="xsi:type mismatch")

        if self._suspended:
            # A real outage would stop these arriving at all. The listener stays
            # up (the operator is driving the test through this device), so the
            # notification is accepted and dropped rather than refused: answering
            # with an error would tell the head-end its delivery failed, and some
            # servers respond by dropping the subscription -- a side effect on
            # the customer's server that a local simulation has no business
            # causing. Recovery re-polls schedules, so nothing is lost by it.
            logger.info(
                "Notification for %s dropped: comms-loss simulation active",
                notification.subscribed_resource or "<unknown>",
            )
            exchange.anomaly = (
                AnomalyCode.DROPPED_NOTIFICATION,
                f"Notification for {notification.subscribed_resource or '<unknown>'} dropped "
                "while a loss-of-communications simulation runs",
            )
            return web.Response(status=201, text="Created")

        if self._forward is not None:
            return await self._forward_body(body, notification, remote, exchange)

        if self._on_notification is not None:
            task = asyncio.create_task(self._safe_notify(notification))
            self._background_tasks.add(task)
            task.add_done_callback(self._background_tasks.discard)

        return web.Response(status=201, text="Created")

    async def _forward_body(
        self, body: bytes, notification: Notification, remote: str, exchange: _Notification
    ) -> web.Response:
        """Hand one notification to the host and answer by the outcome.

        Answered after the host's coroutine returns, so a 201 tells the server
        the host has the notification. A failure answers 503 (RFC 9110
        §15.6.4, a temporary condition) rather than 201, so the server does not
        take a notification nobody holds as delivered.
        """
        from py20305.diagnostics import report

        resource = notification.subscribed_resource or "<unknown>"
        try:
            await self._forward(body)  # type: ignore[misc]
        except Exception as exc:  # pylint: disable=broad-exception-caught
            report(
                "warnings",
                f"Notification for {resource} from {remote} was not handed on: {exc}",
                source="notification",
                dedup_key=f"notif_forward:{resource}:{type(exc).__name__}",
                details={"subscribed_resource": resource, "error": str(exc)},
                exc_info=True,
            )
            exchange.anomaly = (
                AnomalyCode.DROPPED_NOTIFICATION,
                f"Notification for {resource} refused: the host did not accept it ({exc})",
            )
            return web.Response(status=503, text="Notification not accepted")
        return web.Response(status=201, text="Created")

    async def _safe_notify(self, notification: Notification) -> None:
        """Run the notification callback, logging any errors."""
        from py20305.client.errors import Sep2Error
        from py20305.diagnostics import report

        resource = notification.subscribed_resource or "<unknown>"
        try:
            await self._on_notification(notification)  # type: ignore[misc]
        except Sep2Error as exc:
            # B2: protocol-layer error from a downstream server call the
            # callback made (e.g. targeted re-poll, structural rediscovery).
            # Dedup per (resource, exception kind) so a flapping endpoint
            # collapses to a single entry while different paths stay visible.
            report(
                "warnings",
                f"Notification handler {resource} → {type(exc).__name__}: {exc}",
                source="notification",
                dedup_key=f"notif_handler:{resource}:{type(exc).__name__}",
                details={
                    "subscribed_resource": resource,
                    "exc_kind": type(exc).__name__,
                    "error": str(exc),
                },
            )
        except Exception as exc:
            # B11: caller-side bug in the registered callback. Dedup per
            # (resource, exc kind) so a recurring code-path issue doesn't
            # spam the operator -- the count tells the story.
            report(
                "warnings",
                f"Notification callback for {resource} raised {type(exc).__name__}: {exc}",
                source="notification",
                dedup_key=f"notif_callback:{resource}:{type(exc).__name__}",
                details={
                    "subscribed_resource": resource,
                    "exc_kind": type(exc).__name__,
                    "error": str(exc),
                },
                exc_info=True,
            )
on_notification property writable
on_notification: NotificationCallback | None

The coroutine invoked with each parsed, accepted notification.

forward property writable
forward: NotificationForwarder | None

The coroutine each accepted notification's raw body is handed to, if set.

When set, the listener does not process notifications. It parses and checks each one as before, then awaits forward(body) and answers 201 only after it returns. If it raises, the listener answers 503 so the server knows the delivery failed. Use it to put each notification on a queue that the process acting for the affected EndDevice reads, and hand it to :meth:CsipClient.process_notification there.

None, the default, processes each notification here, after answering 201, as before.

suspended property
suspended: bool

Whether accepted notifications are being dropped instead of handled.

suspend async
suspend(*, drain_timeout: float = 5.0) -> bool

Stop acting on notifications, and wait for any already running.

Returns whether the in-flight handlers finished in time. The wait is the point: this server answers 201 and hands the notification to a background task, so one accepted moments earlier is still running and can apply a control after the caller believes the link is down -- a fresh setpoint landing on a DER the operator thinks is isolated.

A False return means handlers were still running when the timeout elapsed. New notifications are dropped either way, from the moment this is called.

Source code in src/py20305/subscription/notification_server.py
async def suspend(self, *, drain_timeout: float = 5.0) -> bool:
    """Stop acting on notifications, and wait for any already running.

    Returns whether the in-flight handlers finished in time. The wait is the
    point: this server answers 201 and hands the notification to a
    background task, so one accepted moments earlier is still running and
    can apply a control *after* the caller believes the link is down -- a
    fresh setpoint landing on a DER the operator thinks is isolated.

    A False return means handlers were still running when the timeout
    elapsed. New notifications are dropped either way, from the moment this
    is called.
    """
    self._suspended = True
    if not self._background_tasks:
        return True
    pending = tuple(self._background_tasks)
    _, still_running = await asyncio.wait(pending, timeout=drain_timeout)
    return not still_running
resume
resume() -> None

Act on notifications again.

Source code in src/py20305/subscription/notification_server.py
def resume(self) -> None:
    """Act on notifications again."""
    self._suspended = False
build_notification_uri
build_notification_uri(external_host: str) -> str

Build the fully-qualified notification URI for subscription requests.

Source code in src/py20305/subscription/notification_server.py
def build_notification_uri(self, external_host: str) -> str:
    """Build the fully-qualified notification URI for subscription requests."""
    return f"https://{external_host}:{self._port}/notify"
start async
start() -> None

Start the notification server.

Source code in src/py20305/subscription/notification_server.py
async def start(self) -> None:
    """Start the notification server."""
    if self._site is not None:
        return

    self._app = web.Application()
    self._app.router.add_post("/notify", self._handle_notify)

    self._runner = web.AppRunner(self._app, shutdown_timeout=self._shutdown_timeout)
    await self._runner.setup()

    ssl_ctx = self._create_server_ssl_context()
    # SO_REUSEADDR lets the listener rebind to a port still in TIME_WAIT
    # from a previous instance — matters most in the cert e2e suite where
    # multiple clients are torn down and recreated in a single pytest
    # session. Production restarts after a clean shutdown don't need it
    # but it's harmless: SO_REUSEADDR doesn't allow stealing an active
    # listener's port, only re-binding to a TIME_WAIT port.
    self._site = web.TCPSite(
        self._runner,
        self._host,
        self._port,
        ssl_context=ssl_ctx,
        reuse_address=True,
    )
    await self._site.start()

    if ssl_ctx is None:
        cert_status = "disabled (plain HTTP)"
    elif self._client_cert_mode == "enforce":
        cert_status = "enforce (mTLS required; no-cert peers rejected with 401)"
    elif self._client_cert_mode == "warn":
        cert_status = "warn (mTLS optional; no-cert peers logged but accepted)"
    else:  # off
        cert_status = "off (TLS without client-cert verification)"

    logger.info(
        "NotificationServer started on %s:%d  client_cert_mode=%s",
        self._host,
        self._port,
        cert_status,
    )
stop async
stop() -> None

Gracefully stop the notification server.

Source code in src/py20305/subscription/notification_server.py
async def stop(self) -> None:
    """Gracefully stop the notification server."""
    # Cancel background notification tasks
    for task in self._background_tasks:
        task.cancel()
    if self._background_tasks:
        await asyncio.gather(*self._background_tasks, return_exceptions=True)
        self._background_tasks.clear()

    if self._site is not None:
        await self._site.stop()
        self._site = None
    if self._runner is not None:
        await self._runner.cleanup()
        self._runner = None
    self._app = None
    logger.info("NotificationServer stopped")

parse_notification

parse_notification(body: bytes) -> Notification

Parse XML bytes into a Notification model.

Source code in src/py20305/subscription/notification_server.py
def parse_notification(body: bytes) -> Notification:
    """Parse XML bytes into a Notification model."""
    return from_xml(body, Notification)

validate_notification

validate_notification(notification: Notification, raw_xml: bytes) -> bool

Validate xsi:type on the Resource element matches expectations.

For list resources, xsi:type must end with "List". For non-list resources, xsi:type must match the element name. Returns True if valid, no Resource present, or no xsi:type.

Source code in src/py20305/subscription/notification_server.py
def validate_notification(notification: Notification, raw_xml: bytes) -> bool:
    """Validate xsi:type on the Resource element matches expectations.

    For list resources, xsi:type must end with "List".
    For non-list resources, xsi:type must match the element name.
    Returns True if valid, no Resource present, or no xsi:type.
    """
    if notification.resource is None:
        return True

    try:
        tree = etree.fromstring(raw_xml)
    except etree.XMLSyntaxError:
        return False

    resource_elem = tree.find(f"{{{NS_SEP}}}Resource")
    if resource_elem is None:
        return True

    xsi_type = resource_elem.get(f"{{{NS_XSI}}}type")
    if xsi_type is None:
        return True

    # Strip namespace prefix if present (e.g., "sep:FunctionSetAssignmentsList")
    if ":" in xsi_type:
        xsi_type = xsi_type.split(":", 1)[1]

    # Validate consistency: list types must end with "List"
    subscribed = notification.subscribed_resource
    if subscribed and subscribed.endswith("/"):
        # List resources typically have trailing paths
        pass

    # The xsi:type should be a valid IEEE 2030.5 type name
    # For list resources, the type ends with "List"
    # For non-list resources, it doesn't
    # We validate structural consistency but don't reject unknown types
    logger.debug("Notification Resource xsi:type=%s for %s", xsi_type, subscribed)
    return True