Skip to content

Codex 사용량 중복 집계 수정 - #146

Merged
soulduse merged 1 commit into
soulduse:mainfrom
shindonghwi:fix/codex-replayed-session-usage
Jun 24, 2026
Merged

soulduse merged 1 commit into
soulduse:mainfrom
shindonghwi:fix/codex-replayed-session-usage

Conversation

@shindonghwi

@shindonghwi shindonghwi commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

문제

Codex 세션 로그에서 같은 세션의 누적 사용량이 여러 rollout JSONL 파일에 다시 나타나는 경우가 있습니다.

지금 코드는 파일/라인마다 token_count를 전부 더하기 때문에, 이미 한 번 기록된 누적 사용량이 다른 파일에 replay되면 토큰, 비용, 메시지 수가 실제보다 크게 보일 수 있습니다.

수정

  • token_count 안의 누적 사용량(total_token_usage)을 중복 판별용 스냅샷으로 보관합니다.
  • 통계를 만들 때 (session_id, model, total_token_usage)가 같은 항목은 한 번만 집계합니다.
  • 파일 변경 감지와 incremental cache key는 그대로 두었습니다.
  • total_token_usage가 없고 last_token_usage만 있는 이벤트는 중복 제거하지 않습니다. 정상 사용 이벤트가 잘못 합쳐지지 않게 하기 위해서입니다.

확인한 내용

  • 같은 누적 사용량이 두 rollout 파일에 replay된 경우 1건만 집계되는 테스트를 추가했습니다.
  • 누적 사용량 없이 last_token_usage만 있는 이벤트 2개는 2건으로 유지되는 테스트를 추가했습니다.

테스트

  • cargo test providers::codex --lib
  • cargo test --lib

@shindonghwi shindonghwi changed the title Fix Codex overcounting from replayed session files Codex 세션 replay로 인한 사용량 중복 집계 수정 Jun 22, 2026
@shindonghwi
shindonghwi force-pushed the fix/codex-replayed-session-usage branch 2 times, most recently from 774a0db to 522e7fb Compare June 22, 2026 11:34
@shindonghwi shindonghwi changed the title Codex 세션 replay로 인한 사용량 중복 집계 수정 Codex 사용량 중복 집계 수정 Jun 22, 2026
@soulduse

Copy link
Copy Markdown
Owner

안녕하세요 @shindonghwi 님, 먼저 직접 사용량 부풀림 문제를 추적해서 원인까지 짚어주시고 PR로 올려주셔서 정말 감사합니다. 🙏 6월에 제보해주신 $1832 케이스 덕분에 v0.19.18에서 한 차례 수정(#145)이 들어갔는데, 그걸로도 여전히 부풀려진다고 하셔서 이 PR을 꼼꼼히 들여다봤습니다.

결론부터 말씀드리면, 문제의 방향(누적 사용량이 중복 집계되어 부풀려진다)은 정확하게 보셨습니다. 다만 이 PR의 dedup 방식이 제 실제 ~/.codex/sessions 데이터(80여 개 세션)에서 검증해보니 정상적인 사용량을 일부 누락(언더카운트)시키는 부작용이 있어서, 이대로는 머지하기 어려울 것 같습니다. 아래에 근거를 정리했습니다.


1. dedup 키와 집계 값의 의미가 어긋납니다

집계에 실제로 쓰이는 값(entry.input_tokens 등)은 extract_token_usage()가 뽑는데, 이 함수는 last_token_usage(per-turn 델타)를 우선합니다 (codex.rs의 해당 주석에도 명시되어 있습니다).

반면 이 PR이 추가한 codex_usage_dedup_snapshot()은 total_token_usage(세션 누적값)만 봅니다.

즉 "누적값이 같으면 델타값도 중복이다" 라고 판정하는 구조인데, 이 두 값은 의미가 다릅니다.

2. 실데이터에서 서로 다른 turn을 잘못 합칩니다

last_token_usage의 input/output이 0인데 total_tokens에는 실제 값이 있는 turn(컴팩션/컨텍스트 관리 turn)들이 존재합니다. 이런 turn들은 누적 스냅샷(total_token_usage)이 직전 turn과 동일하게 유지되기 때문에, 이 PR의 dedup이 서로 다른 turn으로 보고 하나로 합쳐버립니다.

제 데이터로 시뮬레이션한 결과:

  • 서로 다른 12개 turn이 잘못 병합되어 약 496,000 토큰이 누락되었습니다.
  • 같은 누적 스냅샷이 한 파일 안에서 반복되는 파일이 다수 존재했습니다(가장 심한 파일은 한 스냅샷이 313번 반복).
COLLISION 예시:
  total_snapshot(중복 판정 기준): input=8,368,007 ... total=8,405,606
  이 turn  last_token_usage : in=0 out=0 total=14,880   <- 실제 소비 turn인데 버려짐
  직전 turn last_token_usage : in=211,093 ... total=211,726

3. 현재(v0.19.18) 집계 자체는 이미 정확합니다

한 세션에서 검증해보면 sum(last_token_usage.total) = 17,941,018 vs 세션 최종 total_token_usage.total = 17,876,216 으로 1.00배 일치합니다. OpenAI가 매 turn 전체 컨텍스트를 재처리해서 보고하는 방식이라 입력 토큰이 turn마다 커 보이지만, 합산하면 세션 누적과 정확히 맞습니다. 그래서 이 PR의 dedup이 더해지면 정확한 값에서 일부가 빠지는 쪽으로 작동합니다.

4. #145와 책임 영역이 겹칩니다

"파일이 재작성/replay되어 중복 집계되는" 문제는 이미 머지된 #145가 parse_incremental에서 경로 기반(<path>\n<line>)으로 이전 엔트리를 purge하는 방식으로 처리하고 있습니다. 이 PR은 같은 증상을 build_stats 단계에서 다시 처리해서, 두 방어 레이어가 상호작용하면 디버깅이 어려워집니다.


그래서 진짜 궁금한 점 — 어떤 데이터에서 부풀려졌나요?

제 환경에서는 #145 적용 후 cross-file replay가 0건이고 집계도 정확해서, shindonghwi 님 환경에서 v0.19.18으로도 부풀려지는 실제 원인을 아직 재현하지 못했습니다. 원인을 정확히 잡으려면 그쪽 데이터의 형태를 봐야 할 것 같습니다.

번거로우시겠지만 아래 진단 스크립트를 한 번만 돌려서 출력 결과(토큰 수치만 나오고 프롬프트/코드 내용은 절대 출력되지 않습니다) 를 붙여주실 수 있을까요? 특히 [2](total 폴백 turn 수), [3](cross-file replay), [5](집계 불일치 세션) 항목이 결정적입니다.

# 읽기 전용, 수정 없음. 토큰 숫자만 출력합니다.
python3 codex-usage-diagnose.py

# 부풀려져 보였던 특정 날짜가 있다면:
python3 codex-usage-diagnose.py 2026-06-22

스크립트 전문은 아래 접힌 블록에 넣어두었습니다(복사해서 codex-usage-diagnose.py 로 저장 후 실행). 결과를 주시면 그걸 바탕으로 언더카운트 없이 정확히 그 케이스만 잡는 수정을 같이 만들어보면 좋겠습니다. 다시 한 번, 직접 파고들어 주셔서 감사합니다! 🙇

codex-usage-diagnose.py (클릭해서 펼치기)
#!/usr/bin/env python3
"""
Codex 사용량 부풀림 진단 도구 (ai-token-monitor)
================================================

ai-token-monitor가 Codex 사용량을 어떻게 집계하는지 재현하고,
어디서 부풀려지는지(혹은 부풀려지지 않는지)를 알려줍니다.

사용법:
    python3 codex-usage-diagnose.py
    python3 codex-usage-diagnose.py 2026-06-22   # 특정 날짜만 자세히

이 스크립트는 읽기 전용입니다. 어떤 파일도 수정하지 않습니다.
개인정보(프롬프트 내용 등)는 출력하지 않으며, 토큰 수치만 집계합니다.
"""
import json
import glob
import os
import sys
from collections import defaultdict

SESSIONS = os.path.expanduser("~/.codex/sessions")


def extract_preferred(info):
    """ai-token-monitor의 extract_token_usage 재현:
    last_token_usage(per-turn 델타)를 우선, 없으면 total_token_usage(누적) 폴백."""
    u = info.get("last_token_usage") or info.get("total_token_usage")
    if u is None:
        return None
    inp = u.get("input_tokens", 0)
    out = u.get("output_tokens", 0)
    cached = u.get("cached_input_tokens", 0)
    tot = u.get("total_tokens", inp + out)
    return inp, out, cached, tot


def main():
    target_date = sys.argv[1] if len(sys.argv) > 1 else None

    files = glob.glob(os.path.join(SESSIONS, "**", "*.jsonl"), recursive=True)
    if not files:
        print(f"세션 파일을 찾지 못했습니다: {SESSIONS}")
        return

    # 1) 필드 존재 형태 통계
    both = last_only = total_only = neither = 0
    # 2) cross-file replay (같은 session_id가 여러 파일에)
    session_files = defaultdict(set)
    # 3) 파일 내 동일 누적 스냅샷 반복
    files_with_repeat_total = 0
    # 4) 현재 코드 기준 일별 집계
    daily = defaultdict(lambda: [0, 0, 0, 0])  # date -> [input, output, cached, turns]
    # 5) 검증: sum(last) vs final total  (세션별)
    session_sum_last = defaultdict(int)
    session_final_total = {}
    # 6) total_token_usage 폴백으로만 집계된 turn (누적 누수 의심)
    total_fallback_turns = 0

    for f in files:
        sid = None
        prev = None
        repeat_seen = defaultdict(int)
        with open(f, errors="replace") as fh:
            for line in fh:
                try:
                    v = json.loads(line)
                except Exception:
                    continue
                t = v.get("type")
                if t == "session_meta":
                    sid = v.get("payload", {}).get("id")
                    continue
                if t != "event_msg":
                    continue
                p = v.get("payload", {})
                if p.get("type") != "token_count":
                    continue
                info = p.get("info") or {}
                if not info:
                    continue

                has_last = "last_token_usage" in info
                has_total = "total_token_usage" in info
                if has_last and has_total:
                    both += 1
                elif has_last:
                    last_only += 1
                elif has_total:
                    total_only += 1
                else:
                    neither += 1

                e = extract_preferred(info)
                if e is None:
                    continue
                # 연속 동일 스냅샷 skip (현재 코드 동작)
                if prev == e:
                    continue
                prev = e
                if e == (0, 0, 0, 0):
                    continue

                if not has_last and has_total:
                    total_fallback_turns += 1

                ts = v.get("timestamp", "")[:10] or "?"
                if sid:
                    session_files[ts].add(sid) if False else None  # placeholder
                    session_files[sid].add(f)

                daily[ts][0] += e[0]
                daily[ts][1] += e[1]
                daily[ts][2] += e[2]
                daily[ts][3] += 1

                # 검증용: last 합산 vs 최종 total
                last = info.get("last_token_usage")
                if last and sid:
                    session_sum_last[sid] += last.get("total_tokens", 0)
                tot = info.get("total_token_usage")
                if tot and sid:
                    session_final_total[sid] = tot.get("total_tokens", 0)

                # 파일 내 누적 스냅샷 반복 카운트
                if tot:
                    rk = (tot.get("input_tokens"), tot.get("output_tokens"), tot.get("total_tokens"))
                    repeat_seen[rk] += 1
        if any(c > 1 for c in repeat_seen.values()):
            files_with_repeat_total += 1

    cross = {s: fs for s, fs in session_files.items() if len(fs) > 1}

    print("=" * 60)
    print(f"Codex 세션 진단  ({len(files)}개 파일)")
    print("=" * 60)
    print()
    print("[1] token_count 이벤트의 사용량 필드 형태")
    print(f"    last+total 둘 다 : {both}")
    print(f"    last 만          : {last_only}")
    print(f"    total 만         : {total_only}   <- 0보다 크면 누적 누수 위험")
    print(f"    둘 다 없음       : {neither}")
    print()
    print(f"[2] 현재 코드가 total_token_usage(누적)로 폴백 집계한 turn: {total_fallback_turns}")
    print(f"    (0이 아니면 누적값이 델타처럼 합산되어 부풀려질 수 있음 = $1832 패턴)")
    print()
    print(f"[3] 같은 session_id가 여러 파일에 나타남 (cross-file replay): {len(cross)}개")
    for s, fs in list(cross.items())[:5]:
        print(f"    - {s[:24]}... ({len(fs)}개 파일)")
    if not cross:
        print("    없음 -> PR #145가 막으려는 replay는 이 환경에 없음")
    print()
    print(f"[4] 한 파일 안에서 동일 누적 스냅샷이 반복되는 파일: {files_with_repeat_total}/{len(files)}")
    print(f"    (>0 이면 PR #146 dedup이 서로 다른 turn을 잘못 합쳐 언더카운트할 위험)")
    print()
    print("[5] 집계 정확성 검증: sum(last_token_usage) vs 최종 total_token_usage")
    bad = 0
    for s in list(session_final_total.keys())[:200]:
        final = session_final_total[s]
        summed = session_sum_last.get(s, 0)
        if final > 0:
            ratio = summed / final
            if ratio > 1.3 or ratio < 0.7:
                bad += 1
                if bad <= 5:
                    print(f"    [불일치] {s[:24]}...  sum(last)={summed:,}  final={final:,}  ({ratio:.2f}x)")
    if bad == 0:
        print("    모든 세션에서 sum(last) ~= final total (1.00x 근처). 집계 정확.")
    else:
        print(f"    -> {bad}개 세션에서 큰 불일치. 이 세션들이 부풀림 원인일 수 있음.")
    print()
    print("[6] 일별 집계 (현재 코드 기준, input 큰 순 상위 8개)")
    print(f"    {'날짜':<12}{'input':>14}{'output':>12}{'cached':>14}{'turns':>8}")
    for d, (i, o, c, n) in sorted(daily.items(), key=lambda x: -x[1][0])[:8]:
        flag = "  <-- 확인" if (target_date and d == target_date) else ""
        print(f"    {d:<12}{i:>14,}{o:>12,}{c:>14,}{n:>8}{flag}")
    print()

    if target_date:
        print(f"[상세] {target_date} turn별 분해")
        for f in files:
            sid = None
            prev = None
            rows = []
            with open(f, errors="replace") as fh:
                for line in fh:
                    try:
                        v = json.loads(line)
                    except Exception:
                        continue
                    if v.get("type") == "session_meta":
                        sid = v.get("payload", {}).get("id")
                    if v.get("type") != "event_msg":
                        continue
                    p = v.get("payload", {})
                    if p.get("type") != "token_count":
                        continue
                    if (v.get("timestamp", "")[:10]) != target_date:
                        continue
                    info = p.get("info") or {}
                    e = extract_preferred(info)
                    if e is None or e == (0, 0, 0, 0):
                        continue
                    if prev == e:
                        continue
                    prev = e
                    rows.append(e)
            if rows:
                si = sum(r[0] for r in rows)
                print(f"    {os.path.basename(f)[:50]}  turns={len(rows)} input합={si:,}")

    print()
    print("진단 결과를 ai-token-monitor 이슈/PR에 붙여주시면 원인 분석에 큰 도움이 됩니다.")
    print("(이 스크립트는 토큰 수치만 출력하며 프롬프트/코드 내용은 절대 출력하지 않습니다.)")


if __name__ == "__main__":
    main()

Resuming a session or spawning a subagent makes Codex write a new rollout file
that replays the parent's earlier token_count events verbatim (identical per-turn
delta and cumulative snapshot, only the timestamp differs). Those copies live in
different files, so the path-based purge in parse_incremental can't reach them and
build_stats summed each file's copy -- inflating one real session's input ~30x
under heavy resume/subagent use (135.9B vs 24.0B of real distinct work in testing).

Dedup in build_stats by (session, model, per-turn delta, cumulative snapshot): a
verbatim replay shares the whole key and collapses, while a compaction turn (flat
cumulative, different delta) keeps a distinct key and is never merged. Sessions
that are never replayed have all-unique keys, so this is a no-op -- it does not
change aggregation for non-replayed data.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@shindonghwi
shindonghwi force-pushed the fix/codex-replayed-session-usage branch from 522e7fb to 936f266 Compare June 23, 2026 16:22
@shindonghwi

shindonghwi commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor Author

@soulduse 스크립트 돌려봤습니다. python3 codex-usage-diagnose.py 2026-06-22 출력 그대로 붙입니다.

============================================================
Codex 세션 진단  (6499개 파일)
============================================================

[1] token_count 이벤트의 사용량 필드 형태
    last+total 둘 다 : 981626
    last 만          : 0
    total 만         : 0   <- 0보다 크면 누적 누수 위험
    둘 다 없음       : 0

[2] 현재 코드가 total_token_usage(누적)로 폴백 집계한 turn: 0
    (0이 아니면 누적값이 델타처럼 합산되어 부풀려질 수 있음 = $1832 패턴)

[3] 같은 session_id가 여러 파일에 나타남 (cross-file replay): 45개
    - 019d2a84-f91b-70f0-a1e0-... (2개 파일)
    - 019d2cb2-cb30-7460-b3dd-... (3개 파일)
    - 019d3e9c-ec69-7c23-8af1-... (7개 파일)
    - 019d3c95-ee3d-7e90-ab18-... (15개 파일)
    - 019d3a27-d2aa-7b40-9620-... (22개 파일)

[4] 한 파일 안에서 동일 누적 스냅샷이 반복되는 파일: 357/6499
    (>0 이면 PR #146 dedup이 서로 다른 turn을 잘못 합쳐 언더카운트할 위험)

[5] 집계 정확성 검증: sum(last_token_usage) vs 최종 total_token_usage
    [불일치] 019cbc7d-1641-72d1-946f-...  sum(last)=77,452,146  final=54,217,921  (1.43x)
    [불일치] 019d2a84-f91b-70f0-a1e0-...  sum(last)=12,015,734  final=8,946,245  (1.34x)
    [불일치] 019d2cb2-cb30-7460-b3dd-...  sum(last)=367,841,666  final=86,418,112  (4.26x)
    -> 3개 세션에서 큰 불일치. 이 세션들이 부풀림 원인일 수 있음.

[6] 일별 집계 (현재 코드 기준, input 큰 순 상위 8개)
    날짜                   input      output        cached   turns
    2026-06-20  28,489,448,613  77,236,37927,389,741,184  175852
    2026-06-22  23,171,486,709  62,104,84022,279,539,456  145488  <-- 확인
    2026-06-19  18,733,908,768  50,458,10818,003,498,624  114318
    2026-06-21  11,132,046,486  29,917,10010,703,442,432   69478
    2026-06-23   6,012,078,115  16,061,550 5,779,001,984   37936
    2026-06-18   4,649,497,439  12,966,288 4,464,399,616   28515
    2026-04-03   2,931,213,642  14,059,471 2,688,385,024   23318
    2026-06-15   2,424,872,732   6,114,381 2,334,904,448   14253

[상세] 2026-06-22 turn별 분해
    rollout-2026-05-29T16-46-19-019e72b2-c58e-7790-833  turns=10 input합=1,711,538
    rollout-2026-06-10T21-03-36-019eb16a-a1ca-7153-9a2  turns=1324 input합=182,757,205
    rollout-2026-06-15T23-22-52-019ecba9-eee6-7722-82e  turns=24 input합=4,137,202
    rollout-2026-06-15T23-22-32-019ecba9-a076-7590-b50  turns=65 input합=10,364,588
    rollout-2026-06-22T16-58-51-019eee56-de9a-78a1-9e6  turns=17787 input합=2,842,353,276
    rollout-2026-06-22T14-37-31-019eedd5-7c13-7b00-b90  turns=17454 input합=2,795,658,504
    rollout-2026-06-22T21-43-31-019eef5b-7d60-7751-8ca  turns=14 input합=488,569
    rollout-2026-06-22T22-43-28-019eef92-60a2-7281-b32  turns=18 input합=1,185,386
    rollout-2026-06-22T17-32-59-019eee76-2176-70e2-add  turns=17893 input합=2,856,107,609
    rollout-2026-06-22T16-14-22-019eee2e-286b-7140-afa  turns=21 input합=1,583,911
    rollout-2026-06-22T15-34-40-019eee09-cdb1-7fd2-b8a  turns=17544 input합=2,809,547,462
    rollout-2026-06-22T23-39-58-019eefc6-1cd5-7810-b66  turns=18 input합=1,855,658
    rollout-2026-06-22T22-00-43-019eef6b-3fab-7a43-88e  turns=18393 input합=2,924,857,014
    rollout-2026-06-22T22-17-23-019eef7a-8122-70b2-8ca  turns=18454 input합=2,932,991,577
    rollout-2026-06-22T19-41-56-019eeeec-2d6d-7253-971  turns=18059 input합=2,879,811,103
    rollout-2026-06-22T21-30-17-019eef4f-6171-7b61-a53  turns=18296 input합=2,911,860,726
    rollout-2026-06-22T20-06-24-019eef02-93d6-7e82-a5d  turns=114 input합=14,215,381

진단 결과를 ai-token-monitor 이슈/PR에 붙여주시면 원인 분석에 큰 도움이 됩니다.
(이 스크립트는 토큰 수치만 출력하며 프롬프트/코드 내용은 절대 출력하지 않습니다.)

결론부터 말씀드리면, 부풀림의 원인은 누적 폴백이 아니라 cross-file replay([3] 45건)였습니다. Codex가 서브에이전트를 띄우거나 세션을 resume할 때 부모의 token_count 기록을 새 파일에 그대로 복사하는데, 그게 파일마다 합산되어 부풀려집니다. 그리고 지적해주신 #146의 언더카운트도 맞아서, dedup 방식을 바꿨습니다. 아래에 하나씩 정리했습니다.

1. 누적 폴백($1832 패턴)은 아닙니다 — [2] = 0

모든 turn에 last_token_usage가 있어서 폴백이 한 번도 발생하지 않습니다. 처음 의심하셨던 경로는 제 데이터엔 해당이 없었습니다.

2. 진짜 원인은 cross-file replay입니다 — [3] = 45건

soulduse님 환경에선 0건이지만 제 환경은 45건입니다. 여기가 결과가 갈린 지점인 것 같습니다.

2026-06-22 상세를 보면 한눈에 드러납니다. 17,00018,000 turn / 각 2.85B짜리 파일이 8개나 있는데:

turns=17787  input합=2,842,353,276
turns=18393  input합=2,924,857,014
turns=18454  input합=2,932,991,577
turns=18296  input합=2,911,860,726
... (이런 파일이 그날 8개)

이 8개가 전부 같은 대화(019eb16a)에서 파생된 복제본입니다. 즉 그날 input 23B의 대부분이 대화 하나입니다.

3. 왜 이렇게 복제되는가

Codex가 서브에이전트 thread를 spawn하거나 세션을 resume하면, 새 rollout 파일을 만들면서 부모의 기록을 그대로 복사합니다.

  • 파생 파일의 session_meta.source에 subagent.thread_spawn.parent_thread_id가 부모를 가리킵니다.
  • 부모의 token_count가 누적값까지 동일하게(timestamp만 갱신) 다시 들어옵니다.
  • 실제로 한 파생 파일의 2,252 turn 중 2,217개가 부모와 완전히 일치했습니다.

019eb16a 한 대화는 이런 식으로 rollout 파일 143개에 퍼져 있었습니다.

4. #145로는 잡히지 않습니다

#145는 같은 파일이 재작성될 때 path 기준으로 purge하는데, 이 경우는 경로가 전부 다른 파일들이라 그 purge가 닿지 못합니다. 그래서 v0.19.18에서 전부 합산되고, [5]에서 sum(last)이 final보다 몇 배씩 뜨는 것도 이 때문입니다. 실제 build_stats로 측정하면 input 135.9B인데, 중복을 빼면 약 24.0B입니다(약 5.7배 과집계).

5. 지적하신 언더카운트 — 맞습니다. 방식을 바꿨습니다.

①(키가 집계값과 어긋남)과 ②(컴팩션 turn을 잘못 합침) 지적이 정확합니다. 솔직히 제가 올렸던 #146 방식(누적 스냅샷만으로 dedup)이 오히려 더 문제였습니다 — 제 데이터에서 135.9B를 1.5B까지 깎아버립니다(누적은 같지만 델타가 다른 컴팩션 turn까지 합쳐서).

그래서 dedup 키에 집계에 실제 쓰는 last 델타를 함께 넣는 방식으로 바꿨습니다.

key = (session_id, model, last(input,output,cached,total), 누적 total_token_usage)
  • verbatim 복사본 → 델타·누적이 모두 같아서 합쳐짐
  • 컴팩션 turn → 누적은 같아도 델타가 달라서 안 합쳐짐 (언더카운트 없음)
  • replay 없는 세션 → 키가 전부 유일해서 no-op (soulduse님 환경의 집계는 그대로)

검증은 실제 Rust 코드와 파이썬 재구현 두 가지로, 토큰 단위까지 맞춰봤습니다:

방식 input
v0.19.18 (dedup 없음) 135.9B
#146 방식 (누적만) 1.5B ← 언더카운트
새 방식 (누적+last) 24.0B

#145와는 영역이 다릅니다(#145는 같은 파일 재작성, 이건 다른 경로로 복제된 cross-file replay). 회귀 테스트도 추가했습니다(복사본 병합 / 컴팩션 분리 / replay 없을 때 no-op). 방금 이 방식으로 다시 push 했습니다. 꼼꼼히 검토해 주셔서 감사합니다! 🙇

@soulduse

Copy link
Copy Markdown
Owner

@shindonghwi 님, 진단 스크립트까지 직접 돌려서 진짜 원인(cross-file replay)을 규명해주시고, 지적드린 언더카운트까지 깔끔하게 고쳐주셔서 정말 감사합니다. 🙏 새 버전을 실데이터로 전부 다시 검증했고, 이대로 머지하겠습니다. 👍

검증 결과

새 dedup 키 (session_id, model, last 델타 4필드, 누적 스냅샷)을 제 80여 개 세션 + 인위적 replay 시나리오로 재현해봤습니다.

검증 항목 결과
Rust 테스트 19개 ✅ 전부 통과 (collapse / 컴팩션 분리 / no-op 회귀 포함)
replay 없는 환경(제 데이터) 영향 ✅ 1토큰도 안 바뀜 — 2,142 entries 그대로, 완전 no-op
verbatim replay 8개 collapse ✅ 513K → 64K (8배 부풀림 정확히 제거)
컴팩션 turn(누적 동일·델타 다름) 보존 ✅ 안 합쳐짐 — 언더카운트 0
CI ✅ pass

이전 방식(누적만)이 제 데이터에서 135.9B를 1.5B로 잘못 깎던 문제가 완전히 사라졌고, replay가 없는 환경에서는 집계에 아무 영향이 없는 게 확인됐습니다. 세 가지 우려(키-값 의미 불일치, 컴팩션 언더카운트, #145와의 중복)가 모두 해소됐습니다.

특히 좋았던 점

  • 원인 규명이 정확합니다. resume/subagent spawn 시 부모 token_count가 누적값까지 그대로 복제되고, 경로가 달라 #145의 path-purge가 닿지 못한다는 분석이 제 데이터 관찰과도 일치합니다.
  • dedup 키에 델타를 함께 넣은 선택이 핵심입니다. verbatim 복사본만 collapse하고 진짜 turn은 보존하는, 정확히 맞는 판별자입니다.
  • 회귀 테스트(복사본 병합 / 컴팩션 분리 / no-op)까지 챙겨주셔서 앞으로 이 동작이 깨지면 바로 잡힙니다.

꼼꼼하게 끝까지 추적해주셔서 다시 한 번 감사합니다. 머지 후 다음 패치 릴리즈에 포함하겠습니다! 🙇

@soulduse
soulduse merged commit f19a3aa into soulduse:main Jun 24, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants