Skip to content

Commit d2df489

Browse files
authored
Merge pull request #544 from thisisthepy/feat/543-devagent-marker
Dev agent: read the request from the enabling marker when the variable is unset (SPEC L-12)
2 parents b3d5391 + deb57f1 commit d2df489

5 files changed

Lines changed: 156 additions & 18 deletions

File tree

‎docs/SPEC.md‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,12 @@ fail, then implement.
206206
(`src/commonMain/python/python_multiplatform_devagent.py`, generated into Kotlin by `generateDevAgentSource`)
207207
as the module `python_multiplatform_devagent` and it listens on 127.0.0.1 only. The marker is the build-time
208208
switch: this library is one artifact for debug and release, so the app's build decides, and toolchain stages
209-
the marker into debug variants only. Without it the variable is ignored with a warning and no port opens. The
209+
the marker into debug variants only. Without it the variable is ignored with a warning and no port opens. When
210+
the variable is unset, the marker's content is the request, in the same grammar and with the same token check,
211+
because an installed Android or iOS app is given no environment variable (toolchain #154, its Decision 15 (a),
212+
toolchain team report 2026-11-25 relayed by the leader; #543). The variable wins when set, and an empty marker
213+
means no agent. The default overlay is `tempfile.mkdtemp()`, which is writable on Android because
214+
`PythonBootstrap` sets `TMPDIR` to the app's `cacheDir` (`PythonBootstrapTest.initializeLeavesTempfileUsable`). The
210215
token must be at least 43 characters (`secrets.token_urlsafe(32)`), or the agent refuses to start. The listening
211216
socket cannot be bound by another socket while it listens: `SO_EXCLUSIVEADDRUSE` on Windows; on POSIX,
212217
`SO_REUSEADDR` only so that a restarted app can rebind the launcher's port past TIME_WAIT. A connection's first
@@ -218,12 +223,14 @@ fail, then implement.
218223
and does not stop the app. `Status: partial`: desktop
219224
(`PM/desktopTest/.../env/PythonDevAgentTest.kt`: the embedded agent answers over loopback; a child JVM with the
220225
marker and the variable has an agent on that port, one without the variable has none, one without the marker
221-
(a release build) opens no port with the variable set, and a short token opens no port; the protocol, token
226+
(a release build) opens no port with the variable set, and a short token opens no port; with the variable unset,
227+
one whose marker holds the request has an agent on that port, the variable wins over the marker, and a marker
228+
with a short token opens no port; the protocol, token
222229
length, port takeover and restart: `python-multiplatform/src/test/python/test_devagent.py`, CI `Dev agent
223230
protocol tests` on macOS and the `dev-agent` job on ubuntu and windows (#238; with `SO_EXCLUSIVEADDRUSE`
224231
removed, the Windows takeover test fails, checked once); toolchain stages the marker for `enableHotReload`
225-
builds and passes the variable to the desktop run tasks (toolchain#105), but nothing sets the variable on
226-
Android or iOS yet (toolchain's M2, M3); no interrupt; `execute` runs on the agent's thread (no main-thread dispatch yet).
232+
builds and passes the variable to the desktop run tasks (toolchain#105), but nothing writes the
233+
request into an Android or iOS marker in develop yet (toolchain #154, M2; M3); no interrupt; `execute` runs on the agent's thread (no main-thread dispatch yet).
227234

228235
## 2. Low-level C API (downcall surface)
229236

‎python-multiplatform/src/commonMain/kotlin/python/multiplatform/env/PythonDevAgent.kt‎

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,11 @@ import python.multiplatform.ffi.pyErrorOrGeneric
1010
* The dev agent (SPEC L-12, #233): a debug-only channel from a notebook or a hot reload into this
1111
* interpreter, designed in toolchain's `docs/design/live-connection.md` (option B).
1212
*
13-
* [Python3.initialize] calls [startIfRequested]. It does nothing unless the launcher set
14-
* [ENVIRONMENT_VARIABLE] (`port=<n>;token=<t>[;overlay=<dir>]`) **and** the app was built for it: one of
15-
* its installed payload roots ([PythonPayload.installed]) holds [ENABLE_MARKER]. Then the agent's Python
13+
* [Python3.initialize] calls [startIfRequested]. It does nothing unless the app was built for it (one of
14+
* its installed payload roots, [PythonPayload.installed], holds [ENABLE_MARKER]) **and** a request was made:
15+
* [ENVIRONMENT_VARIABLE] (`port=<n>;token=<t>[;overlay=<dir>]`) when the launcher set it, otherwise the
16+
* marker's own content in the same grammar. An installed Android or iOS app gets no environment variable,
17+
* so toolchain writes the request into a debug staging's marker; an empty marker means no agent. Then the agent's Python
1618
* ([DEV_AGENT_SOURCE], embedded from `src/commonMain/python/python_multiplatform_devagent.py`) is loaded as
1719
* the module [MODULE] and listens on 127.0.0.1 with that token, which must be at least 32 random bytes
1820
* (`secrets.token_urlsafe(32)`). A refused or malformed request is reported on stderr and does not stop the app.
@@ -33,23 +35,32 @@ internal object PythonDevAgent {
3335
private var requested = false
3436

3537
fun startIfRequested() {
36-
if (requested || readEnvVar(ENVIRONMENT_VARIABLE).isNullOrBlank()) return
37-
requested = true
38-
if (enabledRoot() == null) {
38+
if (requested) return
39+
val root = enabledRoot()
40+
if (root == null) {
41+
if (readEnvVar(ENVIRONMENT_VARIABLE).isNullOrBlank()) return
42+
requested = true
3943
println(
4044
"WARNING: python-multiplatform dev agent not started: $ENVIRONMENT_VARIABLE is set, but no " +
4145
"payload root holds $ENABLE_MARKER, so this is not a build made for it (a release build).",
4246
)
4347
return
4448
}
49+
requested = true
4550
try {
4651
load()
47-
Python3.exec("__import__(\"$MODULE\").start_from_env()")
52+
// The variable is the request when set; otherwise the marker's content is (Python's
53+
// `request_text`). An empty marker with no variable starts nothing.
54+
Python3.exec("__import__(\"$MODULE\").start_from_env(${pythonString("$root/$ENABLE_MARKER")})")
4855
} catch (e: Exception) {
4956
println("WARNING: python-multiplatform dev agent not started: ${e.message}")
5057
}
5158
}
5259

60+
/** [text] as a Python string literal. */
61+
private fun pythonString(text: String): String =
62+
"\"" + text.replace("\\", "\\\\").replace("\"", "\\\"") + "\""
63+
5364
/** The installed payload root that holds [ENABLE_MARKER], if any. */
5465
private fun enabledRoot(): String? =
5566
PythonPayload.installed.firstOrNull { pathIsAccessible("$it/$ENABLE_MARKER") }

‎python-multiplatform/src/commonMain/python/python_multiplatform_devagent.py‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
The runtime starts it from `Python3.initialize()` only when the launcher sets the environment variable
66
`PYTHON_MULTIPLATFORM_DEV_AGENT` to `port=<n>;token=<t>[;overlay=<dir>]` (a debug launch does; a release
77
build never does), and only in a build that staged the enabling marker (the runtime checks that; see
8-
`PythonDevAgent.kt`). It listens on 127.0.0.1 only. The token must be at least `MIN_TOKEN_LENGTH` characters
8+
`PythonDevAgent.kt`). When the variable is unset, the marker's content is the request, in the same grammar
9+
(an installed Android or iOS app gets no environment variable); an empty marker means no agent. It listens on 127.0.0.1 only. The token must be at least `MIN_TOKEN_LENGTH` characters
910
(`secrets.token_urlsafe(32)`), or the agent refuses to start. A connection's first message must be `hello`
1011
with the token; anything else closes the connection.
1112
@@ -64,9 +65,28 @@ def parse_request(value):
6465
return {"port": port, "token": token, "overlay": fields.get("overlay") or None}
6566

6667

67-
def start_from_env():
68-
"""Start an agent when the launcher asked for one; return it, or None when it did not."""
69-
value = os.environ.get(ENVIRONMENT_VARIABLE)
68+
def request_text(environ_value, marker_path):
69+
"""The request: the variable when it is set, else the enabling marker's content; None for neither.
70+
71+
An installed Android or iOS app cannot be given an environment variable, so toolchain writes the request
72+
into the marker of a debug staging (SPEC L-12). An empty marker is the switch alone and means no agent.
73+
"""
74+
if environ_value:
75+
return environ_value
76+
if not marker_path:
77+
return None
78+
try:
79+
with open(marker_path, encoding="utf-8") as f:
80+
text = f.read().strip()
81+
except OSError:
82+
return None
83+
return text or None
84+
85+
86+
def start_from_env(marker_path=None):
87+
"""Start an agent when the launcher asked for one (the variable, else the marker at `marker_path`);
88+
return it, or None when it did not."""
89+
value = request_text(os.environ.get(ENVIRONMENT_VARIABLE), marker_path)
7090
if not value:
7191
return None
7292
request = parse_request(value)

‎python-multiplatform/src/desktopTest/kotlin/python/multiplatform/env/PythonDevAgentTest.kt‎

Lines changed: 60 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,58 @@ class PythonDevAgentTest {
110110
}
111111
}
112112

113+
/**
114+
* Android and iOS cannot give an installed app an environment variable, so toolchain writes the request into
115+
* the marker of a debug staging (toolchain #154, Decision 15 (a)). With the variable unset, the marker's
116+
* content is the request.
117+
*/
118+
@Test
119+
fun `with the variable unset, the marker's content is the request`() {
120+
val port = ServerSocket(0).use { it.localPort }
121+
val fromMarker = launchProbe(request = false, debugBuild = true, port = port, marker = "port=$port;token=$token\n")
122+
try {
123+
fromMarker.awaitLine("python-multiplatform dev agent: listening on 127.0.0.1:$port")
124+
Socket("127.0.0.1", port).use { socket ->
125+
socket.soTimeout = 10_000
126+
val reader = BufferedReader(InputStreamReader(socket.getInputStream(), Charsets.UTF_8))
127+
socket.getOutputStream().apply {
128+
write("{\"id\": 1, \"op\": \"hello\", \"token\": \"$token\"}\n".toByteArray())
129+
flush()
130+
}
131+
assertTrue("\"type\": \"hello\"" in reader.readLine())
132+
}
133+
} finally {
134+
fromMarker.process.destroyForcibly()
135+
}
136+
}
137+
138+
/** The variable wins over the marker: the agent listens on the variable's port, not the marker's. */
139+
@Test
140+
fun `the variable wins over the marker`() {
141+
val markerPort = ServerSocket(0).use { it.localPort }
142+
val both = launchProbe(request = true, debugBuild = true, marker = "port=$markerPort;token=$token")
143+
try {
144+
both.awaitLine("python-multiplatform dev agent: listening on 127.0.0.1:${both.port}")
145+
assertFailsWith<ConnectException> { Socket("127.0.0.1", markerPort).close() }
146+
} finally {
147+
both.process.destroyForcibly()
148+
}
149+
}
150+
151+
/** A marker that holds a malformed request or a short token opens no port, and says why. */
152+
@Test
153+
fun `a marker with a short token opens no port`() {
154+
val port = ServerSocket(0).use { it.localPort }
155+
val short = launchProbe(request = false, debugBuild = true, port = port, marker = "port=$port;token=short-token")
156+
try {
157+
short.awaitLine(DevAgentProbe.READY)
158+
assertFailsWith<ConnectException> { Socket("127.0.0.1", port).close() }
159+
assertTrue(short.log.readText().contains("refusing to start"), short.log.readText())
160+
} finally {
161+
short.process.destroyForcibly()
162+
}
163+
}
164+
113165
/** A token shorter than the agent's minimum is refused before anything listens. */
114166
@Test
115167
fun `a debug build refuses a short token and opens no port`() {
@@ -139,13 +191,18 @@ class PythonDevAgentTest {
139191
* [debugBuild] stages a payload as toolchain does for a debug variant: a `python/` root on the class path
140192
* with a module and the marker. A release variant's payload is the same without the marker.
141193
*/
142-
private fun launchProbe(request: Boolean, debugBuild: Boolean, token: String = this.token): Probe {
143-
val port = ServerSocket(0).use { it.localPort }
194+
private fun launchProbe(
195+
request: Boolean,
196+
debugBuild: Boolean,
197+
token: String = this.token,
198+
port: Int = ServerSocket(0).use { it.localPort },
199+
marker: String = "",
200+
): Probe {
144201
val workDir = Files.createTempDirectory("pmp-devagent-probe").toFile()
145202
val log = File(workDir, "probe.log")
146203
val payload = File(workDir, "classes/${PythonPayload.PAYLOAD_ROOT}").apply { mkdirs() }
147204
File(payload, "devagent_probe_app.py").writeText("VALUE = 1\n")
148-
if (debugBuild) File(payload, PythonDevAgent.ENABLE_MARKER).writeText("")
205+
if (debugBuild) File(payload, PythonDevAgent.ENABLE_MARKER).writeText(marker)
149206
val command = listOf(
150207
File(System.getProperty("java.home"), "bin/java").path,
151208
"--enable-preview",

‎python-multiplatform/src/test/python/test_devagent.py‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,49 @@ def test_the_request_comes_from_the_environment(self):
130130
with self.assertRaises(ValueError, msg=bad):
131131
devagent.parse_request(bad)
132132

133+
def test_with_the_variable_unset_the_marker_is_the_request(self):
134+
marker = os.path.join(tempfile.mkdtemp(), "python_multiplatform_devagent.enable")
135+
with open(marker, "w") as f:
136+
f.write(f"port=4719;token={TOKEN}\n")
137+
self.assertEqual(f"port=4719;token={TOKEN}", devagent.request_text(None, marker))
138+
self.assertEqual(f"port=4719;token={TOKEN}", devagent.request_text("", marker))
139+
self.assertEqual(
140+
{"port": 4719, "token": TOKEN, "overlay": None}, devagent.parse_request(devagent.request_text(None, marker))
141+
)
142+
143+
def test_the_variable_wins_over_the_marker(self):
144+
marker = os.path.join(tempfile.mkdtemp(), "python_multiplatform_devagent.enable")
145+
with open(marker, "w") as f:
146+
f.write(f"port=4719;token={TOKEN}")
147+
self.assertEqual(f"port=5000;token={TOKEN}", devagent.request_text(f"port=5000;token={TOKEN}", marker))
148+
149+
def test_an_empty_or_missing_marker_means_no_agent(self):
150+
directory = tempfile.mkdtemp()
151+
marker = os.path.join(directory, "python_multiplatform_devagent.enable")
152+
self.assertIsNone(devagent.request_text(None, marker), "a missing marker")
153+
self.assertIsNone(devagent.request_text(None, None), "no marker path")
154+
with open(marker, "w") as f:
155+
f.write(" \n")
156+
self.assertIsNone(devagent.request_text(None, marker), "a blank marker")
157+
saved = os.environ.pop(devagent.ENVIRONMENT_VARIABLE, None)
158+
try:
159+
self.assertIsNone(devagent.start_from_env(marker))
160+
finally:
161+
if saved is not None:
162+
os.environ[devagent.ENVIRONMENT_VARIABLE] = saved
163+
164+
def test_a_marker_with_a_short_token_is_refused(self):
165+
marker = os.path.join(tempfile.mkdtemp(), "python_multiplatform_devagent.enable")
166+
with open(marker, "w") as f:
167+
f.write(f"port=4719;token={TOKEN[: devagent.MIN_TOKEN_LENGTH - 1]}")
168+
saved = os.environ.pop(devagent.ENVIRONMENT_VARIABLE, None)
169+
try:
170+
with self.assertRaises(ValueError):
171+
devagent.start_from_env(marker)
172+
finally:
173+
if saved is not None:
174+
os.environ[devagent.ENVIRONMENT_VARIABLE] = saved
175+
133176
def test_a_short_token_is_refused_before_anything_listens(self):
134177
short = TOKEN[: devagent.MIN_TOKEN_LENGTH - 1]
135178
with self.assertRaises(ValueError):

0 commit comments

Comments
 (0)