From 11385df995e16deb2fe6c0c3798ea4b904db76ff Mon Sep 17 00:00:00 2001 From: twoimo Date: Sat, 24 Oct 2026 17:38:22 +0900 Subject: [PATCH] fix(collection): watch inputs beyond first 200 targets --- .../realtime-scan-coverage-20261024.md | 75 +++++++++++++++++++ scripts/alden_realtime_collection.py | 47 +++++++----- tests/test_alden_realtime_collection.py | 58 ++++++++++++++ 3 files changed, 160 insertions(+), 20 deletions(-) create mode 100644 docs/evaluation/realtime-scan-coverage-20261024.md diff --git a/docs/evaluation/realtime-scan-coverage-20261024.md b/docs/evaluation/realtime-scan-coverage-20261024.md new file mode 100644 index 00000000..04daaf1d --- /dev/null +++ b/docs/evaluation/realtime-scan-coverage-20261024.md @@ -0,0 +1,75 @@ +# Realtime target coverage beyond the first 200 + +The input watcher repeatedly selected the first 200 eligible target IDs. With 201 +permitted, enabled targets, the last target was never observed by this watcher, +even after its source changed. Its ordinary collection schedule could still run; +this defect concerns input-triggered collection, not all collection. + +`RealtimeCollection.scan` now walks keyset pages of 200 IDs, committing each page +before continuing. It releases the collection-store read before inspecting files +or writing observation hints. The page size limits temporary ID storage rather +than the supported target set. Existing debounce, coalescing, acknowledgement, +permission, pause, and scheduler publication rules remain in place. A changed +live-policy revision stops traversal before the next page. + +```mermaid +stateDiagram-v2 + [*] --> Unseen + Unseen --> Settling: permitted input observed + Settling --> Settling: signature changes + Settling --> Queued: same signature after settle interval + Queued --> Queued: duplicate observation + Queued --> Processed: scheduler publishes and acknowledges current signature + Processed --> Settling: source signature changes + Settling --> InputError: missing or unsafe input + Queued --> InputError: missing or unsafe input + InputError --> Settling: valid input observed again +``` + +This diagram describes existing observation states, not an implementation proof. +For a fixed eligible registry, the cursor advances past a page only after that +page's observation transaction commits. A later failure leaves earlier pages +durable and the next watch tick starts again from the beginning. Registration or +permission changes during traversal do not have a single snapshot guarantee; +later ticks reconcile them. Scheduler publication gates remain authoritative. + +For N eligible targets, a complete unchanged-registry, unchanged-policy pass has N +eligible ID visits (paused inputs may be skipped) and `ceil(N/200) + 1` page queries, +including the terminal empty query. Each observed target +also performs its existing target lookup, permission lookup, file metadata checks, +and realtime-state lookup/update. At most 200 IDs are held in the scan's page list. +This is not an O(200) memory claim for the entire watcher: `pending()` and scheduler +candidate collections still grow with their respective target sets. There is no +fixed elapsed-time or arbitrarily large-scale realtime guarantee. No production +speedup, FPS, RAM, or battery improvement is claimed. + +Validation uses isolated real SQLite stores and files with a fake dense index: + +- 401 eligible targets span three nonempty pages. The last target publishes its + first version, detects another source change, publishes a second version, then + remains acknowledged without requeue. Other pending hints and all intervals are + preserved. +- A 203-target fixture excludes disabled, denied, and paused targets, including + traversal beyond the first page. +- A controlled policy-revision response stops before page two; a subsequent + normal pass resumes and settles all 201 inputs. This policy-boundary test is + synthetic, not a concurrent OS-policy proof. +- The realtime collection, watch-state, and scheduler suites pass 46 tests. +- The final 401-target regression run with the exact installed scanner method + fails with `200 != 401`. This negative control uses isolated candidate fixture + dependencies; it does not execute a production collector or alter installed + bytes. + +The actual installed app has 43 declared/eligible targets. A read-only observation +found 43 realtime inputs, no input errors or queued hints, and a fresh heartbeat +from its existing collection process. Its separate OSK producer checkpoint was +older, with `collection=pending` and `saved_corpus_ready=false`; the primary GUI +process was not running. The source shows OSK synchronization belongs to the +desktop process, while the launch agent owns collection watching. This separates +the two observations; it neither proves why the GUI exited nor identifies this +200-target defect as the cause of that stale checkpoint. + +This is an uninstalled candidate on frozen source +`3407c08e8e3bdf14b378735bb7048e4398dbaede`. Current-source external review, +integration with the other candidates, canonical build/sign/install, native +background QA, and production-source observation remain separate delivery gates. diff --git a/scripts/alden_realtime_collection.py b/scripts/alden_realtime_collection.py index ad5cf0a1..402c9c7e 100644 --- a/scripts/alden_realtime_collection.py +++ b/scripts/alden_realtime_collection.py @@ -100,27 +100,34 @@ def signature(target): return hashlib.sha256(json.dumps([str(path), stamps], separators=(',', ':')).encode()).hexdigest() def scan(self, store, *, paused=lambda _id: False, now=None): - if not self.policy()['enabled']: return 0 + policy = self.policy() + if not policy['enabled']: return 0 now = time.time() if now is None else now - with store.database() as source: - ids = [r[0] for r in source.execute('''SELECT t.id FROM targets t WHERE t.enabled=1 AND - EXISTS(SELECT 1 FROM target_projects p WHERE p.target_id=t.id AND p.permission!='denied') ORDER BY t.id LIMIT 200''')] - with self.database(write=True) as db: - for target_id in ids: - if paused(target_id): continue - try: signature, error = self.signature(store.target(target_id)), None - except (OSError, KeyError, ValueError) as exc: - signature, error = None, str(exc) if str(exc).startswith('collection_realtime_') else 'collection_realtime_input_unavailable' - row = db.execute('SELECT * FROM inputs WHERE target_id=?', (target_id,)).fetchone() - if row is None: - db.execute('INSERT INTO inputs VALUES(?,?,?,NULL,NULL,NULL,NULL,?)', (target_id, signature, now, error)) - elif error: - if row['error'] != error: db.execute('UPDATE inputs SET error=? WHERE target_id=?', (error, target_id)) - elif row['seen'] != signature or row['error']: - db.execute('UPDATE inputs SET seen=?,stable_since=?,error=NULL WHERE target_id=?', (signature, now, target_id)) - elif now - row['stable_since'] >= SETTLE_SECONDS and signature != row['processed'] and signature != row['queued']: - db.execute('UPDATE inputs SET queued=?,queued_at=COALESCE(queued_at,?) WHERE target_id=?', (signature, now, target_id)) - return len(ids) + after, scanned = '', 0 + while True: + # The page size bounds temporary IDs, not the supported target set. + # Release the source read before observing files or writing hints. + with store.database() as source: + ids = [r[0] for r in source.execute('''SELECT t.id FROM targets t WHERE t.id>? AND t.enabled=1 AND + EXISTS(SELECT 1 FROM target_projects p WHERE p.target_id=t.id AND p.permission!='denied') + ORDER BY t.id LIMIT 200''', (after,))] + if not ids or self.policy() != policy: return scanned + with self.database(write=True) as db: + for target_id in ids: + if paused(target_id): continue + try: signature, error = self.signature(store.target(target_id)), None + except (OSError, KeyError, ValueError) as exc: + signature, error = None, str(exc) if str(exc).startswith('collection_realtime_') else 'collection_realtime_input_unavailable' + row = db.execute('SELECT * FROM inputs WHERE target_id=?', (target_id,)).fetchone() + if row is None: + db.execute('INSERT INTO inputs VALUES(?,?,?,NULL,NULL,NULL,NULL,?)', (target_id, signature, now, error)) + elif error: + if row['error'] != error: db.execute('UPDATE inputs SET error=? WHERE target_id=?', (error, target_id)) + elif row['seen'] != signature or row['error']: + db.execute('UPDATE inputs SET seen=?,stable_since=?,error=NULL WHERE target_id=?', (signature, now, target_id)) + elif now - row['stable_since'] >= SETTLE_SECONDS and signature != row['processed'] and signature != row['queued']: + db.execute('UPDATE inputs SET queued=?,queued_at=COALESCE(queued_at,?) WHERE target_id=?', (signature, now, target_id)) + after, scanned = ids[-1], scanned + len(ids) def pending(self): if not self.policy()['enabled']: return {} diff --git a/tests/test_alden_realtime_collection.py b/tests/test_alden_realtime_collection.py index 2de66008..63bf4a22 100644 --- a/tests/test_alden_realtime_collection.py +++ b/tests/test_alden_realtime_collection.py @@ -45,6 +45,64 @@ def cycle(self, **changes): return self.scheduler.cycle(collector=collect_target, capturer=capture_source, indexer=changes.pop('indexer', lambda *a, **kw: {'state': 'ready'}), **changes) + def test_input_after_first_200_targets_is_collected_and_requeued_on_change(self): + eligible = {self.target} + for number in range(400): + eligible.add(self.store.register(platform='graph', original_id=f'large-live-{number}', + kind='graph_source', label='fixture', projects=['allowed'], + config={'adapter': 'source-graph', 'path': str(self.source)}, interval_seconds=21600)) + with self.store.database() as db: + tail = db.execute('SELECT id FROM targets ORDER BY id DESC LIMIT 1').fetchone()[0] + self.enable() + self.assertEqual(self.live.scan(self.store, now=100), 401) + self.assertEqual(self.live.scan(self.store, now=103), 401) + queued = self.live.pending() + self.assertEqual(set(queued), eligible) + self.assertEqual(self.cycle(target_id=tail)['attempts'][0]['state'], 'complete') + self.assertEqual(set(self.live.pending()), eligible - {tail}) + self.write('200개 뒤 대상의 새 원문') + self.queue(200) + self.assertNotEqual(self.live.pending()[tail]['queued'], queued[tail]['queued']) + self.assertEqual(self.cycle(target_id=tail)['attempts'][0]['state'], 'complete') + with self.store.database() as db: + self.assertEqual(db.execute('SELECT COUNT(*) FROM versions').fetchone()[0], 2) + self.assertEqual(db.execute('SELECT COUNT(*) FROM targets WHERE interval_seconds=21600').fetchone()[0], 401) + self.live.scan(self.store, now=210) + self.assertNotIn(tail, self.live.pending()) + + def test_page_traversal_keeps_disabled_denied_and_paused_targets_out(self): + eligible = {self.target} + for number in range(202): + eligible.add(self.store.register(platform='graph', original_id=f'scoped-live-{number}', + kind='graph_source', label='fixture', projects=['allowed'], + config={'adapter': 'source-graph', 'path': str(self.source)}, interval_seconds=21600)) + disabled, denied, paused = sorted(eligible)[:3] + with self.store.database() as db: + db.execute('UPDATE targets SET enabled=0 WHERE id=?', (disabled,)) + db.execute("UPDATE target_projects SET permission='denied' WHERE target_id=?", (denied,)) + self.scheduler.pause(True, paused) + self.enable(); self.queue() + self.assertEqual(set(self.live.pending()), eligible - {disabled, denied, paused}) + with self.live.database() as db: + observed = {row[0] for row in db.execute('SELECT target_id FROM inputs')} + self.assertEqual(observed, eligible - {disabled, denied, paused}) + + def test_live_policy_revision_change_stops_before_next_page(self): + for number in range(200): + self.store.register(platform='graph', original_id=f'policy-live-{number}', + kind='graph_source', label='fixture', projects=['allowed'], + config={'adapter': 'source-graph', 'path': str(self.source)}, interval_seconds=21600) + self.enable() + with patch.object(self.live, 'policy', side_effect=[ + {'enabled': True, 'revision': 1}, {'enabled': True, 'revision': 1}, + {'enabled': False, 'revision': 2}]): + self.assertEqual(self.live.scan(self.store, now=100), 200) + with self.live.database() as db: + self.assertEqual(db.execute('SELECT COUNT(*) FROM inputs').fetchone()[0], 200) + self.assertEqual(self.live.scan(self.store, now=103), 201) + self.assertEqual(self.live.scan(self.store, now=106), 201) + self.assertEqual(len(self.live.pending()), 201) + def test_default_read_is_side_effect_free_and_policy_cas_is_recoverable(self): self.assertFalse(self.live.policy()['enabled']) self.assertFalse(self.live.path.exists())