Skip to content

bug: First-time setup token silently lost — print() block-buffered, breaks fresh installs #858

Closed

Description

@AndriiPasternak31

Summary

The first-time setup flow described in docs/memory/architecture.md is silently broken on fresh installs of dev. The setup token printed in main.py:335-341 never reaches docker logs, so operators cannot complete the /api/setup/admin-password flow described in routers/setup.py:54-78. Every fresh Trinity deploy hits this on first boot.

This blocks the trinity:deploy skill (deploy plugin v2.2.0), which instructs operators to read the token from docker compose logs backend.

Root cause

  1. docker/backend/Dockerfile is missing ENV PYTHONUNBUFFERED=1. The scheduler Dockerfile already has it (see docker/scheduler/Dockerfile), but the backend Dockerfile drifted and lost it.
  2. With PYTHONUNBUFFERED unset and stdout connected to a Docker log pipe (not a TTY), Python defaults to block-buffered stdout (~8KB). The lifespan's print() output (setup token plus ~30 other status prints) sits in the buffer and never flushes during normal operation.
  3. Diagnostic confirmation inside the running container:
    $ docker exec trinity-backend env | grep PYTHONUNBUFFERED
    (empty)
    $ docker exec trinity-backend python -c "import sys; print('isatty:', sys.stdout.isatty()); print('line_buffering:', sys.stdout.line_buffering)"
    isatty: False
    line_buffering: False
    

Repro

  1. Fresh Trinity install (no existing DB, setup_completed != 'true').
  2. ./scripts/deploy/start.sh.
  3. docker compose logs backend | grep -i "setup token" → nothing.
  4. Operator opens UI → setup screen demands a token printed in server logs → token is invisible → onboarding deadlock.

Other affected print() calls in the same lifespan (all silently lost): Found N existing agent containers (line 346), System agent: ... (line 355), Using dedicated scheduler service (line 369), Log archive service started (line 374), Audit retention service started (line 381), DB vacuum service started (line 388), and ~20 more.

Fix (verified locally on this branch)

Two layers, both required.

Layer 1 — Dockerfile (catches every print() call)

docker/backend/Dockerfile:

 FROM python:3.11-slim

 WORKDIR /app

+# Unbuffered stdout/stderr — otherwise Python block-buffers print() to the
+# Docker pipe (~8KB) and lifespan output (notably the first-time setup token
+# in main.py) never reaches `docker logs`. Matches docker/scheduler/Dockerfile.
+ENV PYTHONUNBUFFERED=1
+
 # Install curl for healthcheck...

Matches the existing docker/scheduler/Dockerfile precedent. Zero functional change — pure buffering knob.

Layer 2 — Logger for setup token (defense in depth)

src/backend/main.py:329-341 — switch the security-critical setup token block from print() to logger.warning(). Python's logging StreamHandler flushes after every record, so this path is immune to any future Dockerfile drift. Bonus: token now flows through the structured JSON logger and Vector's pipeline.

-    # Print setup token if first-time setup is not yet complete (SEC #177).
+    # Emit setup token if first-time setup is not yet complete (SEC #177).
     # Only someone with access to server logs can read this token and complete setup,
     # preventing installation hijack by unauthenticated remote attackers.
+    #
+    # Use logger.warning (not print) because the lifespan runs under uvicorn
+    # with stdout connected to a pipe — without PYTHONUNBUFFERED=1, print()
+    # output is block-buffered and the token is silently lost from
+    # `docker logs`. The logging module flushes after every record, so this
+    # works regardless of Dockerfile drift.
     from database import db as _db
     if _db.get_setting_value('setup_completed', 'false') != 'true':
         _setup_token = get_setup_setup_token()
-        print("=" * 60)
-        print("TRINITY FIRST-TIME SETUP REQUIRED")
-        print("=" * 60)
-        print(f"Setup token: {_setup_token}")
-        print("Visit the Trinity UI and enter this token to set the admin password.")
-        print("This token is only valid for this session.")
-        print("=" * 60)
+        logger.warning("=" * 60)
+        logger.warning("TRINITY FIRST-TIME SETUP REQUIRED")
+        logger.warning("=" * 60)
+        logger.warning(f"Setup token: {_setup_token}")
+        logger.warning("Visit the Trinity UI and enter this token to set the admin password.")
+        logger.warning("This token is only valid for this session.")
+        logger.warning("=" * 60)

Verification (post-fix, fresh image)

$ docker exec trinity-backend env | grep PYTHONUNBUFFERED
PYTHONUNBUFFERED=1

$ docker logs trinity-backend 2>&1 | grep -E "TRINITY FIRST-TIME|Setup token"
{"timestamp": "...", "level": "WARNING", "logger": "main", "message": "TRINITY FIRST-TIME SETUP REQUIRED"}
{"timestamp": "...", "level": "WARNING", "logger": "main", "message": "Setup token: <redacted>"}

$ docker logs trinity-backend 2>&1 | grep -E "Found.*agent|Using dedicated scheduler|Log archive service started"
Found 1 existing Trinity agent containers
Using dedicated scheduler service (trinity-scheduler)
Log archive service started

All previously-lost output now reaches docker logs. Setup flow unblocked end-to-end.

Follow-up (separate issue — not blocking)

The remaining ~25 print() calls in main.py lifespan (lines 346-490+) are status messages. With PYTHONUNBUFFERED=1 in place they now reach docker logs, but they're inconsistent with the rest of the codebase which uses structured JSON logging. A cleanup pass converting them to logger.info() would improve observability via Vector and Grafana. Not urgent.

Why P1

  • Blocks every fresh Trinity install — the only documented way to complete first-time setup is via the printed token.
  • The trinity:deploy skill explicitly tells operators to docker compose logs backend for the token.
  • Security gate (routers/setup.py:74) makes the token mandatory; there's no fallback path.
  • Affects SOC 2 onboarding story — operators can't self-serve install.

Acceptance criteria

  • docker/backend/Dockerfile sets ENV PYTHONUNBUFFERED=1 (parity with docker/scheduler/Dockerfile).
  • src/backend/main.py:329-341 setup-token block uses logger.warning(...) instead of print(...).
  • After docker compose build backend && docker compose up -d --force-recreate backend on a fresh install, docker logs trinity-backend | grep "Setup token:" returns the token within 30 seconds of container start.
  • Existing scheduler / mcp-server / agent-base behavior unchanged.

Activity

  1. added
    complexity-low
    on Jun 3, 2026
  2. added 2 commits that reference this issue on Jun 12, 2026
    71799b7
    de0b329
  3. added
    status-ready
    on Jun 14, 2026
  4. added
    status-in-dev
    on Jun 16, 2026
  5. added a commit that references this issue on Jun 23, 2026
  6. added a commit that references this issue on Jul 8, 2026
  7. removed
    status-in-dev
    status-ready
    on Aug 7, 2026
  8. added a commit that references this issue on Sep 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

complexity-lowpriority-p1theme-devextype-bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions