Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
9da923c
fix(tcp): stop client retries after terminal close
F18-Ray Nov 26, 2026
f61f2d7
fix(tcp): release a client port reservation only once
F18-Ray Nov 26, 2026
6696e37
fix(tcp): synchronize server startup and client admission with stop()
F18-Ray Nov 27, 2026
8f94da1
docs(plan): separate A1 review from A2 implementation
F18-Ray Nov 30, 2026
6c93e1a
docs(tcp): define the boundary of terminal client retries
F18-Ray Nov 30, 2026
2771f6b
docs(ports): clarify ownership of a released client range
F18-Ray Nov 30, 2026
c992781
test(tcp): pin server shutdown on both sides of listener publication
F18-Ray Nov 30, 2026
869cac9
docs(tcp): describe server startup and connection handoff on stop
F18-Ray Nov 30, 2026
7b2aead
test(tcp): cover listener handoff and pending readers over real TCP
F18-Ray Nov 30, 2026
58bfa17
docs(tcp): record A1 in the control-session change notes
F18-Ray Nov 30, 2026
c7e8246
test(tcp): observe late publication and reader registration directly
F18-Ray Nov 30, 2026
0e1c57a
docs(tcp): distinguish an admitted retry from a refused attempt
F18-Ray Nov 30, 2026
ae1e26c
docs(ports): bound ID reuse to the single remembered reservation
F18-Ray Nov 30, 2026
7d0a625
docs(tcp): link startup outcomes and record module interactions
F18-Ray Nov 30, 2026
4760c09
fix(tcp): synchronize client connection attempts with close()
F18-Ray Dec 1, 2026
6f49e43
test(tcp): cover client close during connection setup and retry
F18-Ray Dec 1, 2026
107ff9f
docs(tcp): describe client connection handoff and retry cancellation
F18-Ray Dec 1, 2026
2413666
test(tcp): measure retry backoff at the wait_for boundary
F18-Ray Dec 1, 2026
5916f5e
test(tcp): wait for both ends of the reconnected control session
F18-Ray Dec 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
527 changes: 318 additions & 209 deletions PyFlow/network_api/connect_tcp.py

Large diffs are not rendered by default.

102 changes: 102 additions & 0 deletions docs/plans/tcp-control-session-lifecycle-plan.md

Large diffs are not rendered by default.

30 changes: 30 additions & 0 deletions docs/plans/tcp-session-port-ownership-requirements.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# 需求卡 B:控制会话的手动端口范围、等待与归还

状态:需求方已确认以下边界,授权记录和[计划拆分](tcp-control-session-lifecycle-plan.md)。恢复的草稿仅针对重复释放与编号复用的原复现场景,不代表以下所有权模型已经实现。

## 目标与口径

**控制会话**是一次实际的 Client–Server 控制连接;同一个 Client 重连后是新会话。**端口范围登记**是分配器记录的一段本地端口的使用权,不是一个已绑定的 TCP socket。**领用端口**指从该登记借出、尚未实际归还的具体端口。撤销后续领用、关闭 socket、归还具体端口、释放整段登记是不同的动作。

Client 的手动范围按控制会话持有。先关闭领用入口,最后一个具体端口归还后才释放范围。同一 Client 的旧、新会话可以分别保有不同范围。控制连接保持响应,不因没有范围而反复重连。Server 仍按实例配置/宣布手动分配;其文件接收等待也必须绑定发来请求的控制会话。

## 路径与固定验收标准

| 路径 | 约定及可观察结果 |
|---|---|
| B-N 通知 | 新会话在自己的第一条有效 `/client_alloc_port_range` 前不继承旧策略、不默认走系统临时端口。`NO_LIMIT` 允许 OS 端口;有效数值走手动分配。相同通知不二次登记;冲突通知留下提示,保留第一条,不断线;旧会话迟到的通知无效。不能因等待范围而阻塞控制 reader。 |
| B-R 范围归属 | 范围为空闲时,断线、会话更替、稍后的显式关闭只实际释放一次;A 退出、B 复用 A 的编号,A 再关闭时 B 的原登记逐字节保留。范围内仍有借出端口时不得删登记。旧会话不再领新端口,但新会话可领取另一段不重叠的范围;若无可用范围,保留新控制连接并等待。旧端口最后归还才使旧范围可复用,不能改新会话账目。 |
| B-D 远端目标 | 配置的 `client.host` / `client.port` 始终是控制连接目标;本地手动范围为避让而移动,不得改写 `self.port` 或本应使用该远端身份的进度键。用不同范围基址的 Client 重连到原监听端验证。 |
| B-U 普通 Client 上传 | 尚未取得本会话策略/手动范围:在发 `/file` 前等,不设固定超时、不写新上传进度。已有范围、但具体端口全忙:保留先请求对端 listener、再取本地端口的顺序。两种等待在原会话结束时都唤醒并取消,不借新连接重试或建立数据连接。旧请求/握手按已有会话规则清理。等待范围或端口不占用控制 reader。 |
| B-Q 普通批量/目录 | `/multiple_file`、目录中的实际文件条目逐文件绑定原会话;尚在等并发名额的 B 不必等 A 交回名额才取消。未开始项不得因重连而首次在新连接发送;已开始项保留原进度和恢复契约。取消/异常不泄漏或多还 `file_semaphore` 的名额;同一实例的并发上限不能因会话更替翻倍。纯建目录命令不创建文件端口。 |
| B-F 原生转发/恢复 | 已准入的原生转发在旧会话等待端口时只取消本次等待。保留原 FID、跟踪开启时已有的五字段进度及路由依据;跟踪关闭不伪造新行,未发起项不冒充已准入。保留共享与一对一两种模式、接收方驱动的恢复、真实最终 ACK。普通上传无进度不等于等待线程已取消。 |
| B-I 双向普通收件 | 收到 `/file` 或目录文件条目时,Server、Client 接收方规则相同:在收件工作线程取本地监听端口,会话失效就唤醒退出,不为旧会话补开 listener。普通发送方等端口回复的既有 20 秒协商时限不变;**不增加接收方独立的 20 秒计时器**。控制连接尚存时不承诺感知对端单笔超时,不改 wire 加取消消息。 |
| B-X 扩展 | `create_temporary_server()` / `create_temporary_client()` 创建的通用临时 socket 由扩展决定何时结束,不随控制断线强关。仅对从登记领用的实际端口计账,归还前旧范围不可复用;用户自选或 OS 分配且未从范围领用的端口不伪记为借出。创建失败、正常关闭/EOF 和 `stop_event` 路径同样不得漏还或多还;不要求等待无关扩展回调。E1 的自定义 worker drain 不变。 |

## 范围、安全与非目标

产品变更限 `PyFlow/network_api/connect_tcp.py` 中的端口分配/归还、控制通知与会话更替、普通及原生转发的发送/收件等待、扩展接口内部的借还配对。采用私有的会话取消信号与条件通知;等待必须重查**原会话**及条件,不能只看实例 `running`,不能靠固定 sleep 循环作为主要取消机制。

不新增公共参数、队列/Future 接口、固定等待超时或持久化待发清单;保持端口日志格式、TCP 线路、FID/ACK、进度/加密和扩展返回值。日志记录取消或冲突原因,不输出载荷、凭据或密钥。不改 CI、依赖、coverage,不放宽既有断言。跨独立实例/进程同时申请登记的锁文件互斥、进程被终止后的锁恢复**单列**;本卡的编号复用验收是有明确先后顺序的真实分配,不把它当作跨进程并发安全证明。

风险**高**:旧会话仍持端口时删登记、晚到 `pfree` 作用到新范围、重复通知覆盖登记、等待者错过取消、固定端口回退到 OS 端口后归还了错误的端口。由独立测试对照磁盘登记、真实监听/连接、逐文件进度和最终 ACK;不只统计函数调用数。与实例启动/关闭交接的分工见[需求卡 A](tcp-terminal-start-retry-requirements.md)。
27 changes: 27 additions & 0 deletions docs/plans/tcp-terminal-start-retry-requirements.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# 需求卡 A:TCP 实例终态与启动、连接重试

状态:需求方已确认以下边界,授权记录和[计划拆分](tcp-control-session-lifecycle-plan.md)。**不是 E1/E2 的追加实现**。恢复的草稿仅涉及 A0;后续原子未授权实施。

## 目标与接口

终态关闭约束的是一个实例,不是宿主进程、地址或线程。旧 Server 不再监听、旧 Client 不再建立控制会话;端口可用时,新实例可以在同一 IP、同一端口工作。普通断线不是终态,未关闭的 Client 可以自动重连。

- 保持 `start_TCP_Server()`、`stop()`、`connect()`、`start_TCP_client()`、`close()` 的签名。显式关闭后的旧 Server 再启动直接返回,不 bind/listen;旧 Client 再连接返回 `False`,不新开 socket。保留已丢弃传输进度实例原有的拒绝契约,不让迟到的启动调用破坏 `delete_config()` 的状态判断。
- `stop()` 不必等另一个普通线程里的 `start_TCP_Server()` 返回;`close()` 不必等另一个普通线程里的 `connect()` 返回。返回时,旧候选 socket 已退休,旧启动线程不能再发布 `running=True`、登记控制 socket、启动新 reader 或接纳新客户端。已发给操作系统的 TCP 请求不是可撤回的消息:对端可以观察到该请求,但旧 Client 不因此发布会话,输掉竞争的 `connect()` 返回 `False`。
- 关闭要通知库内等待者(包括重试和模式协商),不承诺调用者线程的固定返回时限。**不改变** E1 的池外关闭无界等待已接纳 worker、池内自停不 self-join、重复关闭仍 flush 的行为。
- 首次连接立即尝试。`is_wait_server=True` 时,单次尝试超时或被拒后,如仍要重试,等 **1 秒**,终态关闭可打断;`False` 不新增内层重试。固定本地控制端口不可用时保留**一次立即回退**到 OS 选择的本地端口(包括既有 Windows 冲突分支),回退前也必须允许终态胜出。外层 auto-reconnect 已有的 1 秒间隔保留,不为同一次失败叠加内外两次延时。

## 必验路径与证据

| 路径 | 必须看见的结果 |
|---|---|
| A-S:Server 启动前已停、bind/listen 成功但尚未发布时停、已发布后停;线程/asyncio 接收模式 | 真实 listener 不再接入;控制住启动线程的收尾时,新实例仍可绑定同一地址;放行旧线程后没有状态复活或遗留客户端。待启动调用退栈后,`delete_config()` 不会因假 `running` 被拒绝。 |
| A-C:首次 connect、显式晚到的 connect、TCP 已连但尚未发布、reader/协商建立期间关闭 | 用真实 peer 区分“一次在途 TCP 到达”与“新会话成功”;关闭胜出后没有晚启动的 reader、无效控制登记或新的连接尝试;不把库内等待延至原超时。关闭不 join 调用方业务线程。 |
| A-R:不可达/超时/被拒,首连和断线重连,等待开/关、1 秒等待中关闭、正常重新连通 | 记录每次实际尝试和等待的起止:首尝试无延时,被拒/超时后重试有间隔,无忙轮询;关闭能唤醒,不再向恢复上线的监听端发新请求;正常重连后仍用原 executor。 |
| A-F:固定非零本地端口冲突,立即回退、回退前关闭;本地端口为 `0`/`None`、其他错误 | 未关闭时只回退一次且可真实连通;关闭胜出不再进行回退,非冲突不走此分支。远端地址/端口不因本地回退改变。 |

## 范围、数据与风险

产品范围限 `PyFlow/network_api/connect_tcp.py` 的实例启动、控制会话发布和关闭交接。风险**高**:仅给 `running` 加锁而不交接候选 socket/reader 仍会漏清理;锁不能跨网络 I/O、等待用户 handler、join 或 executor drain。握手、加密、传输 FID/进度、备用端口的既有错误判定不改,不记录正文或密钥。不新增设置、超时参数或退出进程逻辑。

排除同一活实例同时两次启动,及[需求卡 B](tcp-session-port-ownership-requirements.md)的端口范围、文件等待与扩展资源。不得用重建 executor、延迟断言、改变 CI/依赖/coverage 或跳过平台分支达标。已确认的是需求,不是任意竞争时序已经通过;逐原子证据见[计划](tcp-control-session-lifecycle-plan.md)。
90 changes: 41 additions & 49 deletions docs/source/Network_APIs/TCP_Client_APIs.rst
Original file line number Diff line number Diff line change
Expand Up @@ -178,15 +178,11 @@ a ``ValueError`` if ``is_wait_server`` is ``True`` and
def start_TCP_client(self: Self) -> Any:
...

In the `start_TCP_client` method, we first attempt to
connect to the server by calling the `connect` method.
If the connection fails and ``is_wait_server`` is ``True``,
the client will keep retrying; otherwise it will exit.

*Note: The client socket is created in the `connect` method
(called by `start_TCP_client`), is based on IPv4 and uses the parameters
``self.host`` and ``self.port`` which are provided when
creating the client instance.*
``start_TCP_client()`` calls
:meth:`~PyFlow.network_api.connect_tcp.TCP_Client_Base.connect` to establish
the control connection. Calling ``connect()`` again on an open client replaces
the previous session: the old socket is retired before the new attempt. This
also lets the client try its configured local port again on reconnect.

Secondly, according to the ``self.is_input_command_in_console``
parameter, we will either start the interactive input loop
Expand All @@ -197,35 +193,29 @@ After that, if the interactive mode is enabled, the client
will read user input from the console and send messages
to the server until the connection is closed.

*Note: There is a global variable ``self.running``
which is set to ``True`` after the client successfully
connects to the server. The ``self.running`` variable is
used to control the main receive loop, and it will be
set to ``False`` when the client is shutting down.*

The `connect` method will try to establish a TCP connection
to the server. If a ``client_port`` is specified, the client
will bind to that local port before connecting. The method
will handle timeouts and connection refused errors gracefully,
especially when ``is_wait_server`` is enabled.

When the connection is established, a background thread
`receive_messages` is started to continuously read data
from the server.

So what can the setup function do if the connection fails?

First, if the connection attempt times out, the client
will either wait and retry (if ``is_wait_server`` is ``True``)
or exit with an error.

Secondly, if the server is not running (connection refused),
the behaviour is the same: retry or exit based on
``is_wait_server``.
Connection attempts and retries
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

If any other socket error occurs, the client will print
the error message and return ``False``, and the
`start_TCP_client` method will call ``sys.exit(1)``.
The first attempt is immediate. If the server refuses the connection or the
attempt times out, ``is_wait_server=True`` makes ``connect()`` wait one second
before its next attempt. With ``is_wait_server=False``, ``connect()`` does
not retry that failure. The outer ``start_TCP_client()`` loop can still retry
when ``is_auto_reconnect=True``; it uses one interruptible one-second delay,
not an additional delay on top of an inner retry for the same failure.
With auto-reconnect off, a connection failure on a still-open instance ends
the driver with an error; an explicit terminal close ends it quietly.

A conflict on a fixed, nonzero **local** control port is different: the client
makes one immediate fallback to an OS-assigned source port, still dialing the
same server. A local port of ``None`` or ``0`` is already OS-assigned. A
remote refusal or an unrelated socket error does not trigger this fallback.

A TCP connection at the peer is not yet a successful client startup. The
client first hands its connected socket to a receive thread and sets
``running``. That reader must be active to receive the server's encryption-mode
announcement. A mismatch, EOF before the announcement, or a silent peer that
reaches the negotiation timeout is a terminal refusal. An ordinary disconnect
**after** successful negotiation is not terminal and can trigger auto-reconnect.

For shutting down the client, the `close` method is defined as:

Expand All @@ -234,24 +224,26 @@ For shutting down the client, the `close` method is defined as:
def close(self: Self) -> None:
...

`close()` is terminal for the client instance. It stops listener delivery, shuts down
and closes the current control socket, retires its transfer resources, and releases
its manually allocated range. An external caller waits for accepted custom workers
``close()`` is terminal for the client instance. It stops listener delivery,
retires either a socket still being connected or the published control session,
and releases the active session's transfer resources and manual port range.
An external caller waits for accepted custom workers
and the receive thread, then flushes the record stores. The wait has no timeout: a
handler that does not leave a socket wait or otherwise return can keep `close()`
waiting indefinitely. Python does not forcibly terminate handler threads. A pool
worker that calls `close()` starts non-waiting shutdown instead of joining itself;
it exits after its handler returns.

With ``is_auto_reconnect``, replacing a disconnected control session through
``_release_client_socket()`` is nonterminal and retains the same custom executor.
Terminal ``close()`` shuts that executor down; later ``submit_task()`` calls are
rejected with ``RuntimeError``. If ``close()`` arrives during an in-flight TCP
connect, `connect` checks the stopped flag when the attempt returns and closes that
socket instead of publishing an active session; the TCP attempt itself may already
have occurred. E2 acceptance also observed an auto-reconnect runner already entering
its next `connect()` open one control connection after terminal ``close()``. This
terminal reconnect race remains unaccepted; see the E2 acceptance report.
Closing the client wakes a retry delay or mode-negotiation wait; it need not
join an ordinary application thread that is still inside ``connect()``.
A TCP request already issued to the OS may still reach the peer. If close
wins before the socket is published, the client neither adopts that connection
nor starts a reader for it. If close wins during mode negotiation, it retires
the reader and the interrupted attempt cannot start key exchange or recovery.
No later retry or fixed-port fallback opens another socket on that instance.

Nonterminal reconnect keeps the same custom executor. Only terminal close
shuts it down and rejects later ``submit_task()`` calls.

.. _tcp-client-handling-information-api:

Expand Down
35 changes: 16 additions & 19 deletions docs/source/Network_APIs/TCP_Server_APIs.rst
Original file line number Diff line number Diff line change
Expand Up @@ -150,29 +150,22 @@ If you set ``is_extend_command=True``, the instance will
not auto-start and you should call ``start_TCP_Server()``
manually when ready.*

.. code-block:: python

def start_TCP_Server(self: Self) -> Any:
...
See :meth:`~PyFlow.network_api.connect_tcp.TCP_Server_Base.start_TCP_Server`.

In the `start_TCP_Server` method, we first create a
TCP server socket and bind it to the ``self.host`` and
``self.port`` which are initialized in the ``__init__`` method.

*Note: The server socket which is set up in the `start_TCP_Server`
method is based on IPv4 form.*
On an open instance, ``start_TCP_Server()`` creates an IPv4 listener for
``(self.host, self.port)``. The instance owns that socket before ``bind()``:
``stop()`` can close it even while startup is still in progress.

Secondly, according to the ``self.is_input_command_in_console``
parameter, we will start a thread to listen to the console
input of the server or not.

After that, a main loop to accept clients will be started.

*Note: there is another global variable ``self.running``
which is set to ``True`` after the server socket is
successfully created. The ``self.running`` variable is
used to control the main loop of the TCP server, and it
will be set to ``False`` when the server is shutting down.*
``running`` becomes ``True`` only after ``listen()`` succeeds and startup wins
the handoff with ``stop()``. A stopped instance refuses startup without opening
a socket. Losing the handoff before publication is a refusal, not a normal
exit from the accept loop. Discarded transfer progress still prevents startup.

With ``is_asynic_clients_io=True`` the main loop is the asyncio event loop
instead: it accepts clients in non-blocking mode and schedules one coroutine
Expand Down Expand Up @@ -228,10 +221,14 @@ indefinitely. Python does not forcibly terminate handler threads. If a pool work
calls `stop()` itself, it initiates non-waiting shutdown to avoid joining itself;
that worker exits after the handler returns.

`start_TCP_Server()` checks the stopped flag after binding and listening, so a stop
that has already reached that check closes the listener instead of starting the
accept loop. A narrower concurrent start/stop interleaving is not covered by this
guarantee; see the E2 acceptance report.
Both reader modes track accepted connections while they are being handed to
their readers, before they appear in ``clients``. If shutdown wins this
handoff, the connection is closed without a greeting or a late registration.
If registration wins, ``stop()`` closes the registered connection instead.

``stop()`` does not need the ordinary thread calling ``start_TCP_Server()``
to return before releasing the listener. A **new** instance can serve the
same address once it is available; the old instance cannot be restarted.

*Note: The ``self.clients`` variable is a dictionary that
maps client address tuples to an info dictionary. The
Expand Down
Loading
Loading