Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

2.4 KB
Raw Blame
# Copyright 2026 Marimo. All rights reserved.
"""Subprocess driver for a controlled interruption of a real host stream."""

from __future__ import annotations

import json
import socket
import sys
import threading
from pathlib import Path
from typing import TYPE_CHECKING
from unittest.mock import patch

import msgspec

from marimo._cli.pair import forwarder
from marimo._cli.pair.client import EventStream, open_events
from marimo._cli.pair.forwarder import ForwarderConfig

if TYPE_CHECKING:
    from marimo._cli.pair.delivery import ProcessHandle


class RecordingInbox:
    inbox_bytes = 8192

    def __init__(self, directory: Path, owner: ProcessHandle | None) -> None:
        self.directory = directory
        self.owner = owner

    def alive(self) -> bool:
        return self.owner is not None and self.owner.alive()

    def send(self, text: str) -> None:
        with (self.directory / "inbox.jsonl").open("a") as output:
            output.write(json.dumps({"message": text}) + "\n")


def main() -> None:
    directory = Path(sys.argv[1])
    config = msgspec.json.decode(sys.stdin.readline(), type=ForwarderConfig)
    calls = 0

    def controlled_events(
        *,
        url: str,
        notebook: str,
        token: str | None,
        identity: str,
        name: str,
        cursor: str | None = None,
    ) -> EventStream:
        nonlocal calls
        calls += 1
        if calls == 2:
            print(json.dumps({"cursor": cursor}), flush=True)
            assert sys.stdin.readline() == "resume\n"
        response = open_events(
            url=url,
            notebook=notebook,
            token=token,
            identity=identity,
            name=name,
            cursor=cursor,
        )
        if calls == 1:

            def drop() -> None:
                command = sys.stdin.readline()
                assert command == "drop\n", (
                    f"Expected drop command, got {command!r}"
                )
                response.socket.shutdown(socket.SHUT_RDWR)

            threading.Thread(target=drop, daemon=True).start()
        return response

    with patch.object(forwarder, "open_events", side_effect=controlled_events):
        forwarder.run_forwarder(
            config,
            RecordingInbox(directory, config.target.process),
            ready=lambda: print("attached", flush=True),
        )


if __name__ == "__main__":
    main()