Commit 2fbef04b6f for frr

commit 2fbef04b6f1387985fed33e88788f4fcad5f6955
Author: Lincoln Thurlow <lincoln@isi.edu>
Date:   Tue Dec 1 09:58:59 2026 -0800

    tests: let the mock PCE accept reconnects

    The pathd PCEP steering topotest fails for good when pathd's PCEP
    session drops, as it did on the churn burst before #24505 fixed
    messages split across TCP reads.

    The mock PCE accepts one connection and stops serving when it ends.

    This commit makes the mock PCE accept reconnects, with a fresh
    session state for each, and act on its command file only after the
    state sync, since pathd discards earlier PCInitiates. The churn test
    also prints the PCEP, policy and mock PCE state when its policies do
    not come up.

    Signed-off-by: Lincoln Thurlow <lincoln@isi.edu>

diff --git a/tests/topotests/pathd_pcep_steering_topo1/mock_pce.py b/tests/topotests/pathd_pcep_steering_topo1/mock_pce.py
index 992ef373a9..e02a861898 100644
--- a/tests/topotests/pathd_pcep_steering_topo1/mock_pce.py
+++ b/tests/topotests/pathd_pcep_steering_topo1/mock_pce.py
@@ -424,6 +424,19 @@ class MockPce:
     def send(self, data):
         self.conn.sendall(data)

+    def reset_session_state(self):
+        # A reconnected PCC starts a clean PCEP session: pathd dropped
+        # every PCE-initiated policy when the old session went down, so
+        # re-sync and re-initiate everything, replaying the command file
+        # from the top.
+        self.sync_done = False
+        self.initiated = False
+        self.next_srp_id = 1
+        self.srp_to_name = {}
+        self.plsp_by_name = {}
+        self.command_pos = 0
+        self.deferred_removes = []
+
     def run(self):
         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
@@ -431,9 +444,26 @@ class MockPce:
         self.sock.listen(1)
         self.log("LISTENING %s:%u" % (self.args.address, self.args.port))

-        self.conn, peer = self.sock.accept()
-        self.log("CONNECT %s:%u" % peer)
-
+        # Accept loop: a real PCE survives a session going down and lets
+        # the PCC reconnect.  Without this a single transient drop ends
+        # the mock for good and strands pathd retrying a dead socket.
+        while True:
+            self.conn, peer = self.sock.accept()
+            self.log("CONNECT %s:%u" % peer)
+            self.reset_session_state()
+            try:
+                self.serve_session()
+            except OSError as e:
+                # Broken pipe / connection reset: the PCC went away.  Log
+                # it and wait for the reconnect instead of crashing.
+                self.log("SESSION-ERROR err=%r" % e)
+            try:
+                self.conn.close()
+            except OSError:
+                pass
+            self.log("SESSION-END awaiting-reconnect")
+
+    def serve_session(self):
         # Both Open-first and Keepalive-first orders are accepted by
         # pceplib; send both back to back.
         self.send(self.build_open())
@@ -468,9 +498,14 @@ class MockPce:
                     self.handle_message(buffer[1], buffer[4:mlen])
                     buffer = buffer[mlen:]

-            self.poll_commands()
+            # pathd discards PCInitiates received before its state sync
+            # completes, and a reconnect replays the command file from
+            # the top, so commands wait for the sync like the base
+            # policies do.
+            if not self.sync_done:
+                continue

-            if self.sync_done and not self.initiated:
+            if not self.initiated:
                 self.initiated = True
                 for policy in self.policies:
                     srp_id = self.next_srp_id
@@ -487,6 +522,8 @@ class MockPce:
                         )
                     )

+            self.poll_commands()
+

 def main():
     parser = argparse.ArgumentParser(description=__doc__)
diff --git a/tests/topotests/pathd_pcep_steering_topo1/test_pathd_pcep_steering_topo1.py b/tests/topotests/pathd_pcep_steering_topo1/test_pathd_pcep_steering_topo1.py
index 0fc468bb69..65893e85c8 100644
--- a/tests/topotests/pathd_pcep_steering_topo1/test_pathd_pcep_steering_topo1.py
+++ b/tests/topotests/pathd_pcep_steering_topo1/test_pathd_pcep_steering_topo1.py
@@ -178,6 +178,17 @@ def print_pce_log():
         logger.info("mock PCE log %s not found", pce_log)


+def mock_pce_log_text():
+    "The mock PCE's log so far (empty when not yet written)"
+
+    tgen = get_topogen()
+    try:
+        with open(os.path.join(tgen.logdir, "rt1", "mock_pce.log")) as log:
+            return log.read()
+    except IOError:
+        return ""
+
+
 def check_label_installed():
     "Check that RT2's prefix-SID labels are in RT1's LFIB"

@@ -328,6 +339,49 @@ def churn_add(i, v6=False):
     pce_command("add {},{},{},{}".format(endpoint, label, churn_name(i, v6), color))


+def _diag_section(title, lines, empty="(no output)"):
+    """One labelled block for failure_diagnostics(): a title line followed
+    by its output indented four spaces, so the sections stay visually
+    distinct in the CI console."""
+
+    body = "\n".join("    " + line for line in lines) if lines else "    " + empty
+    return "{}\n{}".format(title, body)
+
+
+def failure_diagnostics():
+    """A readable dump of the head-end's PCEP and policy state plus the
+    mock PCE log, appended to the assertion message so that a CI failure
+    explains itself without needing the archived logs."""
+
+    tgen = get_topogen()
+    rt1 = tgen.gears["rt1"]
+
+    sections = [
+        _diag_section("routers", [tgen.routers_have_failure() or "all running"])
+    ]
+
+    for cmd in [
+        "show sr-te pcep session",
+        "show sr-te policy",
+        "show zebra client summary",
+    ]:
+        lines = rt1.vtysh_cmd(cmd).splitlines()
+        if len(lines) > 30:
+            lines = lines[:30] + ["... ({} more lines)".format(len(lines) - 30)]
+        sections.append(_diag_section("vtysh -c '{}'".format(cmd), lines))
+
+    sections.append(
+        _diag_section(
+            "mock PCE log (last 40 lines)",
+            mock_pce_log_text().splitlines()[-40:],
+            empty="(empty)",
+        )
+    )
+
+    rule = "=" * 64
+    return "\n\n{0}\nDIAGNOSTICS\n{0}\n\n{1}\n{0}".format(rule, "\n\n".join(sections))
+
+
 def check_policy_count(expected):
     "Check the number of Active SR-TE policies on RT1"

@@ -449,6 +503,7 @@ def test_policy_churn_scale():
     _, result = topotest.run_and_expect(check, None, count=180, wait=1)
     if result is not None:
         print_pce_log()
+        result += failure_diagnostics()
     assert result is None, "churn policies never came up: {}".format(result)

     # Each endpoint now has 1 + CHURN_COUNT policies; its steering route