Skip to content

fix: Replace busy boolean with inFlightRequests counter in NodeBridge #139

@bbopen

Description

@bbopen

Problem

As identified in PR #136 code review, using a boolean busy flag instead of a counter creates a race condition when BridgeCore multiplexes multiple requests on a single worker.

Current Behavior

interface WorkerProcess {
  busy: boolean;  // ← Boolean flag
  // ...
}

private async sendToWorker<T>(worker: WorkerProcess, payload): Promise<T> {
  worker.busy = true;
  // ...
  try {
    return await worker.core.send<T>(payload);
  } finally {
    worker.busy = false;  // ← Sets to false even if other requests in flight
  }
}

Race Condition Scenario:

  1. Request A: busy = true
  2. Request B (multiplexed on same worker): busy = true (already true, no change)
  3. Request A completes: busy = falseBug: B still in flight
  4. Cleanup sees !busy and may terminate worker with B in flight

Proposed Fix

Replace boolean with counter:

interface WorkerProcess {
  inFlightRequests: number;  // ← Counter
  // ...
}

private async sendToWorker<T>(worker: WorkerProcess, payload): Promise<T> {
  worker.inFlightRequests++;
  // ...
  try {
    return await worker.core.send<T>(payload);
  } finally {
    worker.inFlightRequests--;
  }
}

// In cleanup:
const idleWorkers = this.processPool.filter(
  w => w.inFlightRequests === 0 && /* other conditions */
);

Impact

Low in practice because:

  1. Idle cleanup protected: Single-worker mode (default) has minProcesses=1, so processPool.length > minProcesses prevents idle termination of the only worker
  2. Overused cleanup rare: Requires 1000+ requests AND the race timing
  3. Multiplexing requires concurrent calls: Sequential usage never triggers this

However, this is a correctness bug that should be fixed for multi-worker pools with high concurrency.

References

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions