Repository navigation
perf(tasks): remove quadratic scan in sentence splitting; same units - #16
Merged
Merged
Conversation
Reviewer's guide (collapsed on small PRs)Reviewer's GuideThis 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 detectionsequenceDiagram
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
Flow diagram for linear-time sentence splittingflowchart 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()"]
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
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>
Butterski
force-pushed
the
perf/units-linear-sentence-split
branch
from
October 19, 2026 13:23
072106e to
6fbee48
Compare
Butterski
added a commit
to Butterski/basal
that referenced
this pull request
Oct 19, 2026
This was referenced 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
force-pushed
the
perf/units-linear-sentence-split
branch
from
October 20, 2026 12:10
6fbee48 to
695633e
Compare
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
tasks.units(text, "sentence"), the default unit splitter forcompress, looks up the word before eachSENT_ENDmatch to skip abbreviations and single initials:
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.
unitsruns synchronously intasks.expand, called fromServer.decide, andMAX_UNITSis checked aftersplitting. 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_ENDmatch and the current sentence end: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
wisgroup(1).rstrip(".").lower()of the leftmost match of([\w.]+)[.!?…]*[quotes]*$ending at thesentence end
e(wheretext[e - 1]is in[.!?…])..rstrip()on the slice was a no-op: the slice ends on a[.!?…]character, so no quotes can followeither and the quote group is always empty.
[prev, e)is safe:text[prev - 1]is the last character of the previous match's\s+, and noneof the pattern's classes contains whitespace, so no match can start earlier.
e, the trailing[.!?…]run cannot contain a\wcharacter. If the first character beforeit is not
\w, the oldgroup(1)could only be dots andw == ""; the reversed pattern also fails, giving"".Otherwise that character
tmust be ingroup(1), the leftmost start is the beginning of the maximal[\w.]runending at
t, andgroup(1)greedily extends from there through the dots aftert, whichrstrip(".")removes.So the old
wis the[\w.]run ending att, lowercased: exactly the reversedgroup(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:MAX_UNITS)"Start. " + "a" * 20000 + " b. Koniec.""Start. " + "a" * 200000 + " b. Koniec."Tests
test_units_abbreviation_right_after_a_sentence_end: abbreviations and single initials immediately after asentence 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:
Enhancements:
Documentation:
Tests: