feat: join the decode butterfly so scene boundaries reach the face branch

AR-010 — is_scene_boundary had no producer: SceneDetectorFunc was a terminal
sink writing scenes.json and never annotating the frames flowing to face
detection. The flag was permanently false, so the boundary half of AR-007's
frame-dependent association was dead code that a test could still exercise
synthetically and appear to verify.

The topology already forks after decode — dense frames to TransNetV2, sampled
frames to face detection — so this is a fork-join. SceneBoundaries is the join:
the detector publishes each window's verdict with a watermark, and an annotator
on the sampled branch stamps the flag.

The watermark is the part that matters. TransNetV2 buffers 100 frames before it
can score any of them, so at any instant it has an opinion up to some time T and
none after. Without recording T a consumer cannot tell "no boundary" from "not
scored yet", and those demand opposite behaviour — treating unscored frames as
boundary-free is exactly what makes a downstream check pass while verifying
nothing.

Buffering alone does not work, which was my first attempt. Channel depth creates
lag only when the consumer is slower, and the face branch runs four orders of
magnitude faster per frame than TransNetV2 (0.01ms vs 400ms), so its channels
drain instantly and no lag accumulates. Measured: 106 of 364 frames outran the
detector. The annotator therefore waits on the watermark explicitly. The
detector signals completion so the tail cannot deadlock, and publishes from
flush_remaining too — without that the final frames arrive with no verdict.

Boundaries are deduped on publish, matching what scenes.json does at write time.
A run of adjacent high-scoring frames is one boundary, not several; leaving them
raw made this view report 357 where the file said 13. Now the two agree exactly.

Frames past the detector's last scored window remain unverified and are counted
as such rather than silently marked boundary-free.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

TRACES: AR-007, AR-010 | SR-002
This commit is contained in:
2026-07-31 14:56:38 +02:00
co-authored by Claude Opus 5
parent fa1c494825
commit 13bdc27566
7 changed files with 393 additions and 15 deletions
+67 -2
View File
@@ -60,6 +60,8 @@
#include "nodes/identity_matcher_node.hpp"
#include "nodes/scene_tracker_node.hpp"
#include "nodes/scene_detector_node.hpp"
#include "scene_boundaries.hpp"
#include "nodes/scene_boundary_annotator_node.hpp"
#include "nodes/result_sink_node.hpp"
#include "nodes/embedding_dump_node.hpp"
#ifdef SAE_DEBUG
@@ -81,6 +83,18 @@
// ── CLI parsing ───────────────────────────────────────────────────────────────
/// TRACES: AR-010, AR-004 | SR-002
/// How deeply the sampled branch is buffered behind the dense one. TransNetV2
/// needs kWindow (100) dense frames before it can score any of them, so the face
/// branch must lag by at least that much or it asks about frames nobody has
/// looked at yet. Backpressure turns depth into lag: the fanout blocks on the
/// slower branch rather than dropping, so the detector simply runs ahead.
static constexpr std::size_t kSceneJoinDepth = 256;
/// Set when the scene branch is built, so shutdown can report whether the join
/// actually worked.
static std::shared_ptr<SceneBoundaries> scene_stats;
static Config parse_args(int argc, char** argv) {
Config cfg;
cfg.detector_model = kDefaultDetectorModel;
@@ -292,6 +306,21 @@ int main(int argc, char** argv) {
//
// Reporting it in a footer and exiting 0 made both invisible: the run
// "succeeded" and the truth file looked complete. Fail instead.
/// TRACES: AR-010 | SR-002
if (scene_stats) {
std::cerr << "[scene_annotate] boundaries=" << scene_stats->count()
<< " scored_through=" << scene_stats->scored_through() << "s";
// The tail is expected: frames after the detector's last full
// window are never covered, and no amount of buffering changes
// that. They are counted rather than silently treated as
// boundary-free, which is the distinction that matters.
if (scene_stats->outran() > 0)
std::cerr << " unscored=" << scene_stats->outran()
<< " frame(s) past the detector's last window — treated as"
" boundary-free, which is unverified rather than known";
std::cerr << "\n";
}
bool dropped = false;
{
std::lock_guard<std::mutex> lk(event_mtx);
@@ -346,6 +375,21 @@ int main(int argc, char** argv) {
if (cfg.scene_detect) {
scene_done.store(false, std::memory_order_release); // now a real terminal branch
SceneDetectorFunc scene_fn{cfg, scene_done};
/// TRACES: AR-010 | SR-002
// The join of the decode butterfly. source fans out to the dense
// TransNetV2 branch and the sampled face branch; boundaries found on the
// first have to reach the second, and cannot ride the frames because the
// branches run in parallel.
//
// TransNetV2 buffers kWindow frames before it can score any of them, so
// the face branch must lag by at least that much or it will ask about
// frames nobody has looked at yet. Channel depth is what creates the lag:
// with backpressure (AR-004) the fanout blocks on the slower branch, so
// a deep face-branch channel lets the detector run ahead by its window
// rather than dropping anything.
auto boundaries = std::make_shared<SceneBoundaries>();
scene_fn.set_boundaries(boundaries);
kpn::ObjectNode<SceneDetectorFunc, kpn::in<"dense">, kpn::out<>, "scene_detector", 0>
scene_node(scene_fn, 128);
@@ -362,13 +406,34 @@ int main(int argc, char** argv) {
return true;
}
return false;
}, 32);
}, kSceneJoinDepth);
/// TRACES: AR-010 | SR-002
// Stamp is_scene_boundary from the detector's published verdict. tol is
// half a sample interval: the two branches sample at different rates, so
// a boundary found on a dense frame rarely lands exactly on a sampled
// one, and half an interval attributes it to the nearest sampled frame
// and no further.
//
// outran() counts frames that arrived before the detector had scored
// them. Nonzero means the join depth is too shallow for the window, and
// those frames were annotated from an incomplete verdict — which would
// otherwise look exactly like "no boundary here".
SceneBoundaryAnnotatorFunc annotate_fn{boundaries, 0.5 / cfg.sample_fps};
kpn::ObjectNode<SceneBoundaryAnnotatorFunc, kpn::in<"frame">, kpn::out<"frame">,
"scene_annotate", 0> annotate(annotate_fn, kSceneJoinDepth);
// Reported at shutdown: without this the join is unverifiable, and an
// annotator that never fired looks identical to footage with no
// boundaries.
scene_stats = boundaries;
auto net = kpn::make_network(
kpn::edge(source.output<"raw">(), campos.input<"raw">()),
kpn::edge(source.output<"raw">(), scene_node.input<"dense">()),
kpn::edge(campos.output<"frame">(), decimate.input<0>()),
kpn::edge(decimate.output<0>(), detector.input<"frame">()),
kpn::edge(decimate.output<0>(), annotate.input<"frame">()),
kpn::edge(annotate.output<"frame">(), detector.input<"frame">()),
kpn::edge(detector.output<"scene">(), aligner.input<"scene">()),
kpn::edge(aligner.output<"aligned">(), embedder.input<"aligned">()),
kpn::edge(embedder.output<"embedded">(), ftracker.input<"embedded">()),
@@ -0,0 +1,67 @@
#pragma once
/// TRACES: AR-010 | SR-002
///
/// SceneBoundaryAnnotatorFunc — the join of the decode butterfly.
///
/// `source` fans out to two branches: dense frames to TransNetV2, sampled frames
/// to face detection. A boundary found on the first has to reach the second, and
/// cannot ride along in the frame because the branches run in parallel.
///
/// This node sits on the sampled branch and stamps `Frame::is_scene_boundary`
/// from the detector's published verdict.
///
/// **It only works because the sampled branch lags.** TransNetV2 buffers
/// `kWindow` frames before it can score any of them, so this node must not reach
/// a frame before the detector has an opinion about it. Channel depth creates
/// that lag: with backpressure (AR-004) the fanout blocks on the slower branch,
/// so a deep channel here lets the detector run ahead by its window instead of
/// anything being dropped.
///
/// When the lag is insufficient the node **counts it** rather than guessing.
/// Annotating an unscored frame as boundary-free is indistinguishable from a
/// genuine "no boundary here", and that is the failure that makes a downstream
/// test pass while verifying nothing.
#include "scene_boundaries.hpp"
#include "types.hpp"
#include <memory>
#include <string_view>
#include <utility>
struct SceneBoundaryAnnotatorFunc {
static constexpr std::string_view label() { return "scene_annotate"; }
/// `tol` is half a sample interval. The branches sample at different rates,
/// so a boundary found on a dense frame rarely lands exactly on a sampled
/// one; half an interval attributes it to the nearest sampled frame and no
/// further.
SceneBoundaryAnnotatorFunc(std::shared_ptr<SceneBoundaries> b, double tol)
: bounds_(std::move(b)), tol_(tol) {}
Frame operator()(Frame f) {
if (f.eof || !bounds_) return f;
// Wait for the detector's verdict to cover this frame. Channel depth
// alone cannot provide the lag: it holds frames back only when the
// consumer is slower, and this branch is orders of magnitude faster per
// frame than TransNetV2. Blocking here is what makes the join real.
//
// Safe under backpressure because the branches are independent: this
// node stalling does not stop the detector consuming dense frames, and
// the fanout keeps feeding it.
if (!bounds_->wait_until_scored(f.timestamp_sec)) {
// The detector finished without covering this frame — the tail after
// its last full window. Unknown, not negative; counted so it cannot
// pass for "no boundary here".
bounds_->note_outran();
return f;
}
f.is_scene_boundary = bounds_->is_boundary(f.timestamp_sec, tol_);
return f;
}
private:
std::shared_ptr<SceneBoundaries> bounds_;
double tol_{0.0};
};
+35 -2
View File
@@ -1,6 +1,9 @@
#pragma once
#include "types.hpp"
#include "config.hpp"
#include "scene_boundaries.hpp"
#include <memory>
#include "inference/scene_detector.hpp"
#include <nlohmann/json.hpp>
@@ -30,6 +33,11 @@
struct SceneDetectorFunc {
static constexpr std::string_view label() { return "scene_detector"; }
/// TRACES: AR-010 | SR-002
/// Publish each window's verdict as it is scored, so the face branch — held
/// back by channel depth — can consult it for frames it has not reached yet.
void set_boundaries(std::shared_ptr<SceneBoundaries> b) { shared_ = std::move(b); }
SceneDetectorFunc(const Config& cfg, std::atomic<bool>& done)
: detector_(make_scene_detector(cfg))
, threshold_(cfg.scene_threshold)
@@ -51,6 +59,9 @@ struct SceneDetectorFunc {
void operator()(Frame f) {
if (f.eof) {
flush_remaining();
// Release anyone waiting on the join: the tail frames after the last
// full window will never be covered, so waiting for them would hang.
if (shared_) shared_->finish();
write_output();
done_.store(true, std::memory_order_release);
return;
@@ -82,6 +93,7 @@ private:
// otherwise skip the leading guard already covered by the previous window.
const int lo = (window_base_ == 0) ? 0 : guard_;
const int hi = ISceneDetector::kWindow - guard_;
std::vector<double> fresh;
for (int i = lo; i < hi; ++i) {
if (probs[i] <= threshold_) continue;
// Local maximum → the boundary frame (avoid a run of high scores
@@ -89,9 +101,19 @@ private:
const bool peak =
(i == 0 || probs[i] >= probs[i-1]) &&
(i == kLast_() || probs[i] >= probs[i+1]);
if (peak)
if (peak) {
boundaries_.push_back({times_[i], probs[i]});
fresh.push_back(times_[i]);
}
}
/// TRACES: AR-010 | SR-002
// Publish with a watermark: everything up to times_[hi-1] now has a
// final verdict. The face branch consults this for frames it has not
// reached yet, and the watermark is what lets it tell "no boundary
// here" from "not scored yet".
if (shared_ && hi > lo)
shared_->publish(fresh, times_[hi - 1]);
}
// At EOF the tail (< kWindow frames) never formed a full window. Pad it out
@@ -107,14 +129,24 @@ private:
std::vector<float> probs = detector_->detect_window(win);
const int lo = (window_base_ == 0) ? 0 : guard_;
std::vector<double> fresh;
for (int i = lo; i < n; ++i) { // only real (non-padded) frames
if (probs[i] <= threshold_) continue;
const bool peak =
(i == 0 || probs[i] >= probs[i-1]) &&
(i == n - 1 || probs[i] >= probs[i+1]);
if (peak)
if (peak) {
boundaries_.push_back({times_[i], probs[i]});
fresh.push_back(times_[i]);
}
}
/// TRACES: AR-010 | SR-002
// Publish the tail too. Without this the final frames — everything after
// the last full window — reach the join with no verdict and are treated
// as boundary-free without evidence, which is precisely the ambiguity
// the watermark exists to prevent.
if (shared_ && n > 0) shared_->publish(fresh, times_[n - 1]);
}
void write_output() {
@@ -176,4 +208,5 @@ private:
int64_t window_base_{0}; // frame index of images_.front()
std::vector<Boundary> boundaries_;
bool written_{false};
std::shared_ptr<SceneBoundaries> shared_; ///< AR-010 join point
};
+126
View File
@@ -0,0 +1,126 @@
#pragma once
/// TRACES: AR-010 | SR-002
///
/// SceneBoundaries — the join point of the decode butterfly.
///
/// The topology forks after decode: one branch runs TransNetV2 over dense
/// frames, the other runs face detection over the sampled cadence. Boundaries
/// found on the first branch have to reach the second, and they cannot be
/// carried in the frames themselves because the branches are parallel.
///
/// **Why this needs a watermark.** TransNetV2 buffers `kWindow` frames before it
/// can score any of them, so at any instant the detector has an opinion about
/// everything up to some time T and nothing after it. Without recording T, a
/// consumer asking "is there a boundary at t?" cannot distinguish *no* from
/// *not yet* — and those demand opposite behaviour. Silently treating unscored
/// frames as boundary-free is exactly the class of failure that makes a
/// verification pass vacuously.
///
/// The consumer is held back by channel depth (see main.cpp) so that by the time
/// it pulls a frame, the detector has already scored past it. `scored_through()`
/// is what lets that assumption be *checked* rather than assumed.
#include <algorithm>
#include <condition_variable>
#include <mutex>
#include <vector>
class SceneBoundaries {
public:
/// Peaks closer than this are one boundary. Matches the dedup scenes.json
/// applies, so the two views agree.
static constexpr double kMergeSec = 0.04;
/// Called by the scene detector as each window is scored. `through` is the
/// timestamp up to which its verdict is now final.
void publish(const std::vector<double>& ts, double through) {
{
std::lock_guard<std::mutex> g(mu_);
// Dedup on insert, matching what scenes.json does at write time. A run
// of adjacent high-scoring frames is one boundary, not several, and
// leaving them raw made this view report 357 where the file said 13 —
// the same event counted many times. Harmless for is_boundary(), which
// absorbs them in its tolerance, but a count nobody can reconcile with
// the output file is a bad diagnostic.
bounds_.insert(bounds_.end(), ts.begin(), ts.end());
std::sort(bounds_.begin(), bounds_.end());
bounds_.erase(std::unique(bounds_.begin(), bounds_.end(),
[](double a, double b) { return b - a < kMergeSec; }),
bounds_.end());
scored_through_ = std::max(scored_through_, through);
}
cv_.notify_all();
}
/// True if a boundary falls within `tol` of `t`.
///
/// `tol` exists because the two branches sample at different rates: a
/// boundary found on a dense frame rarely lands exactly on a sampled one.
/// Half a sample interval is the natural width — it attributes the boundary
/// to the nearest sampled frame and no further.
bool is_boundary(double t, double tol) const {
std::lock_guard<std::mutex> g(mu_);
auto it = std::lower_bound(bounds_.begin(), bounds_.end(), t - tol);
return it != bounds_.end() && *it <= t + tol;
}
/// The timestamp through which the detector's verdict is final. A consumer
/// past this point is asking about frames nobody has looked at yet.
double scored_through() const {
std::lock_guard<std::mutex> g(mu_);
return scored_through_;
}
/// Block until the detector's verdict covers `t`, or it finishes.
///
/// Channel depth alone does NOT create the required lag: it only holds
/// frames back when the consumer is slower, and the face branch is roughly
/// four orders of magnitude faster per frame than TransNetV2. So the join
/// has to wait explicitly.
///
/// Returns false if the detector finished without ever covering `t`, which
/// happens for the tail frames after its last full window. The caller must
/// distinguish that from a genuine "no boundary" rather than assuming.
bool wait_until_scored(double t) const {
std::unique_lock<std::mutex> lk(mu_);
cv_.wait(lk, [&] { return finished_ || scored_through_ >= t; });
return scored_through_ >= t;
}
/// Called when the detector will publish nothing further. Without this the
/// join would deadlock on the tail: those frames are never covered by a full
/// window, so waiting for them would wait forever.
void finish() {
{
std::lock_guard<std::mutex> g(mu_);
finished_ = true;
}
cv_.notify_all();
}
std::size_t count() const {
std::lock_guard<std::mutex> g(mu_);
return bounds_.size();
}
/// Consumers that outran the detector. Nonzero means the face branch is not
/// buffered deeply enough for the detector's window, so some frames were
/// annotated from an incomplete verdict — a real misconfiguration, and one
/// that would otherwise be invisible.
void note_outran() const {
std::lock_guard<std::mutex> g(mu_);
++outran_;
}
std::size_t outran() const {
std::lock_guard<std::mutex> g(mu_);
return outran_;
}
private:
mutable std::mutex mu_;
mutable std::condition_variable cv_;
bool finished_{false};
std::vector<double> bounds_;
double scored_through_{-1.0};
mutable std::size_t outran_{0};
};