From b9bd2daa342f62f8e1f07ef2c6720c2782aaa832 Mon Sep 17 00:00:00 2001 From: asher-aqi Date: Thu, 12 Nov 2026 00:53:40 -0600 Subject: [PATCH 1/4] test(clock): specify continuous event quiet durations Pin distinct continuous durations, latest-end aggregation, unchanged defaults and atomic admission before implementing the extension. --- python/src/aqi_attend/core/types.py | 1 + python/tests/test_continuous_quiet.py | 123 ++++++++++++++++++++++++++ src/core/types.ts | 2 + test/continuous-quiet.test.ts | 100 +++++++++++++++++++++ 4 files changed, 226 insertions(+) create mode 100644 python/tests/test_continuous_quiet.py create mode 100644 test/continuous-quiet.test.ts diff --git a/python/src/aqi_attend/core/types.py b/python/src/aqi_attend/core/types.py index 0f03a6d..575ebe5 100644 --- a/python/src/aqi_attend/core/types.py +++ b/python/src/aqi_attend/core/types.py @@ -31,6 +31,7 @@ class Event(TypedDict): id: str at: float observedAt: NotRequired[float] + quietForMs: NotRequired[float] name: str data: JsonObject text: NotRequired[str] diff --git a/python/tests/test_continuous_quiet.py b/python/tests/test_continuous_quiet.py new file mode 100644 index 0000000..5857b7f --- /dev/null +++ b/python/tests/test_continuous_quiet.py @@ -0,0 +1,123 @@ +"""Continuous events can carry distinct quiet durations within one window.""" + +import asyncio + +import pytest + +from aqi_attend import create_attend +from aqi_attend.core.types import Buffer, Entry, Kind, default_policy +from aqi_attend.core.window import deadline +from aqi_attend.testing import fake_clock, recording_sink, scripted_judge + + +def entry(id: str, seen_at: float, *, observed_at: float | None = None, quiet: float | None = None, kind: Kind = "continuous") -> Entry: + result: Entry = {"id": id, "at": -1, "name": "move", "data": {}, "kind": kind, "seenAt": seen_at} + if observed_at is not None: + result["observedAt"] = observed_at + if quiet is not None: + result["quietForMs"] = quiet + return result + + +def buffer(*entries: Entry) -> Buffer: + return {"entries": list(entries), "dropped": 0, "gap": False, "forcedAt": None} + + +@pytest.mark.parametrize(("first", "second", "due"), [(40, 90, 210), (90, 40, 190)]) +async def test_continuous_durations_wait_for_latest_end(first: float, second: float, due: float) -> None: + clock = fake_clock(100) + judge = scripted_judge([{"route": "queue"}]) + sink = recording_sink() + attend = create_attend(clock=clock, kind={"move": "continuous"}, judge=judge, sink=sink) + running = asyncio.create_task(attend.run()) + try: + await attend.push("s", {"id": "a", "name": "move", "quietForMs": first}) + await clock.advance(20) + await attend.push("s", {"id": "b", "name": "move", "quietForMs": second}) + record = await attend.inspect("s") + assert record is not None and record["dueAt"] == due + await clock.advance(due - 121) + assert len(judge.calls) == 0 + await clock.advance(1) + assert [call["window"]["settledAt"] for call in judge.calls] == [due] + assert [(event["id"], event.get("quietForMs"), event["seenAt"]) for event in sink.delivered[0]["window"]["events"]] == [("a", first, 100), ("b", second, 120)] + finally: + await attend.stop() + await running + await attend.store.close() + + +def test_mixed_and_out_of_order_durations_take_maximum_event_end() -> None: + policy = default_policy() + policy["streamGapMs"] = 30 + assert deadline(policy, buffer(entry("a", 200, observed_at=100, quiet=90), entry("b", 200, observed_at=140, quiet=20))) == (190, "stream_quiet") + assert deadline(policy, buffer(entry("a", 200, observed_at=140, quiet=20), entry("b", 200, observed_at=100, quiet=90))) == (190, "stream_quiet") + assert deadline(policy, buffer(entry("a", 100), entry("b", 120, quiet=90))) == (210, "stream_quiet") + assert deadline(policy, buffer(entry("a", 100, quiet=90), entry("b", 180))) == (210, "stream_quiet") + + +def test_absent_durations_keep_backward_clock_behavior_and_explicit_ones_include_prior_entries() -> None: + policy = default_policy() + policy["streamGapMs"] = 30 + assert deadline(policy, buffer(entry("a", 200), entry("b", 100))) == (130, "stream_quiet") + assert deadline(policy, buffer(entry("a", 200), entry("b", 100), entry("c", 50, quiet=0))) == (230, "stream_quiet") + assert deadline(policy, buffer(entry("a", 200, observed_at=120), entry("b", 200, observed_at=100))) == (150, "stream_quiet") + + +def test_other_triggers_remain_independent() -> None: + move = entry("a", 100, quiet=90) + policy = default_policy() + policy["passiveQuietMs"] = 15 + policy["closingGraceMs"] = 10 + assert deadline(policy, buffer(move, entry("b", 105, kind="passive"))) == (120, "passive_quiet") + assert deadline(policy, buffer(move, entry("b", 110, kind="closing"))) == (120, "closing") + assert deadline(policy, buffer(move, entry("b", 115, kind="flush"))) == (115, "flush") + policy["maxWindowMs"] = 50 + assert deadline(policy, buffer(move)) == (150, "age") + policy["maxEvents"] = 0 + assert deadline(policy, buffer(move)) == (100, "overflow") + + +@pytest.mark.parametrize( + "quiet", + [None, True, "10", float("nan"), float("inf"), -float("inf"), -1, 10**1000], + ids=["null", "boolean", "string", "nan", "positive-infinity", "negative-infinity", "negative", "outside-number-range"], +) +async def test_invalid_duration_refuses_whole_batch(quiet: object) -> None: + attend = create_attend(clock=fake_clock(100), kind={"move": "continuous"}, judge=scripted_judge([{"route": "queue"}]), sink="log") + try: + with pytest.raises(TypeError, match="quietForMs"): + await attend.push("s", [{"id": "a", "name": "move"}, {"id": "b", "name": "move", "quietForMs": quiet}]) + assert await attend.inspect("s") is None + finally: + await attend.stop() + await attend.store.close() + + +@pytest.mark.parametrize("kind", ["closing", "passive", "flush", "consequence", "context"]) +async def test_duration_on_other_kind_refuses_whole_batch(kind: Kind) -> None: + attend = create_attend(clock=fake_clock(100), kind=lambda event: "continuous" if event["name"] == "move" else kind, judge=scripted_judge([{"route": "queue"}]), sink="log") + try: + with pytest.raises(TypeError, match="quietForMs"): + await attend.push("s", [{"id": "a", "name": "move"}, {"id": "b", "name": "other", "quietForMs": 0}]) + assert await attend.inspect("s") is None + finally: + await attend.stop() + await attend.store.close() + + +async def test_zero_duration_and_late_observation_settle_at_processing_time() -> None: + clock = fake_clock(100) + judge = scripted_judge([{"route": "queue"}]) + attend = create_attend(clock=clock, kind={"move": "continuous"}, judge=judge, sink="log") + running = asyncio.create_task(attend.run()) + try: + await attend.push("s", {"id": "a", "name": "move", "observedAt": 10, "quietForMs": 0}) + await clock.advance(0) + assert [call["window"]["settledAt"] for call in judge.calls] == [100] + event = judge.calls[0]["window"]["events"][0] + assert (event["at"], event.get("observedAt"), event["seenAt"], event.get("quietForMs")) == (100, 10, 100, 0) + finally: + await attend.stop() + await running + await attend.store.close() diff --git a/src/core/types.ts b/src/core/types.ts index 778fff5..1c7940a 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -14,6 +14,8 @@ export interface Event { at: number; /** Source observation time in the engine clock's coordinates. Omit to settle from ingestion. */ observedAt?: number; + /** Quiet duration for a continuous event, in ms. Omit to use streamGapMs. */ + quietForMs?: number; name: string; data: JsonObject; /** One plain line describing the event. The judge never writes text; notices are built from these. */ diff --git a/test/continuous-quiet.test.ts b/test/continuous-quiet.test.ts new file mode 100644 index 0000000..9b2b749 --- /dev/null +++ b/test/continuous-quiet.test.ts @@ -0,0 +1,100 @@ +import { expect, test } from 'vitest'; +import { createAttend, DEFAULT_POLICY, KINDS } from '../src/index.js'; +import type { Buffer, Entry } from '../src/types.js'; +import { deadline } from '../src/core/window.js'; +import { fakeClock, recordingSink, scriptedJudge } from '../src/testing.js'; + +function entry(id: string, seenAt: number, extra: Partial = {}): Entry { + return { id, at: -1, name: 'move', data: {}, kind: 'continuous', seenAt, ...extra }; +} + +function buffer(...entries: Entry[]): Buffer { + return { entries, dropped: 0, gap: false, forcedAt: null }; +} + +test.each([ + { first: 40, second: 90, due: 210 }, + { first: 90, second: 40, due: 190 }, +])('continuous durations $first then $second wait for their latest end', async ({ first, second, due }) => { + const clock = fakeClock(100); + const judge = scriptedJudge([{ route: 'queue' }]); + const sink = recordingSink(); + const attend = createAttend({ clock, kind: { move: 'continuous' }, judge, sink }); + const running = attend.run(); + try { + await attend.push('s', { id: 'a', name: 'move', quietForMs: first }); + await clock.advance(20); + await attend.push('s', { id: 'b', name: 'move', quietForMs: second }); + expect((await attend.inspect('s'))?.dueAt).toBe(due); + await clock.advance(due - 121); + expect(judge.calls).toHaveLength(0); + await clock.advance(1); + expect(judge.calls.map((call) => call.window.settledAt)).toEqual([due]); + expect(sink.delivered[0]?.window.events.map((e) => [e.id, e.quietForMs, e.seenAt])).toEqual([['a', first, 100], ['b', second, 120]]); + } finally { + await attend.stop(); + await running; + } +}); + +test('mixed and out-of-order durations take the maximum event end', () => { + const policy = { ...DEFAULT_POLICY, streamGapMs: 30 }; + expect(deadline(policy, buffer(entry('a', 200, { observedAt: 100, quietForMs: 90 }), entry('b', 200, { observedAt: 140, quietForMs: 20 })))).toEqual({ at: 190, reason: 'stream_quiet' }); + expect(deadline(policy, buffer(entry('a', 200, { observedAt: 140, quietForMs: 20 }), entry('b', 200, { observedAt: 100, quietForMs: 90 })))).toEqual({ at: 190, reason: 'stream_quiet' }); + expect(deadline(policy, buffer(entry('a', 100), entry('b', 120, { quietForMs: 90 })))).toEqual({ at: 210, reason: 'stream_quiet' }); + expect(deadline(policy, buffer(entry('a', 100, { quietForMs: 90 }), entry('b', 180)))).toEqual({ at: 210, reason: 'stream_quiet' }); +}); + +test('absent durations retain backwards clocks and explicit durations include earlier default entries', () => { + const policy = { ...DEFAULT_POLICY, streamGapMs: 30 }; + expect(deadline(policy, buffer(entry('a', 200), entry('b', 100)))).toEqual({ at: 130, reason: 'stream_quiet' }); + expect(deadline(policy, buffer(entry('a', 200), entry('b', 100), entry('c', 50, { quietForMs: 0 })))).toEqual({ at: 230, reason: 'stream_quiet' }); + expect(deadline(policy, buffer(entry('a', 200, { observedAt: 120 }), entry('b', 200, { observedAt: 100 })))).toEqual({ at: 150, reason: 'stream_quiet' }); +}); + +test('other triggers remain independent of continuous durations', () => { + const move = entry('a', 100, { quietForMs: 90 }); + expect(deadline({ ...DEFAULT_POLICY, passiveQuietMs: 15 }, buffer(move, entry('b', 105, { kind: 'passive' })))).toEqual({ at: 120, reason: 'passive_quiet' }); + expect(deadline({ ...DEFAULT_POLICY, closingGraceMs: 10 }, buffer(move, entry('b', 110, { kind: 'closing' })))).toEqual({ at: 120, reason: 'closing' }); + expect(deadline(DEFAULT_POLICY, buffer(move, entry('b', 115, { kind: 'flush' })))).toEqual({ at: 115, reason: 'flush' }); + expect(deadline({ ...DEFAULT_POLICY, maxWindowMs: 50 }, buffer(move))).toEqual({ at: 150, reason: 'age' }); + expect(deadline({ ...DEFAULT_POLICY, maxEvents: 0 }, buffer(move))).toEqual({ at: 100, reason: 'overflow' }); +}); + +test.each([null, true, '10', NaN, Infinity, -Infinity, -1])('invalid duration %s refuses the whole batch', async (quietForMs) => { + const attend = createAttend({ clock: fakeClock(100), kind: { move: 'continuous' }, judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); + try { + // Decoded JavaScript input can violate the declared public type. + // @ts-expect-error invalid input is the boundary under test + await expect(attend.push('s', [{ id: 'a', name: 'move' }, { id: 'b', name: 'move', quietForMs }])).rejects.toThrow('quietForMs'); + expect(await attend.inspect('s')).toBeNull(); + } finally { + await attend.stop(); + } +}); + +test.each(KINDS.filter((kind) => kind !== 'continuous'))('duration on %s refuses the whole batch', async (kind) => { + const attend = createAttend({ clock: fakeClock(100), kind: (event) => event.name === 'move' ? 'continuous' : kind, judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); + try { + await expect(attend.push('s', [{ id: 'a', name: 'move' }, { id: 'b', name: 'other', quietForMs: 0 }])).rejects.toThrow('quietForMs'); + expect(await attend.inspect('s')).toBeNull(); + } finally { + await attend.stop(); + } +}); + +test('zero duration is immediate and late observations settle at processing time', async () => { + const clock = fakeClock(100); + const judge = scriptedJudge([{ route: 'queue' }]); + const attend = createAttend({ clock, kind: { move: 'continuous' }, judge, sink: 'log' }); + const running = attend.run(); + try { + await attend.push('s', { id: 'a', name: 'move', observedAt: 10, quietForMs: 0 }); + await clock.advance(0); + expect(judge.calls.map((call) => call.window.settledAt)).toEqual([100]); + expect(judge.calls[0]?.window.events[0]).toMatchObject({ at: 100, observedAt: 10, seenAt: 100, quietForMs: 0 }); + } finally { + await attend.stop(); + await running; + } +}); From 9573013175ba23a69ac18f237f965815bae14223 Mon Sep 17 00:00:00 2001 From: asher-aqi Date: Thu, 12 Nov 2026 01:05:33 -0600 Subject: [PATCH 2/4] feat(clock): retain continuous event quiet durations Combine distinct continuous quiet durations by their latest end time while retaining independent triggers, processing clocks and default behavior. Persist explicit durations and rebuild summaries through replay and policy changes. --- DEVIATIONS.md | 8 +- conformance/fixtures/scenarios.json | 2748 +++++++++++++++++++++++++ docs/reference.md | 27 + docs/storage.md | 2 +- python/README.md | 1 + python/src/aqi_attend/attend.py | 2 + python/src/aqi_attend/conformance.py | 3 +- python/src/aqi_attend/core/reducer.py | 2 +- python/src/aqi_attend/core/types.py | 4 +- python/src/aqi_attend/core/window.py | 10 +- python/src/aqi_attend/shell/copy.py | 4 + python/tests/scenario.py | 1 + python/tests/test_continuous_quiet.py | 143 +- python/tests/test_observation_time.py | 5 +- src/attend.ts | 1 + src/core/reducer.ts | 2 +- src/core/types.ts | 3 + src/core/window.ts | 7 +- src/internal/shared.ts | 6 + src/testing.ts | 2 +- src/testing/conformance.ts | 2 +- test/conformance/scenario.ts | 3 +- test/conformance/scenarios.ts | 51 + test/continuous-quiet.test.ts | 101 +- test/core-inputs.test.ts | 2 +- test/observation-time.test.ts | 5 +- test/recovery.test.ts | 2 +- 27 files changed, 3124 insertions(+), 23 deletions(-) diff --git a/DEVIATIONS.md b/DEVIATIONS.md index 9087498..9dda78e 100644 --- a/DEVIATIONS.md +++ b/DEVIATIONS.md @@ -1,10 +1,16 @@ # Shell changes from the frozen shell +## Continuous quiet duration + +An optional `Event.quietForMs` gives a continuous event its own quiet duration. Once any continuous entry supplies it, the continuous deadline is the latest of the entries' individual end times. Entries without a duration use the policy's `streamGapMs`. Other kinds keep their independent triggers. With no explicit duration, the frozen default behavior remains unchanged, including backwards clocks. + +The reducer revision is 3. Explicit durations persist in entries and logged inputs; summaries rebuild from them. Tail replay uses the snapshot policy for omitted durations. A live policy change recomputes those defaults under the new policy, as before. Processes sharing a store must use the same revision before opting in. Shared fixtures and runtime tests cover the extension; the frozen differential cases omit it. [The reference](docs/reference.md#continuous-quiet-duration) defines admission and timing. + ## Observation time An explicit `Event.observedAt` supplies quiet and age timing independently of ingestion. The frozen reducer has no observation-time input. Its differential cases omit that field and continue to pin the existing behavior, including backwards engine clocks. Shared runtime fixtures and dedicated tests cover explicit observation times, mixed timestamps, pruning, admission and recovery in both runtimes. -The reducer revision is 2. Snapshots and logged tails without the field retain ingestion timing. The existing upgrade path replays and resnapshots; it is not a downgrade fence. Processes sharing a store must use the same reducer version before opting in. [The reference](docs/reference.md#observation-time) defines the clocks. +Observation time was introduced in reducer revision 2. Snapshots and logged tails without the field retain ingestion timing. The existing upgrade path replays and resnapshots; it is not a downgrade fence. Processes sharing a store must use the same reducer version before opting in. [The reference](docs/reference.md#observation-time) defines the clocks. ## Commit boundaries diff --git a/conformance/fixtures/scenarios.json b/conformance/fixtures/scenarios.json index 466b7d0..6c14eb2 100644 --- a/conformance/fixtures/scenarios.json +++ b/conformance/fixtures/scenarios.json @@ -1,5 +1,2753 @@ { "scenarios": [ + { + "scenario": { + "name": "different continuous durations settle after the latest event end", + "start": 100, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "judge": { + "*": { + "answers": [ + { + "route": "queue" + } + ] + } + }, + "steps": [ + { + "push": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "quietForMs": 40 + } + ] + }, + { + "advance": 20 + }, + { + "push": "s", + "events": [ + { + "id": "b", + "name": "drag", + "text": "drag b", + "quietForMs": 90 + } + ] + }, + { + "inspect": "s" + }, + { + "advance": 89 + }, + { + "inspect": "s" + }, + { + "advance": 1 + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "f9df8ba2df127ca6", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 40, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "quietForMs": 90, + "kind": "continuous", + "seenAt": 120 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 210 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 210 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "f9df8ba2df127ca6", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "f9df8ba2df127ca6", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 40, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "quietForMs": 90, + "kind": "continuous", + "seenAt": 120 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 210 + }, + "at": 210 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "reason": "stream_quiet", + "count": 2, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "attempt": 1, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "route": "queue" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "f9df8ba2df127ca6", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "f9df8ba2df127ca6" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + }, + { + "step": 2, + "error": null + } + ], + "inspections": [ + { + "step": 3, + "scope": "s", + "record": { + "version": 2, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 40, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "quietForMs": 90, + "kind": "continuous", + "seenAt": 120 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 210 + } + }, + { + "step": 5, + "scope": "s", + "record": { + "version": 2, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 40, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "quietForMs": 90, + "kind": "continuous", + "seenAt": 120 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 210 + } + } + ], + "records": { + "s": { + "version": 5, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "f9df8ba2df127ca6", + "route": "queue", + "at": 210 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "f9df8ba2df127ca6", + "scope": "s", + "at": 210, + "route": "queue", + "body": { + "id": "f9df8ba2df127ca6", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "f9df8ba2df127ca6", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 40, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "quietForMs": 90, + "kind": "continuous", + "seenAt": 120 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 210 + }, + "at": 210 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "a later short duration does not replace an earlier long end", + "start": 100, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "judge": { + "*": { + "answers": [ + { + "route": "queue" + } + ] + } + }, + "steps": [ + { + "push": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "quietForMs": 90 + } + ] + }, + { + "advance": 20 + }, + { + "push": "s", + "events": [ + { + "id": "b", + "name": "drag", + "text": "drag b", + "quietForMs": 40 + } + ] + }, + { + "inspect": "s" + }, + { + "advance": 69 + }, + { + "inspect": "s" + }, + { + "advance": 1 + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "f9df8ba2df127ca6", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 90, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "quietForMs": 40, + "kind": "continuous", + "seenAt": 120 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 190 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 190 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "f9df8ba2df127ca6", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "f9df8ba2df127ca6", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 90, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "quietForMs": 40, + "kind": "continuous", + "seenAt": 120 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 190 + }, + "at": 190 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "reason": "stream_quiet", + "count": 2, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "attempt": 1, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "route": "queue" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "f9df8ba2df127ca6", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "f9df8ba2df127ca6" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + }, + { + "step": 2, + "error": null + } + ], + "inspections": [ + { + "step": 3, + "scope": "s", + "record": { + "version": 2, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 90, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "quietForMs": 40, + "kind": "continuous", + "seenAt": 120 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 190 + } + }, + { + "step": 5, + "scope": "s", + "record": { + "version": 2, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 90, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "quietForMs": 40, + "kind": "continuous", + "seenAt": 120 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 190 + } + } + ], + "records": { + "s": { + "version": 5, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "f9df8ba2df127ca6", + "route": "queue", + "at": 190 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "f9df8ba2df127ca6", + "scope": "s", + "at": 190, + "route": "queue", + "body": { + "id": "f9df8ba2df127ca6", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "f9df8ba2df127ca6", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 90, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "quietForMs": 40, + "kind": "continuous", + "seenAt": 120 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 190 + }, + "at": 190 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "out-of-order source times and durations take the maximum sum", + "start": 180, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "judge": { + "*": { + "answers": [ + { + "route": "note" + } + ] + } + }, + "steps": [ + { + "push": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "observedAt": 140, + "quietForMs": 20 + }, + { + "id": "b", + "name": "drag", + "text": "drag b", + "observedAt": 100, + "quietForMs": 90 + } + ] + }, + { + "inspect": "s" + }, + { + "advance": 9 + }, + { + "inspect": "s" + }, + { + "advance": 1 + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "f9df8ba2df127ca6", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 140, + "quietForMs": 20, + "kind": "continuous", + "seenAt": 180 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 100, + "quietForMs": 90, + "kind": "continuous", + "seenAt": 180 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 190 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 190 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "f9df8ba2df127ca6", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "f9df8ba2df127ca6", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 140, + "quietForMs": 20, + "kind": "continuous", + "seenAt": 180 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 100, + "quietForMs": 90, + "kind": "continuous", + "seenAt": 180 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 190 + }, + "at": 190 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "ingested", + "scope": "s", + "count": 2, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "reason": "stream_quiet", + "count": 2, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "attempt": 1, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "route": "note" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "f9df8ba2df127ca6", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "f9df8ba2df127ca6" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + } + ], + "inspections": [ + { + "step": 1, + "scope": "s", + "record": { + "version": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 140, + "quietForMs": 20, + "kind": "continuous", + "seenAt": 180 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 100, + "quietForMs": 90, + "kind": "continuous", + "seenAt": 180 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 190 + } + }, + { + "step": 3, + "scope": "s", + "record": { + "version": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 140, + "quietForMs": 20, + "kind": "continuous", + "seenAt": 180 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 100, + "quietForMs": 90, + "kind": "continuous", + "seenAt": 180 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 190 + } + } + ], + "records": { + "s": { + "version": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "f9df8ba2df127ca6", + "route": "note", + "at": 190 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "f9df8ba2df127ca6", + "scope": "s", + "at": 190, + "route": "note", + "body": { + "id": "f9df8ba2df127ca6", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "f9df8ba2df127ca6", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 140, + "quietForMs": 20, + "kind": "continuous", + "seenAt": 180 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 100, + "quietForMs": 90, + "kind": "continuous", + "seenAt": 180 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 190 + }, + "at": 190 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "omitted continuous durations use the policy within an opted-in window", + "start": 100, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "settle": { + "streamGapMs": 30 + }, + "judge": { + "*": { + "answers": [ + { + "route": "queue" + } + ] + } + }, + "steps": [ + { + "push": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "quietForMs": 90 + } + ] + }, + { + "advance": 20 + }, + { + "push": "s", + "events": [ + { + "id": "b", + "name": "drag", + "text": "drag b" + } + ] + }, + { + "inspect": "s" + }, + { + "advance": 70 + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "f9df8ba2df127ca6", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 90, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "kind": "continuous", + "seenAt": 120 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 190 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 190 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "f9df8ba2df127ca6", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "f9df8ba2df127ca6", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 90, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "kind": "continuous", + "seenAt": 120 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 190 + }, + "at": 190 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "reason": "stream_quiet", + "count": 2, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "attempt": 1, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "route": "queue" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "f9df8ba2df127ca6", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "f9df8ba2df127ca6" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + }, + { + "step": 2, + "error": null + } + ], + "inspections": [ + { + "step": 3, + "scope": "s", + "record": { + "version": 2, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 90, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "kind": "continuous", + "seenAt": 120 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 190 + } + } + ], + "records": { + "s": { + "version": 5, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "f9df8ba2df127ca6", + "route": "queue", + "at": 190 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "f9df8ba2df127ca6", + "scope": "s", + "at": 190, + "route": "queue", + "body": { + "id": "f9df8ba2df127ca6", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "f9df8ba2df127ca6", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 90, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "kind": "continuous", + "seenAt": 120 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 190 + }, + "at": 190 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "held durations do not extend a fresh quiet period after wait", + "start": 100, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "settle": { + "closingGraceMs": 10 + }, + "judge": { + "*": { + "answers": [ + { + "route": "wait" + }, + { + "route": "queue" + } + ] + } + }, + "steps": [ + { + "push": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "quietForMs": 90 + }, + { + "id": "b", + "name": "close", + "text": "close b" + } + ] + }, + { + "advance": 10 + }, + { + "inspect": "s" + }, + { + "advance": 10 + }, + { + "push": "s", + "events": [ + { + "id": "c", + "name": "drag", + "text": "drag c", + "quietForMs": 20 + } + ] + }, + { + "inspect": "s" + }, + { + "advance": 20 + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "f9df8ba2df127ca6", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 90, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "close", + "data": {}, + "text": "close b", + "kind": "closing", + "seenAt": 100 + } + ], + "reason": "closing", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 110 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 110 + }, + { + "scope": "s", + "window": { + "id": "1a353cc02182e85a", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 90, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "close", + "data": {}, + "text": "close b", + "kind": "closing", + "seenAt": 100 + }, + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "quietForMs": 20, + "kind": "continuous", + "seenAt": 120 + } + ], + "reason": "stream_quiet", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 140 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 140 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "1a353cc02182e85a", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "1a353cc02182e85a", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 90, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "close", + "data": {}, + "text": "close b", + "kind": "closing", + "seenAt": 100 + }, + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "quietForMs": 20, + "kind": "continuous", + "seenAt": 120 + } + ], + "reason": "stream_quiet", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 140 + }, + "at": 140 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "ingested", + "scope": "s", + "count": 2, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "reason": "closing", + "count": 2, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "attempt": 1, + "offerWait": true + }, + { + "kind": "waiting", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "waits": 1, + "until": 10110 + }, + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "1a353cc02182e85a", + "reason": "stream_quiet", + "count": 3, + "merged": true + }, + { + "kind": "judging", + "scope": "s", + "batchId": "1a353cc02182e85a", + "attempt": 2, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "1a353cc02182e85a", + "route": "queue" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "1a353cc02182e85a", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "1a353cc02182e85a" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + }, + { + "step": 4, + "error": null + } + ], + "inspections": [ + { + "step": 2, + "scope": "s", + "record": { + "version": 3, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": { + "window": { + "id": "f9df8ba2df127ca6", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 90, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "close", + "data": {}, + "text": "close b", + "kind": "closing", + "seenAt": 100 + } + ], + "reason": "closing", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 110 + }, + "phase": { + "phase": "waiting", + "attempt": 1, + "until": 10110 + } + }, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 10110 + } + }, + { + "step": 5, + "scope": "s", + "record": { + "version": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b", + "c" + ], + "buffer": { + "entries": [ + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "quietForMs": 20, + "kind": "continuous", + "seenAt": 120 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": { + "window": { + "id": "f9df8ba2df127ca6", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 90, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "close", + "data": {}, + "text": "close b", + "kind": "closing", + "seenAt": 100 + } + ], + "reason": "closing", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 110 + }, + "phase": { + "phase": "waiting", + "attempt": 1, + "until": 10110 + } + }, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 140 + } + } + ], + "records": { + "s": { + "version": 7, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b", + "c" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "1a353cc02182e85a", + "route": "queue", + "at": 140 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "1a353cc02182e85a", + "scope": "s", + "at": 140, + "route": "queue", + "body": { + "id": "1a353cc02182e85a", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "1a353cc02182e85a", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 90, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "close", + "data": {}, + "text": "close b", + "kind": "closing", + "seenAt": 100 + }, + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "quietForMs": 20, + "kind": "continuous", + "seenAt": 120 + } + ], + "reason": "stream_quiet", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 140 + }, + "at": 140 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "zero quiet duration on an old observation settles at processing time", + "start": 100, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "judge": { + "*": { + "answers": [ + { + "route": "queue" + } + ] + } + }, + "steps": [ + { + "push": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "observedAt": 10, + "quietForMs": 0 + } + ] + }, + { + "advance": 0 + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 10, + "quietForMs": 0, + "kind": "continuous", + "seenAt": 100 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 100 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 100 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 10, + "quietForMs": 0, + "kind": "continuous", + "seenAt": 100 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 100 + }, + "at": 100 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "reason": "stream_quiet", + "count": 1, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "attempt": 1, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "route": "queue" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "3ecbd4f2ef91c78f", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "3ecbd4f2ef91c78f" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + } + ], + "inspections": [], + "records": { + "s": { + "version": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "3ecbd4f2ef91c78f", + "route": "queue", + "at": 100 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "at": 100, + "route": "queue", + "body": { + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 10, + "quietForMs": 0, + "kind": "continuous", + "seenAt": 100 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 100 + }, + "at": 100 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "quiet duration on another kind refuses the batch without deduplication", + "start": 100, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "judge": { + "*": { + "answers": [ + { + "route": "note" + } + ] + } + }, + "steps": [ + { + "push": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "quietForMs": 40 + }, + { + "id": "b", + "name": "look", + "text": "look b", + "quietForMs": 20 + } + ] + }, + { + "inspect": "s" + }, + { + "push": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "quietForMs": 0 + } + ] + }, + { + "advance": 0 + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 0, + "kind": "continuous", + "seenAt": 100 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 100 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 100 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 0, + "kind": "continuous", + "seenAt": 100 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 100 + }, + "at": 100 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "reason": "stream_quiet", + "count": 1, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "attempt": 1, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "route": "note" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "3ecbd4f2ef91c78f", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "3ecbd4f2ef91c78f" + } + ] + }, + "results": [ + { + "step": 0, + "error": { + "name": "TypeError", + "message": "attend: quietForMs requires a continuous event" + } + }, + { + "step": 2, + "error": null + } + ], + "inspections": [ + { + "step": 1, + "scope": "s", + "record": null + } + ], + "records": { + "s": { + "version": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "3ecbd4f2ef91c78f", + "route": "note", + "at": 100 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "at": 100, + "route": "note", + "body": { + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 0, + "kind": "continuous", + "seenAt": 100 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 100 + }, + "at": 100 + }, + "position": "1" + } + ] + } + }, { "scenario": { "name": "observation time sets a quiet deadline while at and seenAt remain distinct", diff --git a/docs/reference.md b/docs/reference.md index 865e835..cca094f 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -46,6 +46,33 @@ An already-due observation settles through the normal runner at processing time. Both runtimes retain `observedAt` through snapshots, logged inputs, windows and decision records. See [storage](storage.md) for version coordination when sharing a store. +## Continuous quiet duration + +A continuous event can supply a finite, nonnegative `quietForMs`. Zero makes its quiet deadline immediate. `push` and `attach` refuse invalid values or a duration on any other kind before admitting the batch or committing its cursor. + +Once a continuous entry supplies a duration, that group's deadline is the maximum of each entry's observation time plus its duration. An omitted duration uses `streamGapMs`; an omitted observation uses ingestion time. A late observation can therefore be due on arrival, but settlement still happens at processing time. Entry order does not change. + +```ts +import { createAttend } from '@acquiredintelligence/attend'; +import { fakeClock } from '@acquiredintelligence/attend/testing'; + +const clock = fakeClock(100); +const attend = createAttend({ + clock, + kind: { dial: 'continuous', confirmation: 'continuous' }, + judge: async () => ({ route: 'note' }), + sink: 'log', +}); +await attend.push('device', { name: 'dial', quietForMs: 40 }); +await clock.advance(20); +await attend.push('device', { name: 'confirmation', quietForMs: 90 }); +console.log((await attend.inspect('device'))?.dueAt); // 210 +``` + +Closing and passive deadlines can still settle the window earlier. Flush, age and bounds keep their existing precedence. After a wait, only fresh entries set a new quiet deadline; held entries retain their durations as data. Waits, retries and leases keep engine time. + +When every continuous entry omits `quietForMs`, existing timing remains unchanged, including backwards engine clocks. Explicit durations persist through snapshots, tails and decisions. Replay uses the snapshot policy for omitted durations. Changing a live engine's policy recalculates those default durations; it never changes an explicit duration. [Storage](storage.md) describes version coordination. + ## Routes | Route | The agent | Reaches the sink | diff --git a/docs/storage.md b/docs/storage.md index 39ccc04..2e11444 100644 --- a/docs/storage.md +++ b/docs/storage.md @@ -36,6 +36,6 @@ Each store also takes `retain` (decision rows kept by count or age), so the log Several processes can share one store. Any of them can `push`, and any number can `run` or serve the log: a write names the stored version it read, a writer that loses reloads and applies its input again, and every input is idempotent. Give every process the same `kind` function, because the process that ingests an event is the one that kinds it. A scope can take several sources at once; the record keeps one cursor per `Source.key`. Attach a given source to a scope from one process only, since two processes running the same source would overwrite each other's cursor, and a second `attend.attach` of the same key in one process throws. -Keep processes sharing a store on the same reducer version before using [observation time](reference.md#observation-time). A reducer-version mismatch triggers replay and a fresh snapshot; it does not fence out older readers or writers. Older entries without `observedAt` retain their stored `seenAt` during replay. The clock at replay time never replaces that timestamp. +Keep processes sharing a store on the same reducer version before using [observation time](reference.md#observation-time) or [continuous quiet durations](reference.md#continuous-quiet-duration). A reducer-version mismatch triggers replay and a fresh snapshot; it does not fence out older readers or writers. Older entries without `observedAt` retain their stored `seenAt` during replay. The clock at replay time never replaces that timestamp. Each adapter also has an `EventLog`: `memoryLog`, `sqliteLog`, `postgresLog` and `redisLog`. When producers live in other processes and you want a durable shared log in front of attend, append to the log and attach `logSource(log, scope)` instead of calling `push`. diff --git a/python/README.md b/python/README.md index d18aafb..640355d 100644 --- a/python/README.md +++ b/python/README.md @@ -80,6 +80,7 @@ redis-py runs each concurrent command on a pooled connection of its own, and its - Keyword arguments and `settle` keys are snake_case, such as `create_attend(settle={"wait_horizon_ms": 5000})`. Every value that crosses a store or a judge (events, windows, decisions, dead letters, records, traces) is a dict with the TypeScript field names, such as `decision["window"]["settledAt"]`, so both runtimes share one persisted layout. - A judge, sink, dead-letter handler, `context` or `capture` is called with `(value, signal)`, where `signal` is an `aqi_attend.AbortSignal`. Honour it with `await signal.race(work)` or by checking `signal.aborted`. - `push`, `flush` and `end` return futures that resolve once the input is persisted. They take the input when called, as the TypeScript promises do. +- A continuous event can carry `quietForMs` in its wire dictionary. [Continuous quiet duration](../docs/reference.md#continuous-quiet-duration) defines its validation, defaults and recovery. - An event's optional `observedAt` keeps its camelCase wire name. It supplies source observation time for deadlines; `seenAt` remains engine ingestion time. The shared [observation-time reference](../docs/reference.md#observation-time) defines validation, ordering and replay. - Cancelling the task that runs `run()` stops it the way `stop()` does. - `default_notice(decision, max_lines=20, fold=True)` takes its options as keyword arguments. [The notice](../docs/sinks.md#the-notice) says what it folds. diff --git a/python/src/aqi_attend/attend.py b/python/src/aqi_attend/attend.py index 17bdc32..f62fa31 100644 --- a/python/src/aqi_attend/attend.py +++ b/python/src/aqi_attend/attend.py @@ -319,6 +319,8 @@ def _classify(self, given: Mapping[str, Any] | Sequence[Mapping[str, Any]]) -> l kind = self._kind(copied) if kind not in KINDS: raise TypeError("attend: invalid event kind") + if "quietForMs" in copied and kind != "continuous": + raise TypeError("attend: quietForMs requires a continuous event") classified.append(cast(KindedEvent, {**copied, "kind": kind})) return classified diff --git a/python/src/aqi_attend/conformance.py b/python/src/aqi_attend/conformance.py index d960f9d..02d4130 100644 --- a/python/src/aqi_attend/conformance.py +++ b/python/src/aqi_attend/conformance.py @@ -60,10 +60,11 @@ def _window(id: str) -> Window: "id": f"event:{id}", "at": 1, "observedAt": 1, + "quietForMs": 12, "name": "changed", "data": {"nested": [None, True, "héllo 🌍\u0000"]}, "text": "héllo 🌍\u0000", - "kind": "closing", + "kind": "continuous", "seenAt": 2, } return {"id": id, "events": [entry], "reason": "closing", "waits": 0, "dropped": 0, "gap": False, "settledAt": 3} diff --git a/python/src/aqi_attend/core/reducer.py b/python/src/aqi_attend/core/reducer.py index d205b2c..cf3007c 100644 --- a/python/src/aqi_attend/core/reducer.py +++ b/python/src/aqi_attend/core/reducer.py @@ -45,7 +45,7 @@ window_shed, ) -REDUCER_VERSION = 2 +REDUCER_VERSION = 3 """Bumped whenever a release changes a transition. Stored with every snapshot.""" _LANES: tuple[OutboxLane, OutboxLane] = ("decisions", "deadLetters") diff --git a/python/src/aqi_attend/core/types.py b/python/src/aqi_attend/core/types.py index 575ebe5..a0ec2ca 100644 --- a/python/src/aqi_attend/core/types.py +++ b/python/src/aqi_attend/core/types.py @@ -506,7 +506,7 @@ class IdRing: @dataclass(slots=True) class TriggerSummary: - """Everything ``deadline`` reads, kept O(1). NaN means none for the ``*_at`` fields; ``min_flush_at`` and ``prefix_min_sheddable_at`` use inf.""" + """Everything ``deadline`` reads, kept O(1). Absent times use NaN; minima start at inf and maxima at -inf.""" min_flush_at: float = math.inf last_closing_at: float = math.nan @@ -515,6 +515,8 @@ class TriggerSummary: first_act_at: float = math.nan max_closing_at: float = -math.inf max_stream_at: float = -math.inf + max_default_stream_at: float = -math.inf + max_explicit_stream_end_at: float = -math.inf max_passive_at: float = -math.inf min_act_at: float = math.inf closing_observed: bool = False diff --git a/python/src/aqi_attend/core/window.py b/python/src/aqi_attend/core/window.py index c3ddea3..e66fa0a 100644 --- a/python/src/aqi_attend/core/window.py +++ b/python/src/aqi_attend/core/window.py @@ -39,6 +39,10 @@ def _summarize_entry(summary: TriggerSummary, entry: Entry, index: int) -> None: summary.max_stream_at = _max(summary.max_stream_at, observed_at) summary.stream_observed |= explicit summary.last_stream_at = summary.max_stream_at if summary.stream_observed else seen_at + if "quietForMs" in entry: + summary.max_explicit_stream_end_at = _max(summary.max_explicit_stream_end_at, observed_at + entry["quietForMs"]) + else: + summary.max_default_stream_at = _max(summary.max_default_stream_at, observed_at) elif kind == "passive": summary.max_passive_at = _max(summary.max_passive_at, observed_at) summary.passive_observed |= explicit @@ -267,7 +271,11 @@ def window_deadline(policy: SettlePolicy, open: OpenWindow) -> tuple[float, Sett if not math.isnan(s.last_closing_at) and (reason is None or closing < at): at = closing reason = "closing" - stream = s.last_stream_at + policy["streamGapMs"] + stream = ( + s.last_stream_at + policy["streamGapMs"] + if s.max_explicit_stream_end_at == -math.inf + else _max(s.max_explicit_stream_end_at, s.max_default_stream_at + policy["streamGapMs"]) + ) if not math.isnan(s.last_stream_at) and (reason is None or stream < at): at = stream reason = "stream_quiet" diff --git a/python/src/aqi_attend/shell/copy.py b/python/src/aqi_attend/shell/copy.py index 1e463e7..6522f87 100644 --- a/python/src/aqi_attend/shell/copy.py +++ b/python/src/aqi_attend/shell/copy.py @@ -58,6 +58,10 @@ def copy_event(event: Mapping[str, object], fill: tuple[Callable[[], str], Calla observed = fields["observedAt"] if isinstance(observed, bool) or not isinstance(observed, (int, float)) or not -sys.float_info.max <= observed <= sys.float_info.max: raise TypeError("attend: observedAt must be a finite number") + if "quietForMs" in fields: + quiet = fields["quietForMs"] + if isinstance(quiet, bool) or not isinstance(quiet, (int, float)) or not 0 <= quiet <= sys.float_info.max: + raise TypeError("attend: quietForMs must be a finite nonnegative number") if fill is not None: if "id" not in fields: fields["id"] = fill[0]() diff --git a/python/tests/scenario.py b/python/tests/scenario.py index 7c39520..b7c1782 100644 --- a/python/tests/scenario.py +++ b/python/tests/scenario.py @@ -256,6 +256,7 @@ async def result(index: int, work: asyncio.Future[None]) -> None: "data": e.get("data", {}), **({"text": e["text"]} if "text" in e else {}), **({"observedAt": e["observedAt"]} if "observedAt" in e else {}), + **({"quietForMs": e["quietForMs"]} if "quietForMs" in e else {}), } for e in step["events"] ] diff --git a/python/tests/test_continuous_quiet.py b/python/tests/test_continuous_quiet.py index 5857b7f..1196bc9 100644 --- a/python/tests/test_continuous_quiet.py +++ b/python/tests/test_continuous_quiet.py @@ -1,13 +1,16 @@ """Continuous events can carry distinct quiet durations within one window.""" import asyncio +from collections.abc import Awaitable, Callable import pytest -from aqi_attend import create_attend -from aqi_attend.core.types import Buffer, Entry, Kind, default_policy +from aqi_attend import AbortController, AbortSignal, create_attend, memory_store +from aqi_attend.core.step import initial_record +from aqi_attend.core.types import Buffer, Entry, Kind, SourceBatch, default_policy from aqi_attend.core.window import deadline -from aqi_attend.testing import fake_clock, recording_sink, scripted_judge +from aqi_attend.store.types import ScopeWrite +from aqi_attend.testing import ScriptedAnswer, fake_clock, harness, recording_sink, scripted_judge def entry(id: str, seen_at: float, *, observed_at: float | None = None, quiet: float | None = None, kind: Kind = "continuous") -> Entry: @@ -121,3 +124,137 @@ async def test_zero_duration_and_late_observation_settle_at_processing_time() -> await attend.stop() await running await attend.store.close() + + +@pytest.mark.parametrize("kind", ["continuous", "passive"]) +async def test_source_duration_admission_controls_cursor(kind: Kind) -> None: + clock = fake_clock(100) + attend = create_attend(clock=clock, kind={"move": kind}, judge=scripted_judge([{"route": "queue"}]), sink="log") + controller = AbortController() + emitted = asyncio.Event() + refused = False + + class Feed: + key = "feed" + + async def subscribe(self, cursor: str | None, emit: Callable[[SourceBatch], Awaitable[None]], signal: AbortSignal) -> None: + nonlocal refused + try: + await emit({"events": [{"id": "a", "at": 0, "name": "move", "data": {}, "observedAt": 100, "quietForMs": 40}], "cursor": "1"}) + except TypeError: + refused = True + finally: + emitted.set() + ended = asyncio.Event() + remove = signal.add_listener(ended.set) + try: + if not signal.aborted: + await ended.wait() + finally: + remove() + + running = asyncio.create_task(attend.run()) + attached = asyncio.create_task(attend.attach("s", Feed(), signal=controller.signal)) + try: + await emitted.wait() + assert refused == (kind != "continuous") + record = await attend.inspect("s") + if refused: + assert record is None + else: + assert record is not None and record["dueAt"] == 140 and record["cursors"] == {"feed": "1"} + assert record["buffer"]["entries"][0].get("quietForMs") == 40 + finally: + controller.abort() + await attached + await attend.stop() + await running + await attend.store.close() + + +@pytest.mark.parametrize(("answer", "phase", "delay"), [({"route": "wait"}, "waiting", 10_000), ({"fail": "temporary"}, "retrying", 1000)]) +async def test_duration_survives_crash_without_changing_processing_clock(answer: ScriptedAnswer, phase: str, delay: float) -> None: + judge = scripted_judge([answer, {"route": "queue"}]) + h = await harness({"kind": {"move": "continuous"}, "judge": judge, "sink": recording_sink()}) + try: + await h.push([{"id": "a", "at": -1, "name": "move", "data": {}, "quietForMs": 40}]) + await h.advance(40) + record = await h.inspect() + assert record is not None and record["batch"] is not None and record["batch"]["phase"]["phase"] == phase + h.crash() + await h.restart() + await h.advance(delay - 1) + assert len(judge.calls) == 1 + await h.advance(1) + assert [call["now"] for call in judge.calls] == [40, 40 + delay] + assert [call["window"]["settledAt"] for call in judge.calls] == [40, 40] + assert judge.calls[1]["window"]["events"][0].get("quietForMs") == 40 + finally: + await h.stop() + + +async def test_live_policy_change_recomputes_only_omitted_durations() -> None: + store = memory_store() + clock = fake_clock(100) + first = create_attend(store=store, clock=clock, kind={"move": "continuous"}, judge=scripted_judge([{"route": "queue"}]), sink="log", settle={"stream_gap_ms": 80}) + await first.push("s", [{"id": "a", "name": "move"}, {"id": "b", "name": "move", "quietForMs": 40}]) + record = await first.inspect("s") + assert record is not None and record["dueAt"] == 180 + await first.stop() + second = create_attend(store=store, clock=clock, kind={"move": "continuous"}, judge=scripted_judge([{"route": "queue"}]), sink="log", settle={"stream_gap_ms": 20}) + try: + before = await second.inspect("s") + assert before is not None and before["dueAt"] == 180 + await second.push("s", []) + record = await second.inspect("s") + assert record is not None and record["dueAt"] == 140 + assert [event.get("quietForMs") for event in record["buffer"]["entries"]] == [None, 40] + finally: + await second.stop() + await store.close() + + +async def test_revision_two_snapshot_and_mixed_tail_rebuild_end_times() -> None: + store = memory_store() + policy = default_policy() + policy["streamGapMs"] = 30 + record = initial_record("s") + record.update(version=1, seen=["a"], buffer=buffer(entry("a", 100, observed_at=100)), dueAt=130) + checkpoint: ScopeWrite = { + "scope": "s", + "expectedVersion": 0, + "inputs": [{"now": 100, "input": {"kind": "tick"}}], + "snapshot": {"version": 1, "record": record, "policy": policy, "reducer": 2}, + "appends": [], + } + tail: ScopeWrite = { + "scope": "s", + "expectedVersion": 1, + "snapshot": None, + "appends": [], + "inputs": [ + { + "now": 120, + "input": { + "kind": "events", + "events": [ + {"id": "b", "at": 0, "name": "move", "data": {}, "kind": "continuous", "observedAt": 110, "quietForMs": 90}, + {"id": "c", "at": 0, "name": "move", "data": {}, "kind": "continuous"}, + ], + }, + } + ], + } + assert await store.commit([checkpoint]) == ["ok"] + assert await store.commit([tail]) == ["ok"] + attend = create_attend(store=store, clock=fake_clock(120), settle={"stream_gap_ms": 30}, kind={"move": "continuous"}, judge=scripted_judge([{"route": "queue"}]), sink="log") + try: + await attend.push("s", []) + loaded = await attend.inspect("s") + assert loaded is not None and loaded["dueAt"] == 200 + assert [(event["id"], event.get("quietForMs"), event["seenAt"]) for event in loaded["buffer"]["entries"]] == [("a", None, 100), ("b", 90, 120), ("c", None, 120)] + stored = await store.load("s") + assert stored is not None and stored["snapshot"] is not None and stored["snapshot"]["reducer"] == 3 + finally: + await attend.stop() + await store.close() diff --git a/python/tests/test_observation_time.py b/python/tests/test_observation_time.py index 0c4cb9d..2aaa10a 100644 --- a/python/tests/test_observation_time.py +++ b/python/tests/test_observation_time.py @@ -259,7 +259,7 @@ async def test_prior_reducer_snapshot_and_tail_keep_ingestion_deadlines() -> Non assert loaded is not None and loaded["dueAt"] == 2100 assert [(event["id"], event["seenAt"], event.get("observedAt")) for event in loaded["buffer"]["entries"]] == [("a", 1000, None), ("b", 1100, None)] stored = await store.load("s") - assert stored is not None and stored["snapshot"] is not None and stored["snapshot"]["reducer"] == 2 + assert stored is not None and stored["snapshot"] is not None and stored["snapshot"]["reducer"] == 3 finally: await attend.stop() await store.close() @@ -291,13 +291,14 @@ async def commit(self, writes: Sequence[ScopeWrite]) -> list[CommitOutcome]: store = RacingStore() attend = create_attend(store=store, clock=clock, kind={"change": "continuous"}, judge=scripted_judge([{"route": "queue"}]), sink="log") try: - pushed = attend.push("s", {"id": "a", "name": "change", "observedAt": 100}) + pushed = attend.push("s", {"id": "a", "name": "change", "observedAt": 100, "quietForMs": 1000}) await raced.wait() await clock.advance(50) await pushed record = await attend.inspect("s") assert record is not None and [event["id"] for event in record["buffer"]["entries"]] == ["racer", "a"] assert record["buffer"]["entries"][1].get("observedAt") == 100 + assert record["buffer"]["entries"][1].get("quietForMs") == 1000 assert record["dueAt"] == 1100 finally: await attend.stop() diff --git a/src/attend.ts b/src/attend.ts index 3a816c9..dd92c77 100644 --- a/src/attend.ts +++ b/src/attend.ts @@ -81,6 +81,7 @@ export function createAttendInternal(config: AttendConfig, snapshot: 'ratio' | ' if (event.observedAt !== undefined && event.observedAt > clock.now()) throw new TypeError('attend: observedAt must not be in the future'); const kind = kindOf(event); if (!KINDS.includes(kind)) throw new TypeError('attend: invalid event kind'); + if (event.quietForMs !== undefined && kind !== 'continuous') throw new TypeError('attend: quietForMs requires a continuous event'); const entry = { ...event, kind }; sizedEvents.set(entry, bytes); classified[i] = entry; diff --git a/src/core/reducer.ts b/src/core/reducer.ts index 271af81..be71838 100644 --- a/src/core/reducer.ts +++ b/src/core/reducer.ts @@ -9,7 +9,7 @@ import { seenAdmit, seenRelease, seenTrim } from './seen.js'; import { estimateRenderedBytes, openWindow, shedEntries, windowAppend, windowCompact, windowDeadline, windowPrune, windowShed, windowSize } from './window.js'; /** Bumped whenever a release changes a transition. Stored with every snapshot. */ -export const REDUCER_VERSION = 2; +export const REDUCER_VERSION = 3; /** An empty output. One output may collect several inputs: `apply` only ever sets `changed`. */ export function newOutput(): ApplyOutput { diff --git a/src/core/types.ts b/src/core/types.ts index 1c7940a..2a58d23 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -516,6 +516,9 @@ export interface TriggerSummary { /** Candidate extrema retain earlier entries before a kind first uses observation time. */ maxClosingAt: number; maxStreamAt: number; + /** Default durations retain observation time so policy changes can recompute their ends. */ + maxDefaultStreamAt: number; + maxExplicitStreamEndAt: number; maxPassiveAt: number; minActAt: number; closingObserved: boolean; diff --git a/src/core/window.ts b/src/core/window.ts index 9b157e3..c185173 100644 --- a/src/core/window.ts +++ b/src/core/window.ts @@ -20,6 +20,7 @@ function emptySummary(): TriggerSummary { minFlushAt: Infinity, lastClosingAt: NaN, lastStreamAt: NaN, lastPassiveAt: NaN, firstActAt: NaN, firstActIndex: -1, prefixMinSheddableAt: Infinity, sheddable: 0, lastSeenAt: NaN, maxClosingAt: -Infinity, maxStreamAt: -Infinity, maxPassiveAt: -Infinity, minActAt: Infinity, + maxDefaultStreamAt: -Infinity, maxExplicitStreamEndAt: -Infinity, closingObserved: false, streamObserved: false, passiveObserved: false, actObserved: false, lastObservationAt: NaN, }; } @@ -38,6 +39,8 @@ function summarizeEntry(summary: TriggerSummary, entry: Entry, index: number): v summary.maxStreamAt = Math.max(summary.maxStreamAt, observedAt); summary.streamObserved ||= explicit; summary.lastStreamAt = summary.streamObserved ? summary.maxStreamAt : entry.seenAt; + if (entry.quietForMs === undefined) summary.maxDefaultStreamAt = Math.max(summary.maxDefaultStreamAt, observedAt); + else summary.maxExplicitStreamEndAt = Math.max(summary.maxExplicitStreamEndAt, observedAt + entry.quietForMs); } if (entry.kind === 'passive') { summary.maxPassiveAt = Math.max(summary.maxPassiveAt, observedAt); @@ -276,7 +279,9 @@ export function windowDeadline(policy: SettlePolicy, open: OpenWindow): { at: nu at = closing; reason = 'closing'; } - const stream = s.lastStreamAt + policy.streamGapMs; + const stream = s.maxExplicitStreamEndAt === -Infinity + ? s.lastStreamAt + policy.streamGapMs + : Math.max(s.maxExplicitStreamEndAt, s.maxDefaultStreamAt + policy.streamGapMs); if (!Number.isNaN(s.lastStreamAt) && (reason === null || stream < at)) { at = stream; reason = 'stream_quiet'; diff --git a/src/internal/shared.ts b/src/internal/shared.ts index 9bf0b77..2e8ad6f 100644 --- a/src/internal/shared.ts +++ b/src/internal/shared.ts @@ -121,6 +121,7 @@ export function copyEvent(event: Event, defaultData = false): Event { if (!isRecord(data)) throw new TypeError('attend: event data must be a JSON object'); fields.data = data; checkObservation(fields.observedAt); + checkQuietDuration(fields.quietForMs); return fields as unknown as Event; } return checkedEvent(toJson(fields, '', 0), defaultData); @@ -132,9 +133,14 @@ function checkedEvent(copied: JsonValue | undefined, defaultData: boolean): Even if (defaultData && isRecord(copied) && copied.data === undefined) copied.data = {}; if (!isRecord(copied) || !isRecord(copied.data)) throw new TypeError('attend: event data must be a JSON object'); checkObservation(copied.observedAt); + checkQuietDuration(copied.quietForMs); return copied as unknown as Event; } function checkObservation(value: unknown): void { if (value !== undefined && (typeof value !== 'number' || !isFinite(value))) throw new TypeError('attend: observedAt must be a finite number'); } + +function checkQuietDuration(value: unknown): void { + if (value !== undefined && (typeof value !== 'number' || !isFinite(value) || value < 0)) throw new TypeError('attend: quietForMs must be a finite nonnegative number'); +} diff --git a/src/testing.ts b/src/testing.ts index 4fc7278..b05008d 100644 --- a/src/testing.ts +++ b/src/testing.ts @@ -182,7 +182,7 @@ export function logConformance(make: () => Promise | EventLog, options [ 'events round-trip deep-equal', async (log) => { - const e: Event = { id: 'a', at: 7, observedAt: 9, name: 'x.y', data: { n: 1, s: 'ünï 🌍', l: [null, { k: false }] }, text: 'one line' }; + const e: Event = { id: 'a', at: 7, observedAt: 9, quietForMs: 12, name: 'x.y', data: { n: 1, s: 'ünï 🌍', l: [null, { k: false }] }, text: 'one line' }; await log.append('s', [e]); assertEqual((await log.read('s', null, { limit: 1 }))[0]?.event, e, 'round trip'); }, diff --git a/src/testing/conformance.ts b/src/testing/conformance.ts index 17d0037..f1f1bc5 100644 --- a/src/testing/conformance.ts +++ b/src/testing/conformance.ts @@ -16,7 +16,7 @@ function logged(id: string, now = 1000): LoggedInput { function window(id: string): Window { return { - id, events: [{ id: `event:${id}`, at: 1, observedAt: 1, name: 'changed', data: { nested: [null, true, 'héllo 🌍\u0000'] }, text: 'héllo 🌍\u0000', kind: 'closing', seenAt: 2 }], + id, events: [{ id: `event:${id}`, at: 1, observedAt: 1, quietForMs: 12, name: 'changed', data: { nested: [null, true, 'héllo 🌍\u0000'] }, text: 'héllo 🌍\u0000', kind: 'continuous', seenAt: 2 }], reason: 'closing', waits: 0, dropped: 0, gap: false, settledAt: 3, }; } diff --git a/test/conformance/scenario.ts b/test/conformance/scenario.ts index a312352..5889f01 100644 --- a/test/conformance/scenario.ts +++ b/test/conformance/scenario.ts @@ -53,6 +53,7 @@ export interface EventSpec { name: string; at?: number; observedAt?: number; + quietForMs?: number; data?: JsonObject; text?: string; } @@ -268,7 +269,7 @@ export async function runScenario(scenario: Scenario): Promise { for (const [index, step] of scenario.steps.entries()) { if ('push' in step) { scopes.add(step.push); - const events = step.events.map((e) => ({ id: e.id, at: e.at ?? 0, name: e.name, data: e.data ?? {}, ...(e.text === undefined ? {} : { text: e.text }), ...(e.observedAt === undefined ? {} : { observedAt: e.observedAt }) })); + const events = step.events.map((e) => ({ id: e.id, at: e.at ?? 0, name: e.name, data: e.data ?? {}, ...(e.text === undefined ? {} : { text: e.text }), ...(e.observedAt === undefined ? {} : { observedAt: e.observedAt }), ...(e.quietForMs === undefined ? {} : { quietForMs: e.quietForMs }) })); await result(index, () => attend.push(step.push, events)); } else if ('advance' in step) { await clock.advance(step.advance); diff --git a/test/conformance/scenarios.ts b/test/conformance/scenarios.ts index 93bba29..8e9021b 100644 --- a/test/conformance/scenarios.ts +++ b/test/conformance/scenarios.ts @@ -14,6 +14,57 @@ const advance = (ms: number) => ({ advance: ms }); const T = 'test/attend.test.ts'; export const SCENARIOS: Scenario[] = [ + { + name: 'different continuous durations settle after the latest event end', + start: 100, + kinds: KINDS, + judge: { '*': { answers: [{ route: 'queue' }] } }, + steps: [push('s', ev('a', 'drag', { quietForMs: 40 })), advance(20), push('s', ev('b', 'drag', { quietForMs: 90 })), { inspect: 's' }, advance(89), { inspect: 's' }, advance(1)], + }, + { + name: 'a later short duration does not replace an earlier long end', + start: 100, + kinds: KINDS, + judge: { '*': { answers: [{ route: 'queue' }] } }, + steps: [push('s', ev('a', 'drag', { quietForMs: 90 })), advance(20), push('s', ev('b', 'drag', { quietForMs: 40 })), { inspect: 's' }, advance(69), { inspect: 's' }, advance(1)], + }, + { + name: 'out-of-order source times and durations take the maximum sum', + start: 180, + kinds: KINDS, + judge: { '*': { answers: [{ route: 'note' }] } }, + steps: [push('s', ev('a', 'drag', { observedAt: 140, quietForMs: 20 }), ev('b', 'drag', { observedAt: 100, quietForMs: 90 })), { inspect: 's' }, advance(9), { inspect: 's' }, advance(1)], + }, + { + name: 'omitted continuous durations use the policy within an opted-in window', + start: 100, + kinds: KINDS, + settle: { streamGapMs: 30 }, + judge: { '*': { answers: [{ route: 'queue' }] } }, + steps: [push('s', ev('a', 'drag', { quietForMs: 90 })), advance(20), push('s', ev('b', 'drag')), { inspect: 's' }, advance(70)], + }, + { + name: 'held durations do not extend a fresh quiet period after wait', + start: 100, + kinds: KINDS, + settle: { closingGraceMs: 10 }, + judge: { '*': { answers: [{ route: 'wait' }, { route: 'queue' }] } }, + steps: [push('s', ev('a', 'drag', { quietForMs: 90 }), ev('b', 'close')), advance(10), { inspect: 's' }, advance(10), push('s', ev('c', 'drag', { quietForMs: 20 })), { inspect: 's' }, advance(20)], + }, + { + name: 'zero quiet duration on an old observation settles at processing time', + start: 100, + kinds: KINDS, + judge: { '*': { answers: [{ route: 'queue' }] } }, + steps: [push('s', ev('a', 'drag', { observedAt: 10, quietForMs: 0 })), advance(0)], + }, + { + name: 'quiet duration on another kind refuses the batch without deduplication', + start: 100, + kinds: KINDS, + judge: { '*': { answers: [{ route: 'note' }] } }, + steps: [push('s', ev('a', 'drag', { quietForMs: 40 }), ev('b', 'look', { quietForMs: 20 })), { inspect: 's' }, push('s', ev('a', 'drag', { quietForMs: 0 })), advance(0)], + }, { name: 'observation time sets a quiet deadline while at and seenAt remain distinct', kinds: KINDS, diff --git a/test/continuous-quiet.test.ts b/test/continuous-quiet.test.ts index 9b2b749..2453a68 100644 --- a/test/continuous-quiet.test.ts +++ b/test/continuous-quiet.test.ts @@ -1,8 +1,9 @@ import { expect, test } from 'vitest'; -import { createAttend, DEFAULT_POLICY, KINDS } from '../src/index.js'; -import type { Buffer, Entry } from '../src/types.js'; +import { createAttend, DEFAULT_POLICY, KINDS, memoryStore, type AttendConfig } from '../src/index.js'; +import type { Buffer, Entry, Kind, Source } from '../src/types.js'; import { deadline } from '../src/core/window.js'; -import { fakeClock, recordingSink, scriptedJudge } from '../src/testing.js'; +import { initialRecord } from '../src/step.js'; +import { fakeClock, harness, recordingSink, scriptedJudge, type ScriptedAnswer } from '../src/testing.js'; function entry(id: string, seenAt: number, extra: Partial = {}): Entry { return { id, at: -1, name: 'move', data: {}, kind: 'continuous', seenAt, ...extra }; @@ -98,3 +99,97 @@ test('zero duration is immediate and late observations settle at processing time await running; } }); + +test.each(['continuous', 'passive'] satisfies Kind[])('source duration admission for %s controls its cursor', async (kind) => { + const clock = fakeClock(100); + const attend = createAttend({ clock, kind: { move: kind }, judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); + const controller = new AbortController(); + const emitted = new AbortController(); + const done = new Promise((resolve) => emitted.signal.addEventListener('abort', () => resolve(), { once: true })); + let refused = false; + const source: Source = { + key: 'feed', + async subscribe(_cursor, emit, signal) { + try { await emit({ events: [{ id: 'a', at: 0, observedAt: 100, quietForMs: 40, name: 'move', data: {} }], cursor: '1' }); } + catch (error) { if (!(error instanceof TypeError)) throw error; refused = true; } + finally { emitted.abort(); } + if (!signal.aborted) await new Promise((resolve) => signal.addEventListener('abort', () => resolve(), { once: true })); + }, + }; + const running = attend.run(); + const attached = attend.attach('s', source, { signal: controller.signal }); + try { + await done; + expect(refused).toBe(kind !== 'continuous'); + const record = await attend.inspect('s'); + if (refused) expect(record).toBeNull(); + else expect(record).toMatchObject({ dueAt: 140, cursors: { feed: '1' }, buffer: { entries: [{ quietForMs: 40, observedAt: 100 }] } }); + } finally { + controller.abort(); + await attached; + await attend.stop(); + await running; + } +}); + +test.each([ + { answer: { route: 'wait' }, phase: 'waiting', delay: 10_000 }, + { answer: { fail: 'temporary' }, phase: 'retrying', delay: 1000 }, +] satisfies { answer: ScriptedAnswer; phase: string; delay: number }[])('duration survives a crash during $phase without changing its processing clock', async ({ answer, phase, delay }) => { + const judge = scriptedJudge([answer, { route: 'queue' }]); + const h = harness({ kind: () => 'continuous', judge, sink: recordingSink() }); + try { + await h.push([{ id: 'a', at: -1, name: 'move', data: {}, quietForMs: 40 }]); + await h.advance(40); + expect((await h.inspect())?.batch?.phase.phase).toBe(phase); + h.crash(); + await h.restart(); + await h.advance(delay - 1); + expect(judge.calls).toHaveLength(1); + await h.advance(1); + expect(judge.calls.map((call) => call.now)).toEqual([40, 40 + delay]); + expect(judge.calls.map((call) => call.window.settledAt)).toEqual([40, 40]); + expect(judge.calls[1]?.window.events[0]?.quietForMs).toBe(40); + } finally { + await h.stop(); + } +}); + +test('a live policy change recomputes only omitted continuous durations', async () => { + const store = memoryStore(); + const config = { store, clock: fakeClock(100), kind: { move: 'continuous' }, judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' } satisfies AttendConfig; + const first = createAttend({ ...config, settle: { streamGapMs: 80 } }); + await first.push('s', [{ id: 'a', name: 'move' }, { id: 'b', name: 'move', quietForMs: 40 }]); + expect((await first.inspect('s'))?.dueAt).toBe(180); + await first.stop(); + const second = createAttend({ ...config, settle: { streamGapMs: 20 } }); + try { + expect((await second.inspect('s'))?.dueAt).toBe(180); + await second.push('s', []); + expect((await second.inspect('s'))?.dueAt).toBe(140); + expect((await second.inspect('s'))?.buffer.entries.map((event) => event.quietForMs)).toEqual([undefined, 40]); + } finally { + await second.stop(); + } +}); + +test('a revision-two snapshot and mixed tail rebuild continuous end times', async () => { + const store = memoryStore(); + const policy = { ...DEFAULT_POLICY, streamGapMs: 30 }; + const record = { ...initialRecord('s'), version: 1, seen: ['a'], buffer: buffer(entry('a', 100, { observedAt: 100 })), dueAt: 130 }; + expect(await store.commit([{ scope: 's', expectedVersion: 0, inputs: [{ now: 100, input: { kind: 'tick' } }], snapshot: { version: 1, record, policy, reducer: 2 }, appends: [] }])).toEqual(['ok']); + expect(await store.commit([{ scope: 's', expectedVersion: 1, snapshot: null, appends: [], inputs: [{ now: 120, input: { kind: 'events', events: [ + { id: 'b', at: 0, name: 'move', data: {}, kind: 'continuous', observedAt: 110, quietForMs: 90 }, + { id: 'c', at: 0, name: 'move', data: {}, kind: 'continuous' }, + ] } }] }])).toEqual(['ok']); + const attend = createAttend({ store, clock: fakeClock(120), settle: { streamGapMs: 30 }, kind: { move: 'continuous' }, judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); + try { + await attend.push('s', []); + const loaded = await attend.inspect('s'); + expect(loaded?.dueAt).toBe(200); + expect(loaded?.buffer.entries.map((event) => [event.id, event.quietForMs, event.seenAt])).toEqual([['a', undefined, 100], ['b', 90, 120], ['c', undefined, 120]]); + expect((await store.load('s'))?.snapshot?.reducer).toBe(3); + } finally { + await attend.stop(); + } +}); diff --git a/test/core-inputs.test.ts b/test/core-inputs.test.ts index 9771346..1ec7ca8 100644 --- a/test/core-inputs.test.ts +++ b/test/core-inputs.test.ts @@ -379,7 +379,7 @@ test('assertInvariants identifies corrupt counts, rings, summaries, sizes, hashe lane.outbox.decisions.push(lane.outbox.decisions[0]!); lane.dueAt = nextDue(policy, lane); assert.throws(() => assertInvariants(lane, policy), /^Error: outbox: more than one in flight/); - assert.equal(REDUCER_VERSION, 2); + assert.equal(REDUCER_VERSION, 3); }); test('fromRecord accepts frozen oracle snapshots without changing them', () => { diff --git a/test/observation-time.test.ts b/test/observation-time.test.ts index f0ebad0..ba5bc02 100644 --- a/test/observation-time.test.ts +++ b/test/observation-time.test.ts @@ -207,7 +207,7 @@ test('a prior reducer snapshot and tail retain ingestion-time deadlines on upgra const loaded = await attend.inspect('s'); expect(loaded?.dueAt).toBe(2100); expect(loaded?.buffer.entries.map((event) => [event.id, event.seenAt, event.observedAt])).toEqual([['a', 1000, undefined], ['b', 1100, undefined]]); - expect((await store.load('s'))?.snapshot?.reducer).toBe(2); + expect((await store.load('s'))?.snapshot?.reducer).toBe(3); } finally { await attend.stop(); } @@ -233,13 +233,14 @@ test('a conflicting write reloads without replacing observation time', async () }; const attend = createAttend({ store, clock, kind: { change: 'continuous' }, judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); try { - const pushed = attend.push('s', { id: 'a', name: 'change', observedAt: 100 }); + const pushed = attend.push('s', { id: 'a', name: 'change', observedAt: 100, quietForMs: 1000 }); await raced.promise; await clock.advance(50); await pushed; const record = await attend.inspect('s'); expect(record?.buffer.entries.map((event) => event.id)).toEqual(['racer', 'a']); expect(record?.buffer.entries[1]?.observedAt).toBe(100); + expect(record?.buffer.entries[1]?.quietForMs).toBe(1000); expect(record?.dueAt).toBe(1100); } finally { await attend.stop(); diff --git a/test/recovery.test.ts b/test/recovery.test.ts index 6b28080..fc16215 100644 --- a/test/recovery.test.ts +++ b/test/recovery.test.ts @@ -69,7 +69,7 @@ test('recovers every committed write under all snapshot cadences and policy chan let tailInputs = 0; let snapshotBytes = JSON.stringify(latest.record).length; const replay = (snapshot: Snapshot, through: number, expected: ScopeRecord): void => { - assert.equal(snapshot.reducerVersion, 2); + assert.equal(snapshot.reducerVersion, 3); const restored = fromRecord(deepFreeze(json(snapshot.record)), snapshot.policy); let bound = Math.max(snapshot.policy.seenCount, restored.seen.size); assertInvariants(restored, { ...snapshot.policy, seenCount: bound }); From 4089086d25133933b356613d5db3728e01f68147 Mon Sep 17 00:00:00 2001 From: asher-aqi Date: Thu, 12 Nov 2026 01:17:31 -0600 Subject: [PATCH 3/4] test(clock): reproduce omitted durations and absent-default arithmetic Invalid timing fields must not disappear during JSON copying. An explicit continuous duration must also work when no entry uses the configured default gap. --- python/tests/test_continuous_quiet.py | 17 +++++++++++++++++ test/continuous-quiet.test.ts | 18 +++++++++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/python/tests/test_continuous_quiet.py b/python/tests/test_continuous_quiet.py index 1196bc9..62d3c53 100644 --- a/python/tests/test_continuous_quiet.py +++ b/python/tests/test_continuous_quiet.py @@ -258,3 +258,20 @@ async def test_revision_two_snapshot_and_mixed_tail_rebuild_end_times() -> None: finally: await attend.stop() await store.close() + + +async def test_explicit_duration_ignores_unused_infinite_default_gap() -> None: + clock = fake_clock(100) + judge = scripted_judge([{"route": "queue"}]) + attend = create_attend(clock=clock, kind={"move": "continuous"}, settle={"stream_gap_ms": float("inf")}, judge=judge, sink="log") + running = asyncio.create_task(attend.run()) + try: + await attend.push("s", {"id": "a", "name": "move", "quietForMs": 40}) + record = await attend.inspect("s") + assert record is not None and record["dueAt"] == 140 + await clock.advance(40) + assert [call["window"]["settledAt"] for call in judge.calls] == [140] + finally: + await attend.stop() + await running + await attend.store.close() diff --git a/test/continuous-quiet.test.ts b/test/continuous-quiet.test.ts index 2453a68..62bb482 100644 --- a/test/continuous-quiet.test.ts +++ b/test/continuous-quiet.test.ts @@ -62,7 +62,7 @@ test('other triggers remain independent of continuous durations', () => { expect(deadline({ ...DEFAULT_POLICY, maxEvents: 0 }, buffer(move))).toEqual({ at: 100, reason: 'overflow' }); }); -test.each([null, true, '10', NaN, Infinity, -Infinity, -1])('invalid duration %s refuses the whole batch', async (quietForMs) => { +test.each([null, true, '10', NaN, Infinity, -Infinity, -1, Symbol('duration'), () => 40, { toJSON: () => undefined }])('invalid duration %s refuses the whole batch', async (quietForMs) => { const attend = createAttend({ clock: fakeClock(100), kind: { move: 'continuous' }, judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); try { // Decoded JavaScript input can violate the declared public type. @@ -74,6 +74,22 @@ test.each([null, true, '10', NaN, Infinity, -Infinity, -1])('invalid duration %s } }); +test('an explicit duration ignores an unused infinite default gap', async () => { + const clock = fakeClock(100); + const judge = scriptedJudge([{ route: 'queue' }]); + const attend = createAttend({ clock, kind: { move: 'continuous' }, settle: { streamGapMs: Infinity }, judge, sink: 'log' }); + const running = attend.run(); + try { + await attend.push('s', { id: 'a', name: 'move', quietForMs: 40 }); + expect((await attend.inspect('s'))?.dueAt).toBe(140); + await clock.advance(40); + expect(judge.calls.map((call) => call.window.settledAt)).toEqual([140]); + } finally { + await attend.stop(); + await running; + } +}); + test.each(KINDS.filter((kind) => kind !== 'continuous'))('duration on %s refuses the whole batch', async (kind) => { const attend = createAttend({ clock: fakeClock(100), kind: (event) => event.name === 'move' ? 'continuous' : kind, judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); try { From b2332348f85e8b8250778652114a4e8709ad23cb Mon Sep 17 00:00:00 2001 From: asher-aqi Date: Thu, 12 Nov 2026 01:19:54 -0600 Subject: [PATCH 4/4] fix(clock): reject omitted durations and ignore absent defaults Validate captured duration fields before JSON can erase them. Exclude the missing default-duration group from deadline arithmetic, so an unused infinite policy gap cannot suppress an explicit deadline. --- python/src/aqi_attend/core/window.py | 11 ++++++----- src/core/window.ts | 7 ++++--- src/internal/shared.ts | 1 + 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/python/src/aqi_attend/core/window.py b/python/src/aqi_attend/core/window.py index e66fa0a..f3fffe7 100644 --- a/python/src/aqi_attend/core/window.py +++ b/python/src/aqi_attend/core/window.py @@ -271,11 +271,12 @@ def window_deadline(policy: SettlePolicy, open: OpenWindow) -> tuple[float, Sett if not math.isnan(s.last_closing_at) and (reason is None or closing < at): at = closing reason = "closing" - stream = ( - s.last_stream_at + policy["streamGapMs"] - if s.max_explicit_stream_end_at == -math.inf - else _max(s.max_explicit_stream_end_at, s.max_default_stream_at + policy["streamGapMs"]) - ) + if s.max_explicit_stream_end_at == -math.inf: + stream = s.last_stream_at + policy["streamGapMs"] + elif s.max_default_stream_at == -math.inf: + stream = s.max_explicit_stream_end_at + else: + stream = _max(s.max_explicit_stream_end_at, s.max_default_stream_at + policy["streamGapMs"]) if not math.isnan(s.last_stream_at) and (reason is None or stream < at): at = stream reason = "stream_quiet" diff --git a/src/core/window.ts b/src/core/window.ts index c185173..2cd51c5 100644 --- a/src/core/window.ts +++ b/src/core/window.ts @@ -279,9 +279,10 @@ export function windowDeadline(policy: SettlePolicy, open: OpenWindow): { at: nu at = closing; reason = 'closing'; } - const stream = s.maxExplicitStreamEndAt === -Infinity - ? s.lastStreamAt + policy.streamGapMs - : Math.max(s.maxExplicitStreamEndAt, s.maxDefaultStreamAt + policy.streamGapMs); + let stream: number; + if (s.maxExplicitStreamEndAt === -Infinity) stream = s.lastStreamAt + policy.streamGapMs; + else if (s.maxDefaultStreamAt === -Infinity) stream = s.maxExplicitStreamEndAt; + else stream = Math.max(s.maxExplicitStreamEndAt, s.maxDefaultStreamAt + policy.streamGapMs); if (!Number.isNaN(s.lastStreamAt) && (reason === null || stream < at)) { at = stream; reason = 'stream_quiet'; diff --git a/src/internal/shared.ts b/src/internal/shared.ts index c0711b9..1eddad3 100644 --- a/src/internal/shared.ts +++ b/src/internal/shared.ts @@ -71,6 +71,7 @@ function copyObject(value: object, key: string | number, depth: number): JsonVal for (const name of keys(source)) { const field = source[name]; if (depth === 0 && name === 'observedAt') checkObservation(field); + if (depth === 0 && name === 'quietForMs') checkQuietDuration(field); const copied = toJson(field, name, depth + 1); if (copied === undefined) continue; if (name === '__proto__') defineProperty(object, name, { value: copied, enumerable: true, writable: true, configurable: true });