Skip to content

perf(tasks): remove quadratic scan in sentence splitting; same units - #16

Merged
rkinas merged 3 commits into
rkinas:mainfrom
Butterski:perf/units-linear-sentence-split
Oct 20, 2026
Merged

rkinas merged 3 commits into
rkinas:mainfrom
Butterski:perf/units-linear-sentence-split

Conversation

@Butterski

@Butterski Butterski commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Problem

tasks.units(text, "sentence"), the default unit splitter for compress, looks up the word before each SENT_END
match to skip abbreviations and single initials:

word = re.search(r"([\w.]+)[.!?…]*[\"”»)\]]*$", text[:m.start() + 1].rstrip())

The search is unanchored at the start, so it tries every position from 0 on a fresh slice, and inside a long token it
re-scans the token's suffix from every start position. Both are quadratic: O(n²) per document, and O(L²) for a token of
length L. units runs synchronously in tasks.expand, called from Server.decide, and MAX_UNITS is checked after
splitting. A 98k-character document holds the event loop for ~13 s before the request is rejected with 422;
"a" * 20000 + " b. Koniec." takes 6.1 s.

Change

Match an anchored pattern on the reversed window between the previous SENT_END match and the current sentence end:

WORD_BEFORE = re.compile(r"[.!?…]*(\w[\w.]*)")  # matched on the reversed text before a sentence end
...
word = WORD_BEFORE.match(text[prev:m.start() + 1][::-1])
prev = m.end()
w = word.group(1)[::-1].lower() if word else ""

Windows are disjoint, and an anchored greedy match scans each character once, so the scan is O(n) per document.
Collecting the cuts still ends in sorted(set(cuts)), O(k log k) in the number of cuts.

Output identity

The old w is group(1).rstrip(".").lower() of the leftmost match of ([\w.]+)[.!?…]*[quotes]*$ ending at the
sentence end e (where text[e - 1] is in [.!?…]).

  1. The removed .rstrip() on the slice was a no-op: the slice ends on a [.!?…] character, so no quotes can follow
    either and the quote group is always empty.
  2. Restricting to [prev, e) is safe: text[prev - 1] is the last character of the previous match's \s+, and none
    of the pattern's classes contains whitespace, so no match can start earlier.
  3. Read backwards from e, the trailing [.!?…] run cannot contain a \w character. If the first character before
    it is not \w, the old group(1) could only be dots and w == ""; the reversed pattern also fails, giving "".
    Otherwise that character t must be in group(1), the leftmost start is the beginning of the maximal [\w.] run
    ending at t, and group(1) greedily extends from there through the dots after t, which rstrip(".") removes.
    So the old w is the [\w.] run ending at t, lowercased: exactly the reversed group(1).

Empirical check: old and new implementations return identical spans on 20,402 texts (a Polish 19.7k-character
document, English text from docs/*.md, 400 random texts, 20,000 short fuzz texts dense in dots, !?…, quotes,
digits, underscores, non-ASCII letters and abbreviations).

Measurements

CPU, units(text, "sentence"), single call:

text sentences before after
Polish, 98k chars (over MAX_UNITS) 1,636 12,973 ms 4.3 ms
"Start. " + "a" * 20000 + " b. Koniec." 3 6,103 ms 0.29 ms
"Start. " + "a" * 200000 + " b. Koniec." 3 not run 2.65 ms

Tests

  • Added test_units_abbreviation_right_after_a_sentence_end: abbreviations and single initials immediately after a
    sentence end, i.e. at the start of the window, must not produce a cut.
  • tests/test_tasks.py: 20 passed.
  • docs/WHATS_NEW.md: one entry under v2.1.0.

Summary by Sourcery

Make sentence splitting scale linearly while preserving existing sentence boundaries and abbreviation handling.

Bug Fixes:

  • Preserve sentence splitting behavior for abbreviations and single initials occurring immediately after a sentence boundary.

Enhancements:

  • Improve sentence splitting performance from quadratic to linear scanning, preventing long documents from blocking the event loop before unit-limit validation.

Documentation:

  • Document the faster sentence splitting behavior and its performance impact in the changelog.

Tests:

  • Add coverage for abbreviations and initials immediately following sentence ends.

@sourcery-ai

sourcery-ai Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

This PR makes sentence splitting linear by reusing a compiled word-ending regex and restricting each search to the text after the previous sentence-end match, while preserving unit boundaries and adding targeted regression coverage and release-note documentation.

Sequence diagram for optimized sentence boundary detection

sequenceDiagram
    participant U as units
    participant S as SENT_END
    participant W as WORD_END
    participant C as CutBuilder
    U->>S: finditer(text)
    loop Each sentence-end match
        S-->>U: m
        U->>W: search(text, prev, m.start() + 1)
        W-->>U: word match
        U->>U: Check ABBREV or single initial
        alt Abbreviation or initial
            U->>U: Skip boundary
        else Regular sentence end
            U->>C: Append m.end()
        end
        U->>U: Set prev = m.end()
    end
Loading

Flow diagram for linear-time sentence splitting

flowchart LR
    A["units(text, sentence)"] --> B[SENT_END.finditer]
    B --> C["WORD_END.search(text, prev, m.start() + 1)"]
    C --> D["Check ABBREV and single initials"]
    D --> E["Append sentence cut or skip"]
    E --> F["Update prev = m.end()"]
Loading

File-Level Changes

Change Details Files
Replace repeated prefix slicing and unanchored regex searches with a bounded, reusable regex search to make sentence splitting linear in document size.
  • Compile the word-ending pattern once at module scope.
  • Track the previous sentence-end match and pass search bounds directly to the compiled pattern, including skipped matches.
  • Preserve abbreviation and single-initial detection while avoiding substring allocation and repeated scans.
basal/tasks.py
Add regression coverage for abbreviation and initial handling at search-window boundaries.
  • Verify abbreviations and single-letter initials immediately following a sentence end do not create incorrect cuts.
tests/test_tasks.py
Document the sentence-splitting performance improvement and unchanged output behavior.
  • Record the linear-time implementation and long-document performance impact in release notes.
docs/WHATS_NEW.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 2 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="basal/tasks.py" line_range="96" />
<code_context>
-            word = re.search(r"([\w.]+)[.!?…]*[\"”»)\]]*$", text[:m.start() + 1].rstrip())
+            # Search from the previous match's end, not from 0 (O(n²) per document): text[prev - 1] is whitespace,
+            # which no WORD_END character class contains, so no match could start earlier.
+            word = WORD_END.search(text, prev, m.start() + 1)
+            prev = m.end()
             w = (word.group(1) if word else "").rstrip(".").lower()
</code_context>
<issue_to_address>
**Long tokens still block the event loop**

When a sentence-search window contains a very long word-like run followed by whitespace and another word before the sentence-ending punctuation, `WORD_END.search` retries at each position in an earlier long `\w` run, rescanning its suffix when it cannot reach `endpos`; a long unbroken token followed by a space and the final word makes the search window quadratic, so `tasks.expand` blocks `Server.decide` before the unit limit is checked.

Avoid retrying the greedy word pattern from every position, for example by locating the final word directly within the window.
</issue_to_address>

### Comment 2
<location path="docs/WHATS_NEW.md" line_range="16-17" />
<code_context>
 - Every other request takes the same code path as in v2.0.0 (on basal-omni-1.0-max, 23,276 of 23,278 served-check
   answers were the same; the two others were near-ties).
+- `compress` with `unit: "sentence"` splits long documents in linear time: the word before each sentence end was
+  searched from the start of the text, O(n²) per document (a 98k-character document: 13 s on the event loop before
+  the 600-unit refusal, now 19 ms). Same units as before.

 **New models (Hugging Face, Sat 17 Oct, 09:00 CEST)**
</code_context>
<issue_to_address>
**Sentence splitting stays superlinear**

When the text contains many sentence boundaries, `units` still passes all collected cut offsets through `sorted(set(cuts))` (`basal/tasks.py:104`), so the full splitter has no guaranteed linear-time bound; dense long inputs do not meet the documented complexity.

Merge the ordered cut streams with linear deduplication, or describe the change as eliminating the quadratic scan rather than making the whole splitter linear.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread basal/tasks.py Resolved
Comment thread docs/WHATS_NEW.md Resolved
@Butterski Butterski changed the title perf(tasks): split sentences in linear time; same units perf(tasks): remove quadratic scan in sentence splitting; same units Oct 18, 2026
@Butterski
Butterski force-pushed the perf/units-linear-sentence-split branch from 072106e to 6fbee48 Compare October 19, 2026 13:23
Butterski added a commit to Butterski/basal that referenced this pull request Oct 19, 2026
units() searched for the word before each sentence end from the start
of the text, O(n^2) per document. Search from the previous sentence
end instead: no match can start earlier, because text[prev - 1] is
whitespace and no class of the pattern contains whitespace. The slice's
.rstrip() was a no-op (the slice ends on a [.!?…] character), and
Pattern.search(text, pos, endpos) treats endpos as the end of the
string, so $ matches where it did.

98k-char Polish document: 13.0 s -> 18.6 ms (blocking the event loop
before the 600-unit refusal); same spans on 402 test texts.
WORD_END.search still retried every start position inside a long
token ("a" * 20000 + " b.": 6.1 s). Match [.!?…]*(\w[\w.]*) on the
reversed window instead: anchored at the sentence end, every character
is scanned once. Same w on 20,402 texts (corpus + punctuation-dense
fuzz). WHATS_NEW: describe the change as removing the quadratic scan,
not as a linear-time splitter (cuts are still sorted).
@Butterski
Butterski force-pushed the perf/units-linear-sentence-split branch from 6fbee48 to 695633e Compare October 20, 2026 12:10
@rkinas
rkinas merged commit d31c807 into rkinas:main Oct 20, 2026
1 check passed
@rkinas

rkinas commented Oct 20, 2026

Copy link
Copy Markdown
Owner

Thanks, Milosz! Merged for basal 2.3.1. The backwards anchored match keeps every unit identical (your new test and the full suite pass), and a long compress request no longer blocks the event loop. You are credited in WHATS_NEW and in the 2.3.1 release notes.

rkinas added a commit that referenced this pull request Oct 20, 2026
rkinas added a commit that referenced this pull request Oct 21, 2026
…) into 2.3.1

# Conflicts:
#	docs/WHATS_NEW.md
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