Skip to content

[csp] Bug with race condition of select() and read() + suggested fix #546

@azerum

Description

@azerum

I assume that select() should unblock with undefined only when the selected channel is closed

However, it may unblock undefined even when the channel is not closed. This happens when read() runs after write(), before continuation of select():

import { channel, select } from '@thi.ng/csp'

void main()

async function main() {
    const ch = channel<number>(1)
    const s = select(ch)

    queueMicrotask(async () => {
        const x = await ch.read()
        console.log('Did read', x)
    })

    ch.write(42)

    const [v, _] = await s
    console.log('Did select', v)
}

Expected output:

Did read 42
<select remains blocked>

Actual output:

Did read 42
Did select undefined

This requires write() to happen within the same call that schedules callback doing read(), so might never happen in real world code. Still, it might a tricky bug

One way to handle this is to do poll() after race(), and re-run the race if the selected channel is empty and not closed

Shameless plug: I've implemented similar library before finding the great @thi.ng, and decided to publish it anyway. Here's select implementation that handles the case

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions