-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_parser.py
More file actions
9129 lines (7908 loc) · 343 KB
/
test_parser.py
File metadata and controls
9129 lines (7908 loc) · 343 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Tests for copilot_usage.parser — session discovery, parsing, and summary."""
# pyright: reportPrivateUsage=false
import builtins
import io
import json
import os
import time
from collections.abc import Iterator
from datetime import UTC, datetime
from pathlib import Path
from typing import SupportsIndex, overload
from unittest.mock import patch
import pytest
from pydantic import ValidationError
import copilot_usage.parser as _parser_module
from copilot_usage._fs_utils import safe_file_identity
from copilot_usage.models import (
AssistantMessageData,
EventType,
GenericEventData,
ModelMetrics,
RequestMetrics,
SessionContext,
SessionEvent,
SessionShutdownData,
SessionStartData,
SessionSummary,
TokenUsage,
ToolExecutionData,
ToolRequest,
ToolTelemetry,
UserMessageData,
)
from copilot_usage.parser import (
_DISCOVERY_CACHE,
_EVENTS_CACHE,
_FIRST_PASS_EVENT_TYPES,
_MAX_CACHED_EVENTS,
_MAX_CACHED_SESSIONS,
_MAX_PLAN_PROBES,
_SESSION_CACHE,
DEFAULT_SESSION_PATH,
_build_active_summary,
_build_completed_summary,
_CachedEvents,
_CachedSession,
_CopilotConfig,
_detect_resume,
_discover_with_identity,
_extract_output_tokens,
_extract_session_name,
_first_pass,
_FirstPassResult,
_infer_model_from_metrics,
_insert_session_entry,
_read_config_model,
_ResumeInfo,
build_session_summary,
discover_sessions,
get_all_sessions,
get_cached_events,
parse_events,
)
def _reset_all_caches() -> None:
"""Clear all module-level caches (shared between fixture and tests)."""
_SESSION_CACHE.clear()
_EVENTS_CACHE.clear()
_DISCOVERY_CACHE.clear()
_read_config_model.cache_clear()
_parser_module._config_file_id = None
_parser_module._sorted_sessions_cache = None
@pytest.fixture(autouse=True)
def _clear_session_cache() -> None:
"""Isolate tests from all module-level caches."""
_reset_all_caches()
# ---------------------------------------------------------------------------
# Fixtures — synthetic events.jsonl content
# ---------------------------------------------------------------------------
_START_EVENT = json.dumps(
{
"type": "session.start",
"data": {
"sessionId": "test-session-001",
"version": 1,
"producer": "copilot-agent",
"copilotVersion": "1.0.0",
"startTime": "2026-03-07T10:00:00.000Z",
"context": {"cwd": "/home/user/project"},
},
"id": "ev-start",
"timestamp": "2026-03-07T10:00:00.000Z",
"parentId": None,
}
)
_USER_MSG = json.dumps(
{
"type": "user.message",
"data": {
"content": "hello",
"transformedContent": "hello",
"attachments": [],
"interactionId": "int-1",
},
"id": "ev-user1",
"timestamp": "2026-03-07T10:01:00.000Z",
"parentId": "ev-start",
}
)
_ASSISTANT_MSG = json.dumps(
{
"type": "assistant.message",
"data": {
"messageId": "msg-1",
"content": "hi there",
"toolRequests": [],
"interactionId": "int-1",
"outputTokens": 150,
},
"id": "ev-asst1",
"timestamp": "2026-03-07T10:01:05.000Z",
"parentId": "ev-user1",
}
)
_ASSISTANT_MSG_2 = json.dumps(
{
"type": "assistant.message",
"data": {
"messageId": "msg-2",
"content": "more content",
"toolRequests": [],
"interactionId": "int-1",
"outputTokens": 200,
},
"id": "ev-asst2",
"timestamp": "2026-03-07T10:01:10.000Z",
"parentId": "ev-asst1",
}
)
_TOOL_EXEC = json.dumps(
{
"type": "tool.execution_complete",
"data": {
"toolCallId": "tc-1",
"model": "claude-sonnet-4",
"interactionId": "int-1",
"success": True,
},
"id": "ev-tool1",
"timestamp": "2026-03-07T10:01:07.000Z",
"parentId": "ev-asst1",
}
)
_TURN_START_1 = json.dumps(
{
"type": "assistant.turn_start",
"data": {"turnId": "0", "interactionId": "int-1"},
"id": "ev-turn-start-1",
"timestamp": "2026-03-07T10:01:01.000Z",
"parentId": "ev-user1",
}
)
_TURN_START_2 = json.dumps(
{
"type": "assistant.turn_start",
"data": {"turnId": "1", "interactionId": "int-1"},
"id": "ev-turn-start-2",
"timestamp": "2026-03-07T10:01:08.000Z",
"parentId": "ev-asst1",
}
)
_SHUTDOWN_EVENT = json.dumps(
{
"type": "session.shutdown",
"data": {
"shutdownType": "routine",
"totalPremiumRequests": 5,
"totalApiDurationMs": 12000,
"sessionStartTime": 1772895600000,
"codeChanges": {
"linesAdded": 50,
"linesRemoved": 10,
"filesModified": ["a.py", "b.py"],
},
"modelMetrics": {
"claude-sonnet-4": {
"requests": {"count": 8, "cost": 5},
"usage": {
"inputTokens": 5000,
"outputTokens": 350,
"cacheReadTokens": 1000,
"cacheWriteTokens": 0,
},
}
},
"currentModel": "claude-sonnet-4",
},
"id": "ev-shutdown",
"timestamp": "2026-03-07T11:00:00.000Z",
"parentId": "ev-asst2",
"currentModel": "claude-sonnet-4",
}
)
_RESUME_EVENT = json.dumps(
{
"type": "session.resume",
"data": {},
"id": "ev-resume",
"timestamp": "2026-03-07T12:00:00.000Z",
"parentId": "ev-shutdown",
}
)
_POST_RESUME_USER_MSG = json.dumps(
{
"type": "user.message",
"data": {
"content": "continue working",
"transformedContent": "continue working",
"attachments": [],
"interactionId": "int-2",
},
"id": "ev-user2",
"timestamp": "2026-03-07T12:01:00.000Z",
"parentId": "ev-resume",
}
)
_POST_RESUME_ASSISTANT_MSG = json.dumps(
{
"type": "assistant.message",
"data": {
"messageId": "msg-3",
"content": "resuming work",
"toolRequests": [],
"interactionId": "int-2",
"outputTokens": 250,
},
"id": "ev-asst3",
"timestamp": "2026-03-07T12:01:05.000Z",
"parentId": "ev-user2",
}
)
_POST_RESUME_TURN_START = json.dumps(
{
"type": "assistant.turn_start",
"data": {"turnId": "2", "interactionId": "int-2"},
"id": "ev-turn-start-post-resume",
"timestamp": "2026-03-07T12:01:01.000Z",
"parentId": "ev-user2",
}
)
_SHUTDOWN_EVENT_2 = json.dumps(
{
"type": "session.shutdown",
"data": {
"shutdownType": "routine",
"totalPremiumRequests": 10,
"totalApiDurationMs": 20000,
"sessionStartTime": 1772895600000,
"codeChanges": {
"linesAdded": 80,
"linesRemoved": 20,
"filesModified": ["a.py", "b.py", "c.py"],
},
"modelMetrics": {
"claude-sonnet-4": {
"requests": {"count": 15, "cost": 10},
"usage": {
"inputTokens": 9000,
"outputTokens": 700,
"cacheReadTokens": 2000,
"cacheWriteTokens": 0,
},
}
},
"currentModel": "claude-sonnet-4",
},
"id": "ev-shutdown-2",
"timestamp": "2026-03-07T13:00:00.000Z",
"parentId": "ev-asst3",
"currentModel": "claude-sonnet-4",
}
)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _write_events(path: Path, *lines: str) -> Path:
"""Write event lines to an events.jsonl file and return the path."""
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
return path
def _make_completed_session(base: Path, name: str, sid: str) -> Path:
"""Create a completed session directory and return the events.jsonl path.
Writes start, user-message, and shutdown events — the minimal set
required to produce a valid completed ``SessionSummary``.
"""
start = json.dumps(
{
"type": "session.start",
"data": {
"sessionId": sid,
"version": 1,
"startTime": "2026-03-07T10:00:00.000Z",
"context": {"cwd": "/"},
},
"id": f"ev-{sid}",
"timestamp": "2026-03-07T10:00:00.000Z",
}
)
user = json.dumps(
{
"type": "user.message",
"data": {
"content": "hi",
"transformedContent": "hi",
"attachments": [],
"interactionId": "int-1",
},
"id": f"ev-u-{sid}",
"timestamp": "2026-03-07T10:01:00.000Z",
}
)
shutdown = json.dumps(
{
"type": "session.shutdown",
"data": {
"shutdownType": "routine",
"totalPremiumRequests": 1,
"totalApiDurationMs": 500,
"sessionStartTime": 1772895600000,
"modelMetrics": {
"gpt-5.1": {
"requests": {"count": 1, "cost": 1},
"usage": {"outputTokens": 50},
}
},
},
"id": f"ev-sd-{sid}",
"timestamp": "2026-03-07T10:05:00.000Z",
}
)
return _write_events(base / name / "events.jsonl", start, user, shutdown)
def _completed_events(
tmp_path: Path,
) -> tuple[list[SessionEvent], Path]:
p = tmp_path / "s" / "events.jsonl"
_write_events(
p,
_START_EVENT,
_USER_MSG,
_ASSISTANT_MSG,
_ASSISTANT_MSG_2,
_SHUTDOWN_EVENT,
)
return parse_events(p), p.parent
def _active_events(
tmp_path: Path,
) -> tuple[list[SessionEvent], Path]:
p = tmp_path / "s" / "events.jsonl"
_write_events(
p,
_START_EVENT,
_USER_MSG,
_ASSISTANT_MSG,
_ASSISTANT_MSG_2,
_TOOL_EXEC,
)
return parse_events(p), p.parent
# ---------------------------------------------------------------------------
# discover_sessions
# ---------------------------------------------------------------------------
class TestDiscoverSessions:
def test_finds_sessions(self, tmp_path: Path) -> None:
s1 = tmp_path / "session-a" / "events.jsonl"
s2 = tmp_path / "session-b" / "events.jsonl"
_write_events(s1, _START_EVENT)
_write_events(s2, _START_EVENT)
result = discover_sessions(tmp_path)
assert len(result) == 2
assert all(p.name == "events.jsonl" for p in result)
def test_sorted_newest_first(self, tmp_path: Path) -> None:
older = tmp_path / "old" / "events.jsonl"
newer = tmp_path / "new" / "events.jsonl"
_write_events(older, _START_EVENT)
time.sleep(0.05)
_write_events(newer, _START_EVENT)
result = discover_sessions(tmp_path)
assert result[0] == newer
def test_empty_directory(self, tmp_path: Path) -> None:
assert discover_sessions(tmp_path) == []
def test_nonexistent_directory(self, tmp_path: Path) -> None:
assert discover_sessions(tmp_path / "nope") == []
def test_regular_file_returns_empty(self, tmp_path: Path) -> None:
"""Passing an existing file (not a directory) → returns []."""
some_file = tmp_path / "some_file.txt"
some_file.write_text("not a directory", encoding="utf-8")
assert discover_sessions(some_file) == []
def test_stat_race_file_deleted_between_glob_and_sort(self, tmp_path: Path) -> None:
"""TOCTOU: session dir deleted after glob but before stat()."""
s1 = tmp_path / "session-a" / "events.jsonl"
s2 = tmp_path / "session-b" / "events.jsonl"
_write_events(s1, _START_EVENT)
_write_events(s2, _START_EVENT)
original_stat = Path.stat
def _flaky_stat(self: Path) -> object:
if self == s1:
raise FileNotFoundError(f"deleted: {self}")
return original_stat(self)
with patch.object(Path, "stat", _flaky_stat):
result = discover_sessions(tmp_path)
# s1 is excluded (FileNotFoundError → pruned); s2 still returned.
assert result == [s2]
def test_stat_race_permission_error(self, tmp_path: Path) -> None:
"""discover_sessions skips sessions whose events.jsonl is unreadable."""
s1 = tmp_path / "sess-a" / "events.jsonl"
_write_events(s1, _START_EVENT)
original_stat = Path.stat
def _flaky_stat(self: Path, **kwargs: object) -> object:
if self.name == "events.jsonl":
raise PermissionError("denied")
return original_stat(self)
with patch.object(Path, "stat", _flaky_stat):
result = discover_sessions(tmp_path)
# Session with unreadable events.jsonl is skipped, not crashed
assert result == []
def test_get_all_sessions_skips_vanished_session(self, tmp_path: Path) -> None:
"""TOCTOU: events.jsonl deleted after discover but before parse."""
s1 = tmp_path / "session-a" / "events.jsonl"
s2 = tmp_path / "session-b" / "events.jsonl"
_write_events(s1, _START_EVENT)
_write_events(s2, _START_EVENT)
original_open = Path.open
def _flaky_open(self: Path, *args: object, **kwargs: object) -> object: # type: ignore[override]
if self == s1:
raise FileNotFoundError(f"deleted: {self}")
return original_open(self, *args, **kwargs) # type: ignore[arg-type]
with patch.object(Path, "open", _flaky_open):
summaries = get_all_sessions(tmp_path)
# Only s2 should produce a summary
assert len(summaries) == 1
# ---------------------------------------------------------------------------
# discover_sessions — depth contract
# ---------------------------------------------------------------------------
class TestDiscoverSessionsDepth:
"""Regression: discover_sessions must only scan one directory level."""
def test_two_level_deep_events_not_discovered(self, tmp_path: Path) -> None:
"""A nested ``deeply/nested/events.jsonl`` must NOT be discovered."""
# Two-level deep file — should be excluded
deep = tmp_path / "deeply" / "nested" / "events.jsonl"
_write_events(deep, _START_EVENT)
# One-level deep file — should be included
valid = tmp_path / "valid-session" / "events.jsonl"
_write_events(valid, _START_EVENT)
result = get_all_sessions(base_path=tmp_path)
assert len(result) == 1
assert result[0].session_id == "test-session-001"
# Also verify via discover_sessions directly
paths = discover_sessions(tmp_path)
assert paths == [valid]
# ---------------------------------------------------------------------------
# _discover_with_identity — no stat for absent plan.md (issue #763)
# ---------------------------------------------------------------------------
class TestDiscoverWithIdentityNoAbsentPlanStat:
"""os.scandir-based discovery must not stat absent plan.md files."""
def test_no_stat_for_absent_plan_md(self, tmp_path: Path) -> None:
"""No stat() call is made for a non-existent plan.md path.
Creates 100 sessions where only 10 have plan.md. Patches
``safe_file_identity`` to count calls and asserts that the call
count equals exactly 1 (root directory) + 10 (existing plan.md).
``events.jsonl`` uses direct ``Path.stat()`` rather than
``safe_file_identity``, and absent plan.md files are not probed
on fresh discovery.
"""
n_total = 100
n_with_plan = 10
for i in range(n_total):
session_dir = tmp_path / f"sess-{i:04d}"
events = session_dir / "events.jsonl"
_write_events(events, _START_EVENT)
if i < n_with_plan:
(session_dir / "plan.md").write_text(
f"# Session {i}\n", encoding="utf-8"
)
with patch(
"copilot_usage.parser.safe_file_identity", wraps=safe_file_identity
) as spy:
_, _, result = _discover_with_identity(tmp_path)
assert len(result) == n_total
# 1 call for root directory + n_with_plan for existing plan.md.
# events.jsonl uses direct stat() rather than safe_file_identity,
# and absent plan.md files are not probed on fresh discovery.
assert spy.call_count == 1 + n_with_plan
def test_plan_id_populated_when_present(self, tmp_path: Path) -> None:
"""plan_id is non-None only for sessions that have plan.md on disk."""
for i in range(5):
session_dir = tmp_path / f"sess-{i}"
_write_events(session_dir / "events.jsonl", _START_EVENT)
# Add plan.md to only the first session
(tmp_path / "sess-0" / "plan.md").write_text("# Plan\n", encoding="utf-8")
_, _, result = _discover_with_identity(tmp_path)
plans = {p.parent.name: pid for p, _eid, pid in result}
assert plans["sess-0"] is not None
for i in range(1, 5):
assert plans[f"sess-{i}"] is None
def test_include_plan_false_skips_all_plan_stat(self, tmp_path: Path) -> None:
"""When include_plan=False, plan.md stat is skipped even if file exists."""
session_dir = tmp_path / "sess-a"
_write_events(session_dir / "events.jsonl", _START_EVENT)
(session_dir / "plan.md").write_text("# Plan\n", encoding="utf-8")
with patch(
"copilot_usage.parser.safe_file_identity", wraps=safe_file_identity
) as spy:
_, _, result = _discover_with_identity(tmp_path, include_plan=False)
assert len(result) == 1
assert result[0][2] is None # plan_id is None
# 1 call for root directory only; events.jsonl uses direct stat()
# and include_plan=False skips all plan.md stat calls.
assert spy.call_count == 1
def test_scandir_root_oserror_returns_empty(self, tmp_path: Path) -> None:
"""Return [] when os.scandir on the root directory raises OSError."""
session_dir = tmp_path / "sess-x"
_write_events(session_dir / "events.jsonl", _START_EVENT)
original_scandir = os.scandir
def _bomb(path: str | os.PathLike[str]) -> Iterator[os.DirEntry[str]]:
if str(path) == str(tmp_path):
raise OSError("permission denied")
return original_scandir(path)
with patch("copilot_usage.parser.os.scandir", side_effect=_bomb):
_, _, result = _discover_with_identity(tmp_path)
assert result == []
def test_scandir_session_dir_oserror_skips_entry(self, tmp_path: Path) -> None:
"""Skip a session directory when os.scandir on it raises OSError."""
good = tmp_path / "sess-good"
_write_events(good / "events.jsonl", _START_EVENT)
bad = tmp_path / "sess-bad"
_write_events(bad / "events.jsonl", _START_EVENT)
original_scandir = os.scandir
def _bomb(path: str | os.PathLike[str]) -> Iterator[os.DirEntry[str]]:
if str(path) == str(bad):
raise OSError("permission denied")
return original_scandir(path)
with patch("copilot_usage.parser.os.scandir", side_effect=_bomb):
_, _, result = _discover_with_identity(tmp_path)
assert len(result) == 1
assert result[0][0].parent.name == "sess-good"
# ---------------------------------------------------------------------------
# _discover_with_identity — linear scan (issue #773)
# ---------------------------------------------------------------------------
class TestDiscoverWithIdentityLinearScan:
"""Verify linear scan returns correct tuples for many session dirs."""
def test_120_sessions_correct_tuples(self, tmp_path: Path) -> None:
"""120 session dirs return correct (events_path, events_id, plan_id).
Creates 120 session directories: 40 with plan.md (plus extra files),
80 without. Asserts that every session is returned with the correct
events_path and plan_id (non-None only when plan.md exists).
"""
n_total = 120
n_with_plan = 40
for i in range(n_total):
session_dir = tmp_path / f"sess-{i:04d}"
_write_events(session_dir / "events.jsonl", _START_EVENT)
# Add unrelated files to exercise the linear scan skip logic
(session_dir / "debug.log").write_text("log\n", encoding="utf-8")
(session_dir / "notes.txt").write_text("notes\n", encoding="utf-8")
if i < n_with_plan:
(session_dir / "plan.md").write_text(
f"# Session {i}\n", encoding="utf-8"
)
_, _, result = _discover_with_identity(tmp_path)
assert len(result) == n_total
lookup = {p.parent.name: (p, eid, pid) for p, eid, pid in result}
for i in range(n_total):
name = f"sess-{i:04d}"
assert name in lookup
events_path, events_id, plan_id = lookup[name]
assert events_path == tmp_path / name / "events.jsonl"
assert events_id is not None
if i < n_with_plan:
assert plan_id is not None
else:
assert plan_id is None
def test_plan_id_none_without_plan_md(self, tmp_path: Path) -> None:
"""Sessions without plan.md get plan_id=None."""
for i in range(5):
_write_events(tmp_path / f"sess-{i}" / "events.jsonl", _START_EVENT)
_, _, result = _discover_with_identity(tmp_path)
assert len(result) == 5
for _path, _eid, plan_id in result:
assert plan_id is None
def test_sessions_without_events_jsonl_skipped(self, tmp_path: Path) -> None:
"""Directories lacking events.jsonl are excluded from results."""
good = tmp_path / "sess-good"
_write_events(good / "events.jsonl", _START_EVENT)
empty = tmp_path / "sess-empty"
empty.mkdir()
(empty / "plan.md").write_text("# Plan\n", encoding="utf-8")
_, _, result = _discover_with_identity(tmp_path)
assert len(result) == 1
assert result[0][0].parent.name == "sess-good"
# ---------------------------------------------------------------------------
# _discover_with_identity — discovery cache (issue #809)
# ---------------------------------------------------------------------------
class TestDiscoverWithIdentityCache:
"""Root-directory identity caching skips inner os.scandir on repeat calls."""
def test_second_call_skips_inner_scandir(self, tmp_path: Path) -> None:
"""When root mtime is unchanged, cached discovery avoids os.scandir.
Creates 10 session subdirectories. The first call to
``_discover_with_identity`` populates the discovery cache. The
second call — with an unchanged root directory — checks root
identity via ``stat`` and reuses the cached entries list, so it
must issue zero ``os.scandir`` calls, including for the root.
"""
k = 10
for i in range(k):
_write_events(tmp_path / f"sess-{i:04d}" / "events.jsonl", _START_EVENT)
# First call — full discovery.
_, _, result1 = _discover_with_identity(tmp_path)
assert len(result1) == k
original_scandir = os.scandir
scandir_calls: list[str] = []
def _tracking_scandir(
path: str | os.PathLike[str],
) -> Iterator[os.DirEntry[str]]:
scandir_calls.append(str(path))
return original_scandir(path)
# Second call — root unchanged, cache should be used.
with patch("copilot_usage.parser.os.scandir", side_effect=_tracking_scandir):
_, _, result2 = _discover_with_identity(tmp_path)
assert len(result2) == k
# No os.scandir calls at all — the cached entries list is reused.
assert len(scandir_calls) == 0
def test_changed_events_detected_despite_cached_discovery(
self,
tmp_path: Path,
) -> None:
"""Mutating events.jsonl is detected even when inner scandir is cached.
After a cached second call, changing a session's events.jsonl
must still produce a different ``events_file_id`` because the
per-file ``stat`` call is always issued.
"""
k = 5
for i in range(k):
_write_events(tmp_path / f"sess-{i}" / "events.jsonl", _START_EVENT)
_, _, result1 = _discover_with_identity(tmp_path)
assert len(result1) == k
ids1 = {p.parent.name: eid for p, eid, _ in result1}
# Mutate one session's events.jsonl to change its file identity.
target = tmp_path / "sess-2" / "events.jsonl"
target.write_text(target.read_text(encoding="utf-8") + "\n", encoding="utf-8")
_, _, result2 = _discover_with_identity(tmp_path)
ids2 = {p.parent.name: eid for p, eid, _ in result2}
assert len(result2) == k
# The mutated session's identity must differ.
assert ids2["sess-2"] != ids1["sess-2"]
# Other sessions' identities remain unchanged.
for name in ("sess-0", "sess-1", "sess-3", "sess-4"):
assert ids2[name] == ids1[name]
def test_new_session_triggers_rescan(self, tmp_path: Path) -> None:
"""Adding a session directory changes root mtime and triggers rescan."""
for i in range(3):
_write_events(tmp_path / f"sess-{i}" / "events.jsonl", _START_EVENT)
_, _, result1 = _discover_with_identity(tmp_path)
assert len(result1) == 3
# Add a new session — this changes the root directory mtime.
_write_events(tmp_path / "sess-new" / "events.jsonl", _START_EVENT)
_, _, result2 = _discover_with_identity(tmp_path)
assert len(result2) == 4
names = {p.parent.name for p, _, _ in result2}
assert "sess-new" in names
def test_cache_invalidated_when_root_changes(self, tmp_path: Path) -> None:
"""Full rescan issues inner os.scandir calls when root mtime changes."""
for i in range(3):
_write_events(tmp_path / f"sess-{i}" / "events.jsonl", _START_EVENT)
# First call populates cache.
_discover_with_identity(tmp_path)
# Add a new session to change root mtime.
_write_events(tmp_path / "sess-new" / "events.jsonl", _START_EVENT)
original_scandir = os.scandir
scandir_calls: list[str] = []
def _tracking_scandir(
path: str | os.PathLike[str],
) -> Iterator[os.DirEntry[str]]:
scandir_calls.append(str(path))
return original_scandir(path)
with patch("copilot_usage.parser.os.scandir", side_effect=_tracking_scandir):
_, _, result = _discover_with_identity(tmp_path)
assert len(result) == 4
# Full rescan: root + inner per-session calls.
assert len(scandir_calls) >= 2
def test_include_plan_false_then_true_returns_plan_paths(
self,
tmp_path: Path,
) -> None:
"""Cache populated via include_plan=False still has plan paths.
The discovery cache always stores plan paths unconditionally.
A call with ``include_plan=False`` followed by ``include_plan=True``
must return non-None ``plan_id`` for sessions that have ``plan.md``.
"""
sess = tmp_path / "sess-0"
_write_events(sess / "events.jsonl", _START_EVENT)
plan = sess / "plan.md"
plan.write_text("# My Session\n", encoding="utf-8")
# First call with include_plan=False — populates cache.
_, _, result1 = _discover_with_identity(tmp_path, include_plan=False)
assert len(result1) == 1
assert result1[0][2] is None # plan_id omitted when include_plan=False
# Second call with include_plan=True — must use cached entries
# but still produce a valid plan_id.
_, _, result2 = _discover_with_identity(tmp_path, include_plan=True)
assert len(result2) == 1
assert result2[0][2] is not None # plan_id must be present
def test_deleted_events_jsonl_skipped_and_pruned_from_cache(
self,
tmp_path: Path,
) -> None:
"""Definitively-deleted events.jsonl is pruned from the cache.
When ``events.jsonl`` is deleted (``FileNotFoundError``) from a
session directory *without* changing the root directory mtime,
the entry must be excluded from the result and pruned from the
cached entries list so subsequent calls do not re-stat the
missing file.
"""
for i in range(3):
_write_events(tmp_path / f"sess-{i}" / "events.jsonl", _START_EVENT)
# Populate discovery cache.
_, _, result1 = _discover_with_identity(tmp_path)
assert len(result1) == 3
# Delete one session's events.jsonl without changing root mtime.
target = tmp_path / "sess-1" / "events.jsonl"
target.unlink()
_, _, result2 = _discover_with_identity(tmp_path)
names2 = {p.parent.name for p, _, _ in result2}
assert len(result2) == 2
assert "sess-1" not in names2
# The stale entry must be pruned from the cache so a third call
# also returns only 2 sessions (no repeated stat warnings).
_, _, result3 = _discover_with_identity(tmp_path)
assert len(result3) == 2
assert _DISCOVERY_CACHE[tmp_path] is not None
cached_paths = {ep for ep, _ in _DISCOVERY_CACHE[tmp_path].entries}
assert target not in cached_paths
def test_transient_permission_error_preserves_cache_entry(
self,
tmp_path: Path,
) -> None:
"""Transient PermissionError on events.jsonl keeps entry in cache.
When ``events.jsonl`` raises a non-``FileNotFoundError`` OSError
(e.g. ``PermissionError``), the entry is excluded from the
current result but *not* pruned from the cache — so the session
reappears once the file becomes readable again.
"""
for i in range(3):
_write_events(tmp_path / f"sess-{i}" / "events.jsonl", _START_EVENT)
_, _, result1 = _discover_with_identity(tmp_path)
assert len(result1) == 3
target = tmp_path / "sess-1" / "events.jsonl"
original_stat = Path.stat
def _permission_bomb(self: Path) -> os.stat_result:
if self == target:
raise PermissionError("transient")
return original_stat(self)
# Simulate transient PermissionError on one session.
with patch.object(Path, "stat", _permission_bomb):
_, _, result2 = _discover_with_identity(tmp_path)
assert len(result2) == 2
names2 = {p.parent.name for p, _, _ in result2}
assert "sess-1" not in names2
# Entry must still be in the cache.
cached_paths = {ep for ep, _ in _DISCOVERY_CACHE[tmp_path].entries}
assert target in cached_paths
# Once readable again, the session reappears.
_, _, result3 = _discover_with_identity(tmp_path)
assert len(result3) == 3
def test_deleted_plan_clears_cached_path(
self,
tmp_path: Path,
) -> None:
"""Deleted plan.md clears cached plan_path to avoid repeated stats.
When a previously-present ``plan.md`` becomes unreadable, the
cached ``plan_path`` is set to ``None`` so subsequent calls
do not repeatedly stat a missing file.
"""
sess = tmp_path / "sess-0"
_write_events(sess / "events.jsonl", _START_EVENT)
plan = sess / "plan.md"
plan.write_text("# My Session\n", encoding="utf-8")
_, _, result1 = _discover_with_identity(tmp_path)
assert len(result1) == 1
assert result1[0][2] is not None # plan_id present
# Delete plan.md without changing root mtime.
plan.unlink()
_, _, result2 = _discover_with_identity(tmp_path)
assert len(result2) == 1
assert result2[0][2] is None # plan_id gone
# Cached plan_path must be cleared to None.
cached_entries = _DISCOVERY_CACHE[tmp_path].entries
assert cached_entries[0][1] is None
def test_plan_md_created_after_cache_detected(
self,
tmp_path: Path,
) -> None:
"""Newly-created plan.md is detected on cache hit.
When ``plan.md`` is created after the discovery cache is
populated (without changing root mtime), the next call with
``include_plan=True`` must detect it and return a non-None
``plan_id``.
"""
sess = tmp_path / "sess-0"
_write_events(sess / "events.jsonl", _START_EVENT)
# Populate cache — no plan.md exists.
_, _, result1 = _discover_with_identity(tmp_path)
assert len(result1) == 1
assert result1[0][2] is None # no plan_id
# Create plan.md without changing root mtime.
plan = sess / "plan.md"
plan.write_text("# My Session\n", encoding="utf-8")
# Cache hit must detect the new plan.md.
_, _, result2 = _discover_with_identity(tmp_path)
assert len(result2) == 1
assert result2[0][2] is not None # plan_id detected
# Cached entry must now include the plan path.
cached_entries = _DISCOVERY_CACHE[tmp_path].entries
assert cached_entries[0][1] == plan
def test_plan_probe_rotates_across_cache_hits(
self,
tmp_path: Path,
) -> None:
"""plan.md created beyond initial probe budget is eventually detected.
Creates more sessions than ``_MAX_PLAN_PROBES`` without any
``plan.md``. A ``plan.md`` is then created in a session that
sits beyond the first probe window. After enough cache-hit
calls for the rotating cursor to reach the target session, the
new ``plan.md`` must be detected.
"""
n = _MAX_PLAN_PROBES * 3
for i in range(n):