python / python/cpython

`state_reset()` does not clear `save_marks` after an aborted match

未關閉
#157,705 0 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

extension-modules type-bug
主要語言
Python
星號
77.2k
分支
35.9k
PR 合併指標
PR 指標待擷取

描述

Bug description:

state_reset() in Modules/_sre/sre.c clears the per-match state at the start of each match in a scanner loop, including state->repeat, but not state->save_marks, which is zeroed only in state_init(). A match aborted by a signal returns straight out of SRE(match), so that counter stays above zero for the rest of the iterator and every later match saves and restores marks on backtracking that it would otherwise skip. Only finditer() and pattern.scanner() can observe it, because the findall/sub/split loops abandon the state on error. Results are unchanged, only the cost.

$ cat repro.py
import re, signal, time

class Alarm(Exception): pass

def boom(*args): raise Alarm
signal.signal(signal.SIGALRM, boom)

PAT = r"(z)*" + "(a)" * 200 + r"(?:xy|x)" * 300
SUBJECT = "z" * 400000 + ("a" * 200 + "x" * 300) * 400

def run(interrupt):
    it = re.compile(PAT).finditer(SUBJECT)
    if interrupt:
        signal.setitimer(signal.ITIMER_REAL, 0.02)
        try:
            next(it)
        except Alarm:
            pass
        signal.setitimer(signal.ITIMER_REAL, 0)
    next(it)
    t = time.perf_counter()
    spans = [m.span() for m in it]
    return time.perf_counter() - t, spans

clean, clean_spans = run(False)
dirty, dirty_spans = run(True)
print("clean iterator          : %.4fs, %d matches" % (clean, len(clean_spans)))
print("resumed after one abort : %.4fs, %d matches" % (dirty, len(dirty_spans)))
print("same results            : %s" % (clean_spans == dirty_spans,))

$ ./python repro.py
clean iterator          : 0.0087s, 399 matches
resumed after one abort : 0.0238s, 399 matches
same results            : True

Expected: an iterator resumed after an aborted match costs the same as a clean one.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs
  • gh-157707

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

從 Modules/_sre/sre.c 中的 state_reset 以及 finditer() 和 pattern.scanner() 使用的 scanner-loop 路徑開始。先執行 repro.py 比較,然後確認已中止的 match 不會拖慢後續迭代,且恢復後的 spans 保持不變。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
python
領域
backend
Issue 類型
缺陷
難度
3/5
預估耗時
1-2 天
活躍度
停滯
描述清晰度
描述清楚
新手友好度
30/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。