Skip to content

Concurrency: NodeConnector.ForwardIfCurrent invokes subscriber delegates while holding _clientLifecycleLock (lifecycle stall/reentrancy hazard) #1020

Closed

Description

@anagnorisis2peripeteia

Split out of #1010 (residual hazard 2 of 3), per the maintainer status update there. Verified present on current main @ ee4817d. Filed so the accept/fix/defer decision is explicit and tracked rather than buried in the umbrella (per the review note there).

The hazard

src/OpenClaw.Connection/NodeConnector.cs — both ForwardIfCurrent overloads (L224, L240) invoke subscriber delegates inside lock (_clientLifecycleLock):

// Validation and dispatch stay atomic so a retired client cannot publish after its
// replacement. Subscribers must remain synchronous and must not block on connector
// lifecycle work while this lock is held.
private void ForwardIfCurrent<T>(object? sender, long generation, T args, EventHandler<T>? handler)
{
    lock (_clientLifecycleLock)
    {
        if (Interlocked.Read(ref _clientGeneration) == generation &&
            ReferenceEquals(sender, _client))
        {
            handler?.Invoke(this, args);
        }
    }
}

Every lifecycle operation takes the same _clientLifecycleLock (L110, L136, L181, L187, L214, L258, L272, L304), so event dispatch and lifecycle transitions are mutually exclusive:

  • A slow subscriber (StatusChanged, PairingStatusChanged, TransportConnected, ConnectionFailure, DeviceTokenReceived) stalls every Connect/Dispose/DisconnectIfCurrent for its duration.
  • A subscriber that blocks on another thread which is itself doing lifecycle work deadlocks (handler waits on thread T; T waits on _clientLifecycleLock).
  • Same-thread re-entry (a handler calling back into lifecycle methods) is silently permitted by Monitor reentrancy and mutates generation state mid-dispatch.

Handlers are fast today, and the constraint is now documented at the call site (L221–223) — but it's enforced by comment, not by structure.

Why this isn't a mechanical snapshot-and-raise

The lock currently buys a real ordering guarantee: validation + dispatch are atomic, so a retired client can never publish after its replacement. Naively moving handler?.Invoke outside the lock reopens that publish-after-retire window. A fix needs to preserve the guarantee — e.g. a per-generation dispatch queue drained before retirement completes, or validate-under-lock + invoke-outside with a completion barrier on retire. That design tension is why this stayed a tracked hazard in #1010 rather than a quick fix.

Deterministic reproduction (base-red / head-green)

No timing dependence needed — gate the interleaving explicitly:

  1. Stall repro: subscribe a handler that blocks on a ManualResetEventSlim; deliver an event through the current client; from another thread call DisconnectIfCurrent (or Dispose).
    • Base (red): the lifecycle call cannot complete until the handler's gate opens.
    • Fixed (green): the lifecycle call completes promptly while the handler is still running.
  2. Ordering guarantee (must stay green in both): after Dispose/generation retirement returns, no subscriber invocation from the retired client is observed — retirement acts as a barrier for in-flight dispatch.

Acceptance criteria

  • Lifecycle operations no longer block on subscriber execution (repro 1 flips red → green).
  • The publish-after-retire guarantee holds under the new dispatch scheme (repro 2 green before and after), with the mechanism documented at the call site.
  • Alternatively, if the maintainers' verdict is that the documented synchronous-subscriber contract is the intended final state, close this as accepted-by-design — the point of the split is that the decision is explicit.

Activity

  1. added
    P2
    impact:other
    issue-rating: 🐚 platinum hermit
    clawsweeper:needs-live-repro
    clawsweeper:no-new-fix-pr
    clawsweeper:needs-maintainer-review
    clawsweeper:needs-product-decision
    on Jul 18, 2026
  2. clawsweeper commented on Jul 18, 2026

    @clawsweeper

    Codex review: keeping this open for maintainer follow-up; there is still a little grit to resolve. Reviewed July 18, 2026, 5:35 PM ET / 21:35 UTC.

    Summary
    Keep this issue open. It was filed on July 18, 2026 against the stated current-main SHA with a concrete lock-held callback path and a deterministic reproduction design; resolving it requires an explicit choice between preserving the synchronous callback contract or introducing a retirement-safe out-of-lock dispatch protocol.

    Reproducibility: yes. at source level: block a current-client event handler on a gate, invoke DisconnectIfCurrent or disposal from another thread, and observe whether the lifecycle call waits for that handler. The supplied report also defines the required post-retirement no-publication assertion, but this review did not execute the repro.

    Root-cause cluster
    Relationship: canonical
    Canonical: #1020
    Summary: This is the focused canonical tracker for one residual NodeConnector dispatch hazard split from a broader, now-closed concurrency report.

    Members:

    Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

    Next step
    A maintainer must choose the intended event/lifecycle contract before a repair worker can safely select a dispatch mechanism.

    Maintainer decision needed

    • Question: Should NodeConnector retain its documented synchronous-under-lock subscriber contract, or should maintainers sponsor a retirement-safe out-of-lock dispatch design that prevents lifecycle stalls?
    • Rationale: Both choices intentionally define the connection event contract: a naive lock removal breaks the stated retired-client ordering guarantee, while retaining the lock preserves a known blocking and reentrancy hazard.
    • Likely owner: anagnorisis2peripeteia — The supplied context identifies this contributor as the only person who has traced and documented both sides of the dispatch-contract tradeoff; confidence is limited because current-main ownership history was unavailable in the review packet.
    • Options:
      • Sponsor retirement-safe dispatch (recommended): Introduce a bounded per-generation dispatch/completion barrier with deterministic tests proving lifecycle progress and no post-retirement publication.
      • Accept synchronous callback contract: Keep validation and subscriber invocation atomic under the lifecycle lock, explicitly document the nonblocking/non-reentrant subscriber requirement, and close this as accepted by design.
    Review details

    Best possible solution:

    Adopt a small, tested dispatch/retirement protocol that lets lifecycle transitions complete independently of subscriber execution while making retirement a barrier for all events from the retired generation; document that invariant at the dispatch seam.

    Do we have a high-confidence way to reproduce the issue?

    Yes, at source level: block a current-client event handler on a gate, invoke DisconnectIfCurrent or disposal from another thread, and observe whether the lifecycle call waits for that handler. The supplied report also defines the required post-retirement no-publication assertion, but this review did not execute the repro.

    Is this the best way to solve the issue?

    Unclear until maintainers choose the event-contract direction. A naive snapshot-and-raise change is not sufficient because it can violate the existing retirement barrier; a completion-aware dispatch design is the narrow maintainable fix if the synchronous contract is not accepted.

    AGENTS.md: found and applied where relevant.

    Remaining risk / open question:

    • Moving subscriber invocation outside _clientLifecycleLock without a completion/retirement barrier can let an already-retired client publish after replacement.
    • Keeping the current design intentionally retains lifecycle stalls and potential deadlock/reentrancy exposure if a future subscriber blocks or calls lifecycle work.

    Codex review notes: model internal, reasoning high; reviewed against ee4817d2c2e7.

    Label changes

    Label changes:

    • add P2: The reported core connection lifecycle stall has bounded current impact because subscribers are presently fast, but it can block connect, disconnect, and disposal when the contract is violated.
    • add impact:other: This is a concrete connection-lifecycle responsiveness and reentrancy hazard that does not fit the more specific owned impact classes.
    • add issue-rating: 🐚 platinum hermit: Current issue advisory state selects this label.
    • add clawsweeper:needs-live-repro: Current issue advisory state selects this label.
    • add clawsweeper:no-new-fix-pr: Current issue advisory state selects this label.
    • add clawsweeper:needs-maintainer-review: Current issue advisory state selects this label.
    • add clawsweeper:needs-product-decision: Current issue advisory state selects this label.

    Label justifications:

    • P2: The reported core connection lifecycle stall has bounded current impact because subscribers are presently fast, but it can block connect, disconnect, and disposal when the contract is violated.
    • impact:other: This is a concrete connection-lifecycle responsiveness and reentrancy hazard that does not fit the more specific owned impact classes.
    Evidence reviewed

    What I checked:

    • Current-main source path reported: The report identifies both ForwardIfCurrent overloads in NodeConnector.cs as validating generation/current-client identity and invoking the handler inside _clientLifecycleLock; the item states this was verified at current main ee4817d2c2e7b509474d0979aa746a762448cd0c. (src/OpenClaw.Connection/NodeConnector.cs:224, ee4817d2c2e7)
    • Concrete lifecycle invariant: The report distinguishes the real ordering guarantee from a simple snapshot-and-raise change: after client retirement returns, a retired client must not deliver an event. That makes the proposed fix a dispatch/retirement design choice rather than a mechanical lock removal. (src/OpenClaw.Connection/NodeConnector.cs:224, ee4817d2c2e7)
    • Related umbrella disposition: The closed umbrella report explicitly retained this lock-held event-dispatch behavior as a lower-severity hazard and split it into this focused item, while its independently fixed cancellation and session-snapshot work moved to separate pull requests.
    • Repository policy applied: The fully supplied AGENTS.md requires focused regression coverage and the required build/shared/tray validation for any eventual connection-path change; it also directs node/MCP-related work toward real behavior proof where applicable. (AGENTS.md:1, ee4817d2c2e7)

    Likely related people:

    • anagnorisis2peripeteia: Authored the focused report after tracing the lifecycle lock, identifying the preserved retirement invariant, and providing deterministic red/green acceptance criteria; no current-main implementation owner could be established from the supplied history packet. (role: reporter and concurrency-audit contributor; confidence: medium; files: src/OpenClaw.Connection/NodeConnector.cs)
    How this review workflow works
    • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
    • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
    • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
    • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
    • Maintainers can also comment @clawsweeper review to request a fresh review only.
    • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
    • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
    • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
  3. steipete commented on Jul 19, 2026

    @steipete
    Contributor

    Resolved on main by #1022 at 15ed439.

    That merge selected the report's explicit synchronous-callback option: validation and dispatch remain atomic under the lifecycle lock, with the fast/nonblocking subscriber contract documented. Regression coverage proves retired-client events are suppressed after reconnect and disconnect, while current-client handlers can read connector properties consistently. The full Windows build, 14 focused connection tests, 2,901 shared tests, and 1,823 tray tests passed. Closing this design report as decided and documented on main.

  4. locked as resolved and limited conversation to collaborators on Jul 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2clawsweeper:needs-live-reproclawsweeper:needs-maintainer-reviewclawsweeper:needs-product-decisionclawsweeper:no-new-fix-primpact:otherissue-rating: 🐚 platinum hermit

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions