A result spec written right after launch can get an mtime below `launched_ns` and be rejected as stale

Abierto
#887 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
34/100
Tipo de issue
Error
Claridad
Bastante claro
Estado de actividad
Activo
Stack tecnológico
python
Área
backend, testing

Línea de trabajo

Start by tracing launched_ns through start_session, the artifact freshness checks in devcontract, and SignalWatcher.wait_for in adapters/generic.py and probe.py; compare the artifact checks with hook-event replay filters. Review the launch paths and existing session snapshot logic, then inspect tests/test_stories_e2e.py and the regression cases listed in the issue. Done means post-launch artifacts qualify under a distinct freshness rule while pre-launch terminal specs and hook events remain rejected.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Summary

launched_ns is taken from time.time_ns() at session launch, and the result-artifact freshness checks compare a file's st_mtime_ns against it (mtime >= launched_ns). On the hosts measured below, a file written after time.time_ns() was read can still get an mtime below that reading, by up to about 20 ms. A session that writes its result spec within that window can have the spec rejected as stale-mtime or no-artifact.

With the scripted fake CLI in tests/test_stories_e2e.py, the observed sequence was:

  1. resultless Stop;
  2. the fake's window dies after its sleep 30, and the session is recorded crashed;
  3. a retry that needs a rollback;
  4. with auto-rollback off, rollback-manual-required and run-paused.

bmad-loop run then exits 0 (RunPaused is caught), with the story's spec on disk saying done and no story commit. A real CLI hitting the same rejection could instead stall, time out, or later produce an artifact that qualifies; that was not observed.

Environment

  • WSL2, Ubuntu 24.04, kernel 5.15.167.4-microsoft-standard-WSL2 (CONFIG_HZ=100, CONFIG_NO_HZ_IDLE=y), ext4 root filesystem, a native clone (not /mnt/c).
  • tmux 3.4, distro Python 3.12.3.
  • bmad-loop main at a4375bba.

Repro

python -m pytest -n 2 -p no:cacheprovider tests/test_stories_e2e.py in that clone: 4 of 4 file runs failed (2, 3, 2 and 7 failures). Ten different tests were hit, among them test_e2e_two_story_happy_path and test_e2e_sweep_intent_gap_patch_restore. Alone, each passes.

Clock check:

import os, tempfile, time

p = os.path.join(tempfile.mkdtemp(), "f")
neg = worst = 0
for _ in range(5000):
    t = time.time_ns()
    with open(p, "w") as f:
        f.write("x")
    m = os.stat(p).st_mtime_ns
    if m < t:
        neg += 1
        worst = max(worst, t - m)
print(f"{neg} of 5000 below time_ns(); worst {worst / 1e6:.1f} ms")

Measured:

  • WSL2 (ext4): 4998 of 5000, worst 19.9 ms.
  • Native Windows 11 (NTFS, Python 3.13.2, where time.time_ns() uses GetSystemTimePreciseAsFileTime): 3088 of 5000, worst 3.6 ms.

Native Linux was not measured.

Evidence

  • Every failing test's task dir has resultless-stops.jsonl, with verdict stale-mtime (.../stories/2-slug.md predates session launch) or no-artifact (no result artifact newer than session launch directly under: .../implementation-artifacts). Passing tests have none.
  • In one failing run, the fake CLI stamped its SessionStart event with date +%s%N = ...148.300279456 before writing the spec, yet the spec's st_mtime is ...148.289336126, 11 ms earlier.
  • Two-story run journal:
    1. story 1 story-done;
    2. story 2 session-end crashed (resultless_verdict: stale-mtime), then dev-decision retry, rollback-manual-required and run-paused.
      HEAD holds only story 1's commit, and the paused run's tmux session stays alive.
  • A/B: with the floor lowered to the filesystem's own clock (log_file.touch(); launched_ns = min(launched_ns, log_file.stat().st_mtime_ns) in start_session), the same file passed 72/72 in 3 of 3 runs, in about 60 s instead of 117–301 s. That one-line change also moves the hook-event floor, so it is a confirmation, not a proposed fix.

Likely cause

The floor mixes two clock sources. On Linux, inode timestamps are normally taken from the kernel's coarse clock, which advances per tick (10 ms at HZ=100). time.time_ns() reads the precise clock. A write less than about a tick after the launch reading can therefore be stamped earlier than it. Why the measured lag (19.9 ms) exceeds one 10 ms tick was not established.

Some Linux filesystems can use fine-grained timestamps (multigrain), so how much this applies depends on the kernel and filesystem. The Windows measurement shows the same symptom; the mechanism there was not investigated.

The fake CLI writes its spec within a few ms of launch, which is why the E2E suite hits this. Real CLIs normally take longer, so in practice the exposure is a very fast session, or a host with coarse timestamps.

Floor consumers

Artifact-freshness checks, which all compare mtime against handle.launched_ns:

  • devcontract.find_result_artifact, is_result_artifact, find_frontmatter_candidates, is_frontmatter_candidate;
  • the nested-spec diagnostics (_nested_spec_hint, find_nested_result_hints, and its unreadable-file path);
  • _DevSynthesisMixin._written_this_session, inherited by GenericDevAdapter and OpencodeDevAdapter.

The opencode HTTP adapter builds its own handle with its own launch stamp.

Hook-event replay filters, SignalWatcher.wait_for(since_ns=...) in adapters/generic.py and probe.py, compare against hook-event wall-clock nanosecond stamps (time.time_ns() in the production hooks, date +%s%N in the E2E fake). They are correct as they are and must keep launched_ns.

Fix direction (open for discussion)

Keep launched_ns for hook-event filtering, and give the artifact checks a separate floor. Options, each with a tradeoff:

  1. Filesystem-clock floor. Sample an mtime floor from the filesystem immediately before launch, ideally by touching a marker beside the artifact dir, not the session log, since artifact dirs can be rebased into a worktree or configured outside the project. Take the floor as min(launched_ns, sampled_mtime) and thread it through both launch paths.
    • Assumes the marker and the artifacts share a filesystem and its clock. Network filesystems that take server timestamps, and backward wall-clock steps, break that.
  2. Fixed slack (subtract a tick or a few ms). Simpler, but it guesses the granularity.

Both widen admission. Because the checks accept mtime >= floor, an unchanged spec written in the same tick before launch would qualify. The stories path has a launch-snapshot gate against an unchanged done spec, but only for review sessions; a dev leg has no snapshot and relies on the mtime floor alone. Comparing against an attempt-relative content snapshot of the artifacts at launch, like the review gate's digest, would avoid the clock question at the cost of a larger change. It detects changed bytes, not who wrote them, and misses an identical rewrite; an (mtime, size) snapshot would not help, since a same-size rewrite within one tick leaves both unchanged.

Regression tests, none needing timing luck:

  • stub time.time_ns ahead of the filesystem clock, and assert a spec written after launch qualifies;
  • assert an unchanged pre-launch terminal spec with an equal timestamp is still rejected where a snapshot exists;
  • assert hook-event replay still rejects pre-launch events.
Lenguaje dominante
Python
Estrellas
196
Forks
78
Merge medio
9 h 24 min
PR fusionados (30 d)
44

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de bmad-code-org/bmad-loop

Todos los issues de bmad-code-org/bmad-loop

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.