Watchline

How a second
becomes a number

Follow playback evidence from the browser to a verified total. Explore the flowcharts, or try the watch-time calculation below.

How the engine is built.

One Next.js application wraps a framework-free TypeScript engine and a local SQLite store. The browser supplies intervals, the server decides what counts, and the database keeps both the evidence and the derived answer. Playback and access control stay outside the engine; no video is uploaded.

Framework-free engine

engine/

TypeScript modules own segment state, validation policy, range arithmetic, projection updates and reconciliation. They do not import Next.js or a database driver.

watch-math.ts · sanitize.ts · projection.ts · reconcile.ts

Storage and delivery

server/

Node's built-in SQLite driver stores evidence, sessions, request claims, projections and outbox rows. Repository functions own the SQL; broker adapters share one interface.

db.ts · schema.ts · repository.ts · broker.ts

HTTP boundary

app/api/analytics/

Zod validates requests, server-owned session context is resolved, and the engine runs through the repository. Session, heartbeat, read and admin routes stay separate.

session/route.ts · heartbeat/route.ts · read/route.ts · admin/route.ts

The full request, relay and read paths are in the system diagram under the message layer.

Four guarantees.

The client is untrusted.

The server validates playback ranges and computes the metrics itself.

Proof computeWatchMetrics(ranges, duration)

Delivery is at-least-once.

Request keys and segment identities stop retries from counting twice.

Proof UNIQUE(idempotency_key)

Reads are projections.

Stored totals can be rebuilt from the append-only evidence log.

Proof drop → rebuild → compare

Drift is repairable.

Audit the difference, repair affected subjects, then verify the result.

Proof audit → repair → verify

Count each second once.

Watch the same part twice: total watch time increases, but unique watch time stays the same.

How overlaps are counted

Adding lengths

// adding lengths counts a rewatch twice
progress.uniqueContentSeconds +=
  segment.endSecond - segment.startSecond;

Correct for the first range. Wrong as soon as two ranges overlap.

Merging ranges

const merged = mergeRanges([
  ...progress.watchedRanges,
  newRange,
]);
progress.uniqueContentSeconds =
  sumRanges(merged);

Every accepted range passes through the same function. Shared seconds are counted once.

See how watch time adds up

Toggle ranges from a 40-second watch.

Unique watched31s2 watched ranges
0s10s20s30s40s
Total watched
41s
Unique watched
31s
Rewatch
10s
Completion
77.5%
Overlapping seconds count once. Pauses are excluded.

Retries shouldn’t count twice.

One key protects the request. Another protects each playback segment.

Loading architecture diagram…

Request keys catch repeated batches. Segment identities catch the same evidence, even in a new session.
View Mermaid source
sequenceDiagram
  participant C as Client
  participant A as API
  participant D as Store

  Note over C: 300 segments queued<br/>while offline for 1 hour
  C->>A: POST heartbeat (Idempotency-Key K1)
  A->>D: CLAIM K1
  D-->>A: claimed
  A->>D: BEGIN IMMEDIATE
  A->>D: INSERT segments ON CONFLICT DO NOTHING
  Note over D: unique index on<br/>(student, scope, client_segment_id)<br/>scope is session-independent
  D-->>A: accepted=280 duplicate=20
  A->>D: COMMIT
  A-->>C: acceptedSegmentIds, duplicateSegmentIds

  Note over C: session ended while offline.<br/>Replay arrives under a NEW session id.
  C->>A: POST heartbeat (Idempotency-Key K2, new session)
  A->>D: CLAIM K2
  D-->>A: claimed (K2 is new)
  A->>D: INSERT same 300 segments
  D-->>A: duplicate=280 accepted=0
  Note over D: segment identity collapses the replay<br/>even though the request key differs
  A-->>C: duplicateSegmentIds = all 280

Evidence, totals, and the outbox commit together. The broker delivers events separately; a unique index prevents double-counting.

Replay details

Request key

A repeated key returns the original acknowledgement instead of applying the batch again.

UNIQUE(idempotency_key)

Evidence key

The scope is session-independent, so the same evidence cannot count twice under a new session id.

UNIQUE(student, scope, client_segment_id)
How the browser closes a segment

A segment opens while playback is running and closes on pause, seek, buffering, rate change, tab hide, end, rewind, or at 110 seconds of content.

Loading architecture diagram…

The tracker is player-agnostic: ten standard media events are the whole adapter surface. No SDK, iframe or provider data is involved.
View Mermaid source
stateDiagram-v2
  [*] --> IDLE
  IDLE --> PLAY_REQUESTED : play
  PLAY_REQUESTED --> PLAYING : playing
  PLAYING --> PAUSED : pause
  PLAYING --> SEEKING : seeking
  SEEKING --> PLAY_REQUESTED : seeked
  SEEKING --> PAUSED : seeked while paused
  PLAYING --> BUFFERING : waiting or stalled
  BUFFERING --> PLAY_REQUESTED : playing
  PLAYING --> SUSPENDED : tab hidden
  SUSPENDED --> PLAY_REQUESTED : tab visible
  PLAYING --> ENDED : ended
  PAUSED --> PLAY_REQUESTED : play
  ENDED --> [*]

  note right of PLAYING
    A segment is open.
    It closes on pause, seek,
    buffering, rate change,
    tab hide, end, rewind,
    or at 110 seconds of content.
  end note

Count first. Deliver separately.

Accepted events leave through a transactional outbox. Use Kafka or the in-memory broker; watch time is credited before either runs.

Loading architecture diagram…

The full path from playback to stored totals. Subject-detail reads also compare the projection with raw evidence.
View Mermaid source
flowchart LR
  V["Local video file<br/>never uploaded"] --> SM["Segment machine<br/>10 player events"]
  SM --> OB["Durable outbox<br/>IndexedDB + mirror"]
  OB -->|"POST heartbeat + Idempotency-Key"| API["API<br/>parse, sanitize, BEGIN IMMEDIATE"]
  API -->|"evidence"| SEG["watch_segments<br/>append-only evidence"]
  API -->|"upsert"| PROJ["subject_progress<br/>materialized projection"]
  API -->|"same transaction"| OUT["outbox row<br/>transactional hand-off"]
  SEG -.->|"full recompute<br/>audit and repair"| PROJ
  OUT -->|"relay"| TOPIC["topic video.segments<br/>partitioned by subject scope"]
  TOPIC --> GROUP["consumer group<br/>va-projector"]
  GROUP -->|"upsert"| PROJ
  PROJ -->|"GET read"| UI["Analytics surface"]
Message layer details
Durable outbox
Written in the same commit as evidence, so a crash cannot lose the intent to publish.
Relay
Publishes unpublished rows, then marks them. A crash between the two publishes twice — never not at all.
Topic
video.segments, partitioned by subject scope so one subject's updates stay ordered.
va-projector
Consumer group with idempotent projection apply. Each partition is assigned to one member.
Lag and dead letters
Committed offset vs. end offset per partition; a poison record moves aside instead of stalling the queue.
Kafka is optional
KAFKA_BROKERS selects KafkaBroker; otherwise MemoryBroker provides the same semantics in process. Both share one contract.

Check the totals. Repair the difference.

Compare stored totals with raw evidence. Fix only what disagrees.

Loading architecture diagram…

Audit → preview changes → repair → verify. A successful repair leaves no difference.
View Mermaid source
flowchart LR
  SEG["watch_segments<br/>append-only evidence<br/>never updated, never deleted"]
  PROJ["subject_progress<br/>mutable projection<br/>rebuildable from the log"]

  SEG -->|"incremental<br/>on every heartbeat"| PROJ
  SEG -->|"full recompute<br/>repair and rebuild"| PROJ

  CMP{"Compare the<br/>two paths"}
  PROJ --> CMP
  RECOMPUTE["recompute from<br/>raw evidence"] --> CMP
  CMP -->|"delta = 0"| OK["Projection is correct"]
  CMP -->|"delta != 0"| DRIFT["Drift detected"]
  DRIFT --> AUDIT["Audit - read only,<br/>safe to run on a schedule"]
  AUDIT --> DRY["Dry run - show what<br/>would change"]
  DRY --> APPLY["Bounded apply<br/>keyset paged, per-subject savepoint"]
  APPLY --> VERIFY["Verify - re-audit,<br/>delta must now be 0"]
  VERIFY --> OK

Audit is read-only. Apply is separate, keyset-paged per subject, and resumable by cursor.

Paging and savepoints

A repair walks subjects in keyset order and holds at most one page of locks. Each subject is repaired in its own savepoint, so a bad row is reported and skipped instead of aborting the batch.

When things go wrong.

See how Watchline handles retries, rewatches, and incorrect totals.

Failure matrixSix failures, each caught by a specific guard.
FailureWatchline
Client claims 60s but spends 6sRecomputes 6s from ranges
Same batch retried twiceRequest key returns the original
Outbox replays under a new session idSegment key rejects the evidence
Learner rewinds and rewatchesUnion stays unchanged, repeat grows
Projection loses a rowAudit finds the delta, repair verifies
Outbox relay falls behindProjection stays rebuildable and observable
Every row above is covered by the engine's test suite.Read the tests

The API, at a glance.

Write evidence, read progress, or repair totals.

POST /api/analytics/heartbeat

The hot path. Segments are evidence; the server returns a per-segment verdict and its own summary.

Request
const res = await fetch("/api/analytics/heartbeat", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Idempotency-Key": crypto.randomUUID(),
  },
  body: JSON.stringify({
    sessionId,
    currentTimeSeconds: 134.56,
    eventType: "heartbeat",
    segments: [{
      startSecond: 12.34,
      endSecond: 78.90,
      playbackRate: 1.0,
      clientSegmentId: "0f9c...",
      wallClockSeconds: 66.56,
      segmentStartedAt: "2026-10-22T09:12:03.114Z",
      segmentEndedAt: "2026-10-22T09:13:09.674Z",
    }],
    counts: { play: 1, pause: 0, seek: 0, ratechange: 0 },
  }),
});
Response
{
  "ok": true,
  "segmentsReceived": 3,
  "acceptedSegmentIds": ["a", "b"],
  "duplicateSegmentIds": ["c"],
  "rejectedSegments": [],
  "summary": {
    "videoDurationSeconds": 600,
    "totalWatchedSeconds": 300,
    "uniqueWatchedSeconds": 280,
    "repeatWatchedSeconds": 20,
    "completionPercentage": 46.67
  }
}
At-least-once delivery · two independent idempotency guardsPer-segment verdicts, not a single ok
What the API does not do
Auth is a layer above

Access control answers who may watch. The engine answers what was watched.

The broker is not a judge

It schedules projection updates. A unique index decides what counts.

No player coupling

No SDK, no iframe, no media fetch. A purity guard fails the test suite if coupling appears.

Explore the implementation.

The engine, APIs, and design decisions are in the repository.