Skip to content

fix(python): AIRC_PYTHON env var replaces broken export -f shim (THE root cause) - #164

Merged
joelteply merged 1 commit into
canaryfrom
fix/python3-subshell-leak-airc-python-var
Apr 27, 2026
Merged

joelteply merged 1 commit into
canaryfrom
fix/python3-subshell-leak-airc-python-var

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Bug (continuum-b69f traced send 2026-04-27)

PR #153's bash function shim `python3() { command python "$@"; }` exported via `export -f` does NOT reliably inherit into `$(...)` command-substitution subshells on Git Bash MINGW. Every site that captured `$(python3 -c "...")` output (45+ in airc) bypassed the shim, hit the Microsoft Store stub, exited 49 with empty stdout.

Cascade:

  • `get_name` → `from:"unknown"` in stored messages
  • `get_config_val host_target ""` → empty → cmd_send takes HOST path (no host_target check), mirrors locally only, NEVER SSH-pushes
  • All `|| echo ""` fallbacks silently mapped 49-exit to empty string

Net: continuum's Windows `airc msg` returned exit 0, mirrored locally, broadcast NEVER reached the mac host. Every Win→Mac broadcast invisible-failed for the entire session.

Fix

Bash variable instead of function shim — variables propagate to subshells unconditionally:

```bash
if python3 --version >/dev/null 2>&1; then AIRC_PYTHON=python3
elif command -v python >/dev/null 2>&1 && python --version >/dev/null 2>&1; then AIRC_PYTHON=python
else die-with-Windows-Store-hint
fi
export AIRC_PYTHON
```

Then sed: 45 `python3 -c` callsites → `"$AIRC_PYTHON" -c`. Two `command -v python3` guards → `[ -n "${AIRC_PYTHON:-}" ]`.

Beyond Win→Mac

This unblocks the entire Windows code path. Every config read on Git Bash was silently corrupted; every send silent-failed. Mac/Linux unaffected (function-shim only fires when python3 is missing/stubbed, which doesn't happen on those).

Mac regression

scenario result
identity 19/19
whois 5/5
part_persists 8/8
list 4/4
general_sidecar_default 12/12
platform_adapters 11/11

Filing for follow-up

continuum's secondary observations:

  1. `relay_ssh` should fail loudly when host_target is empty (defense-in-depth)
  2. `|| echo ""` on get_config_val / get_name masks any exec failure (silent-data-loss class)

Both worth real fixes; out of scope here.

…root cause continuum found)

continuum-b69f's traced send 2026-04-27 found THE bug behind every
silent-broadcast-failure on Windows Git Bash. Long-form analysis in
the cross-Mac/Windows coord gist; tldr below.

## Bug

PR #153 added a bash function shim:

```bash
if ! python3 --version >/dev/null 2>&1; then
  if command -v python >/dev/null 2>&1; then
    python3() { command python "$@"; }
    export -f python3 2>/dev/null || true
  fi
fi
```

`export -f python3` is supposed to propagate the function into
subshells. On Git Bash MINGW, `export -f` succeeds silently but the
function does NOT reliably inherit into `$(...)` command-substitution
subshells. Result: every callsite that captures `$(python3 -c "...")`
output (45+ in airc) bypassed the shim, hit the Microsoft Store
stub, exited ~49 with empty stdout. The `|| echo ""` fallbacks on
those sites then silently set config values to empty strings.

Cascade:
- `get_name` → `from:"unknown"` in stored messages
- `get_config_val host_target ""` → empty → cmd_send takes HOST path
  (no `[ -n "$host_target" ]`), mirrors locally only, NEVER SSH-pushes
- `get_config_val host_airc_home ""` → empty → would-be wrong path
  anyway (but moot since SSH was skipped)

Net: continuum's Windows airc msg returned exit 0, mirrored locally,
broadcast NEVER reached the mac host's messages.jsonl. cmd_send's
"queue or die" failure paths never fired because cmd_send thought
it WAS the host. Every Win→Mac broadcast invisible-failed.

## Fix (continuum's prescription)

Replace the function-shim with a bash variable. Bash variables
propagate to subshells unconditionally — no function-export quirks.

```bash
if python3 --version >/dev/null 2>&1; then
  AIRC_PYTHON=python3
elif command -v python >/dev/null 2>&1 && python --version >/dev/null 2>&1; then
  AIRC_PYTHON=python
else
  echo "ERROR: airc requires a working python3..." >&2
  exit 1
fi
export AIRC_PYTHON
```

Then sed across airc: every `python3 -c "..."` callsite (45 of them)
becomes `"$AIRC_PYTHON" -c "..."`. The two `command -v python3`
guards (which became unreliable under the Store-stub case) become
`[ -n "${AIRC_PYTHON:-}" ]` — set if and only if a working python
resolved at startup.

## Why this matters beyond Win→Mac

The same `export -f` leak silently corrupted every config read on
Windows Git Bash. Every `airc nick` rendered nicks blank; every
`airc whois` walked an empty peer file path; every `cmd_send` was
mirroring-locally-only. Three full days of "Windows works" reports
were actually "Windows mostly works for read-only commands; sends
silent-fail." This fix unblocks the whole Windows code path.

## Test posture (Mac regression — function-shim never fired here)

- identity: 19/19
- whois: 5/5
- part_persists: 8/8
- list: 4/4
- general_sidecar_default: 12/12
- platform_adapters: 11/11

## Out of scope

continuum's secondary observations:
1. `relay_ssh` should fail loudly when host_target is empty rather
   than silent no-op. Defense in depth — this PR fixes the upstream
   cause; failing-loudly downstream is an additional safety net.
2. `|| echo ""` patterns on get_config_val / get_name silently mask
   ANY exec failure (not just Store-stub). Worth reviewing each
   callsite; out of scope for this PR which fixes the immediate
   blocker.

Both filed as separate issues for follow-up.
Copilot AI review requested due to automatic review settings April 27, 2026 21:24
@joelteply
joelteply merged commit 99e3e20 into canary Apr 27, 2026
2 checks passed
@joelteply
joelteply deleted the fix/python3-subshell-leak-airc-python-var branch April 27, 2026 21:24

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR fixes Windows Git Bash failures caused by relying on an exported bash function (export -f) to shim python3, which does not reliably propagate into $(...) command-substitution subshells on MINGW. It replaces the shim with an exported AIRC_PYTHON environment variable and updates all Python callsites to invoke the resolved interpreter consistently.

Changes:

  • Resolve the Python interpreter once at startup into AIRC_PYTHON and export it for subshell safety.
  • Replace all python3 -c ... callsites with "$AIRC_PYTHON" -c ....
  • Replace command -v python3 guards with checks against AIRC_PYTHON being set.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread airc
Comment on lines +38 to +43
if python3 --version >/dev/null 2>&1; then
AIRC_PYTHON=python3
elif command -v python >/dev/null 2>&1 && python --version >/dev/null 2>&1; then
AIRC_PYTHON=python
else
echo "ERROR: airc requires a working python3 (or python on Windows/Git Bash)." >&2

Copilot AI Apr 27, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fallback branch accepts any python that runs, but multiple inline snippets in this script use Python 3-only features (e.g., f-strings, datetime.timezone, subprocess.run(..., capture_output=..., text=...)). On systems where python is Python 2.x (still common on some older Linux/Cygwin installs), this will pass the probe and then fail later with syntax/runtime errors. Please make the probe validate that the chosen interpreter is Python 3 (and ideally enforce the minimum minor version the script requires), and only set AIRC_PYTHON when that check succeeds; otherwise print the install guidance and exit 1.

Suggested change
if python3 --version >/dev/null 2>&1; then
AIRC_PYTHON=python3
elif command -v python >/dev/null 2>&1 && python --version >/dev/null 2>&1; then
AIRC_PYTHON=python
else
echo "ERROR: airc requires a working python3 (or python on Windows/Git Bash)." >&2
# Validate that the selected interpreter is Python 3.7+ because later
# inline snippets rely on Python 3-only features, including
# subprocess.run(..., capture_output=..., text=...).
python_supports_airc() {
local candidate="$1"
command -v "$candidate" >/dev/null 2>&1 || return 1
"$candidate" -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 7) else 1)' >/dev/null 2>&1
}
if python_supports_airc python3; then
AIRC_PYTHON=python3
elif python_supports_airc python; then
AIRC_PYTHON=python
else
echo "ERROR: airc requires a working Python 3.7+ interpreter (python3, or python on Windows/Git Bash)." >&2

Copilot uses AI. Check for mistakes.
joelteply added a commit that referenced this pull request Apr 27, 2026
…_* config write (continuum's retest) (#165)

fix(airc): two PR #164 followups — sed missed line 1372 + harden host_* config write

continuum-b69f's PR #164 retest 2026-04-27 found two remaining bugs:

## Bug A: sed missed `python3 -u -c '` at line 1372

PR #164's sed pattern was `python3 -c` — didn't match the `-u` flag
sandwiched between python3 and -c at line 1372 (monitor_formatter
unbuffered launch). On Windows Git Bash with the Microsoft Store
stub, this site silent-failed too: monitor_formatter crashed at
launch, the inbound stream went dark, joiner couldn't see anything
the host wrote. One-line fix: `python3 -u -c '` →
`"$AIRC_PYTHON" -u -c '`.

## Bug B: host_* config write silently no-op'd if ANY bash subst broke

continuum's joiner config showed `name`, `host`, `host_target`,
`created` but NOT `host_airc_home`, `host_name`, `host_port`,
`host_ssh_pub`, `host_identity` — all five fields written together
by the heredoc at line 2768.

Pre-fix:
```bash
HOST_IDENTITY="$host_identity_json" "$AIRC_PYTHON" -c "
import json, os
c = json.load(open('$CONFIG'))
c['host_airc_home'] = '$host_airc_home'
c['host_name']      = '$peer_name'
c['host_port']      = ${peer_port:-7547}
c['host_ssh_pub']   = '''$host_ssh_pub'''
...
" 2>/dev/null || true
```

Five bash substitutions into python source. If ANY substitution
breaks python parsing (newline in host_ssh_pub, special char in
host_airc_home, empty/non-numeric peer_port, etc.) the whole heredoc
crashes at parse time. `2>/dev/null || true` swallows the SyntaxError
and zero fields land. Five silently-empty config fields downstream:
- host_airc_home empty → cmd_send computes wrong remote path
- host_name empty → "Connected to ''" banner
- host_port wrong → SSH targets wrong port (or 7547 fallback)
- host_ssh_pub empty → host's SSH key not in authorized_keys
- host_identity empty → airc whois <host> shows (unset)

Post-fix: pass everything as env vars; python reads from os.environ.
Bash never touches the python source. Also emit stderr to a warn line
(not /dev/null) so the future debugger can see it. Also catch
ValueError on int(host_port) so a non-numeric value falls back to
7547 instead of dying.

## Pattern lesson

bash → python heredoc with bash variable substitution into the
python SOURCE is fragile. Any unusual byte in the variable can
break python parsing. Same shape as the resolver heredoc that
broke pre-PR #155 with set -e + pipefail.

Repeat-offender pattern. Consider a sweep: every `"$AIRC_PYTHON" -c
"..."` heredoc that contains `$bash_var` substitutions — convert to
env-var pass + os.environ. Out of scope for this PR (would touch
~30 sites); file as a separate canary follow-up.

## Test posture

Mac regression (5 scenarios, all green):
- identity 19/19
- whois 5/5
- part_persists 8/8
- list 4/4
- general_sidecar_default 12/12

End-to-end Win→Mac broadcast verification still pending continuum's
retest after pulling this fix.
joelteply added a commit that referenced this pull request Apr 27, 2026
…Phase 0) (#166)

Joel 2026-04-27: "3000 lines of code dear god" → "yes" (start the
architectural pivot to airc_core).

Today's session shipped 17 PRs, ~half fighting bash → python heredoc
fragility (silent SyntaxErrors, function-export leaks, missed sed
patterns, swallowed stderr). The pattern is the problem: bash
substituting variables INTO python source code is a per-site silent
fail. PR #164 fixed the export -f leak via AIRC_PYTHON; PR #165
hardened ONE heredoc with env-var pass; ~30 more heredocs remain.

This PR pivots: business logic moves to a Python truth-layer
package (airc_core/), bash + ps1 become thin shells that invoke
the Python via -m. Same input → same output → same testable code,
no more bash-into-python escaping.

## Phase 0: foundation

- `lib/airc_core/__init__.py` — package marker. v0.1.0.
- airc bash resolves the lib dir at startup (4 candidates, first hit
  wins; canonicalizes to absolute via cd+pwd so PYTHONPATH stays
  valid across cwd changes). Sets PYTHONPATH unconditionally.
- New debug command `airc debug-pythonpath` echoes the resolved
  path + tests `import airc_core` end-to-end.
- install.sh changes: none needed — the existing clone-everything
  shape already pulls lib/ along.

## Phase 0a: first function migrated

- `lib/airc_core/datetime.py` exposes `iso_to_epoch()` with a CLI
  entry: `python -m airc_core.datetime iso_to_epoch <ts>`.
- Bash `iso_to_epoch` shrinks from 22 lines (3-fallback adapter
  chain) to 4 lines (single Python module call).
- Test harness in scenario_platform_adapters updated to set
  AIRC_PYTHON + PYTHONPATH for the extracted-adapter shell so
  the test sees the Python module.

## Why iso_to_epoch as the first migration

- Pure logic, no I/O — easiest to verify identical behavior.
- Already adapter-fied in PR #151 (clean callsite contract).
- Three callsites downstream — proves the pattern works for both
  the function definition AND its consumers.
- Smallest possible blast radius if the pattern flubs.

## Test posture

- platform_adapters: 11/11 (was 11/11; iso_to_epoch trio still green
  through the migrated code path)
- part_persists: 8/8 (downstream consumer via heartbeat parse)
- list: 4/4 (downstream consumer via _format_relative_time)
- general_sidecar_default: 12/12 (sidecar spawn touches the path)

## Pattern for follow-up phases

Phase 0a establishes the shape. For each subsequent migration:

1. Identify a heredoc-heavy function in airc bash.
2. Re-implement the logic in airc_core/<module>.py with a CLI entry.
3. Bash function becomes a 1-line `"$AIRC_PYTHON" -m airc_core.<module> <subcommand> "$@"` call.
4. Run integration tests; verify identical bash-side behavior.
5. Same module is callable from airc.ps1 (Phase 2 — drift between
   bash and ps1 ports goes away mechanically).

Priority order for Phase 1 (high-fragility first):
- pair handshake JSON build/parse (~80 lines, env-var pass already
  partially done in #165)
- gist envelope build (host's response payload)
- gist envelope resolve (joiner's parse — the JSON-key-leak class)
- monitor_formatter (the long-running -u -c heredoc; missed by sed
  in #164, fixed in #165)
- host_address_set (network enumeration)
- config CRUD (45+ callsites; biggest dedupe but most plumbing)

## Out of scope for this PR

- No Phase 1 migrations land here. Joel reviews the SHAPE first.
- airc.ps1 still uses its own duplicate logic; that's Phase 2.
- The 30+ remaining heredocs in airc bash still exist; they'll
  migrate one at a time per the Phase 1 priority order.
joelteply added a commit that referenced this pull request Apr 27, 2026
…nd-to-end (#177)

fix(msys): export MSYS2_ARG_CONV_EXCL at airc startup — last layer of cross-machine fix (continuum's catch + verify)

continuum-b69f's diagnosis 2026-04-27: even with PR #174 + #176's
argparse `--flags`, MSYS Git Bash on Windows translates argv VALUES
that look like Unix-rooted paths when bash invokes a Windows-native
binary. So `--host-airc-home /Users/joelteply/.airc` arrived at
python.exe as `--host-airc-home C:/Program Files/Git/Users/joelteply/.airc`,
the joiner cached the corrupted path, the SSH command later sent
it to a real Unix host that had no such file. Silent broadcast
failure.

## Fix

```bash
export MSYS2_ARG_CONV_EXCL="${MSYS2_ARG_CONV_EXCL:-/Users/;/home/;/root/}"
```

Set once at airc startup, exported, every airc_core invocation
inherits the same translation policy. Targeted prefix list covers
macOS / Linux / root home prefixes without breaking `/tmp/` or `/c/`
paths (which DO need translation for `--config "$CONFIG"` where
$CONFIG is on the local Windows filesystem). Honors a user override
via the `${...:-...}` default-fallback.

## End-to-end verification

continuum-b69f shipped a test broadcast from Windows after their
local patch:

> WORKING TEST: Windows-Mac airc msg via continuum-msyspatch with
> targeted MSYS exclude. should land!

Verified live in MY host's messages.jsonl on Mac:

```
{"from":"continuum-msyspatch","to":"all","ts":"2026-04-27T23:30:13Z",
 "msg":"WORKING TEST: Windows-Mac airc msg via continuum-msyspatch
 with targeted MSYS exclude. should land!","sig":"..."}
```

**Cross-machine Mac↔Windows airc end-to-end working.** This was the
last bug in the chain that started at PR #153 (Microsoft Store
python3 stub).

## Test posture (Mac, where the env var is a no-op)

- tabs 19/19, identity 19/19, whois 5/5, part_persists 8/8,
  list 4/4, general_sidecar_default 12/12, kick 12/12, events 5/5,
  platform_adapters 11/11, whois_cross_scope 6/6

## Today's full chain of cross-machine fixes

#153 → #154 → #155 → #156 → #157 → #158 → #159 → #160 → #162 →
#164 → #165 → #166 → ... → #176 → this. 27+ PRs to ship a working
cross-machine airc on Windows. Every step revealed a new layer.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants