File size: 8,656 Bytes
61bb557 | 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 | # Bugfix Case Study — Trailing Delimiters in Truncated Slugs
**Project:** [python-slugify](https://github.com/un33k/python-slugify)
(219-line slug-generation library, used to build URL-safe slugs from arbitrary text)
**Bug:** the `modern` algorithm's hard-cut truncation could emit a trailing
(or leading) delimiter when the input contained consecutive separators.
**Fix commit upstream:** [`8f9a550`](https://github.com/un33k/python-slugify/commit/8f9a550)
("Avoid trailing post-replacement delimiters in modern hard cuts", PR #200)
**My reproduction date:** 2026-09-26
---
## 1. Symptom
Given a text with consecutive separators and a `max_length` truncation, the
modern slug algorithm returns slugs that end (or start) with a separator that
has nothing after it:
```python
from slugify import slugify
# 'one--two' is 8 chars; we ask for a 5-char slug.
slugify("one--two", algorithm="modern", max_length=5)
# -> 'one-' expected 'one'
slugify("x--two", algorithm="modern", separator="x", max_length=3)
# -> 'xx' expected 'x'
slugify("--one", algorithm="modern", max_length=2)
# -> '-' expected ''
```
A trailing `-` in a slug is cosmetically wrong but also *functionally* wrong:
it changes the slug's length, breaks exact-match lookups against previously
generated slugs, and in the word-boundary path it can produce a *leading*
separator (`'-'` where `''` was expected).
## 2. Diagnosis
I started at the truncation helper `_modern_truncate` in `slugify/slugify.py`.
The input text is split on the internal dash into `tokens`, and the hard-cut
branch walks those tokens while budgeting characters:
```python
parts: list[str] = []
length = 0
for index, word in enumerate(tokens):
delimiter = separator if index else '' # <- the bug
remaining = max_length - length - len(delimiter)
if remaining <= 0:
break
parts.append(delimiter + word[:remaining])
length += len(delimiter) + min(len(word), remaining)
if len(word) > remaining:
break
return ''.join(parts)
```
Two problems, both about how empty tokens (consecutive separators) are
handled:
1. **One separator is charged per token index, regardless of content.**
`text.split('-')` turns `one--two` into `['one', '', 'two']`. The empty
middle token still gets a `delimiter = separator` and is emitted as a bare
separator. If the budget runs out *right after* emitting that bare
separator, the output ends in a delimiter: `'one-'`.
2. **The cut breaks *after* appending, without knowing the next token.**
There is no lookahead: the code commits a delimiter before checking
whether any nonempty word will actually follow within the budget.
I confirmed the diagnosis by writing the failing test **first** (below), then
tracing one failing case by hand (`'one--two'`, separator `-`, max 5):
token 0 `one` (len 3), token 1 `''` charges one `-` (len 4), token 2 `two`
needs one more `-` → `remaining = 0` → break → `'one-'`. Exactly what the
test shows.
## 3. Fix
Minimal, localized to the hard-cut loop (7 lines added, 1 changed — see
`bugfix.diff`):
```python
parts: list[str] = []
length = 0
previous_index = 0
for index, word in enumerate(tokens):
if not word:
continue # skip empty tokens...
# ...and keep their whole delimiter run with the next nonempty word
delimiter = separator * (index - previous_index)
remaining = max_length - length - len(delimiter)
if remaining <= 0:
break # <- checked BEFORE emitting
parts.append(delimiter + word[:remaining])
length += len(delimiter) + min(len(word), remaining)
previous_index = index
if len(word) > remaining:
break
return ''.join(parts)
```
The key idea: a separator is only emitted **together with** the nonempty word
that follows it, and the budget check happens **before** anything is emitted.
So a delimiter can never be left dangling at the end of a hard cut, and the
full run of repeated separators (`--` → `--`) travels with the next word
instead of being split across iterations.
I did not touch the word-boundary branch above it — it already skips empty
tokens — and the `if words:` fall-through into the hard-cut path is exactly
why this bug also showed up with `word_boundary=True`.
## 4. Verification
**Failing test, written before the fix** (the exact regression test from the
upstream PR, run against the buggy parent commit `8f9a550^`):
```
$ python -m pytest tests/test_release.py -k "modern_hard_cut or (word_boundary_hard_cut and modern)"
...
> self.assertEqual(slugify('value', replacements=[('value', replacement)], ...), expected)
E AssertionError: 'one-' != 'one'
...
E AssertionError: '-' != ''
====================== 2 failed, 38 deselected in 0.11s =======================
```
Full transcript: `test_results_before.txt`.
**After applying `bugfix.diff`:**
```
tests/test_release.py::ReleaseRegressionTests::test_modern_hard_cut_does_not_end_in_post_replacement_delimiters PASSED [ 50%]
tests/test_release.py::ReleaseRegressionTests::test_modern_word_boundary_hard_cut_keeps_delimiters_with_the_next_word PASSED [100%]
====================== 2 passed, 38 deselected in 0.06s =======================
```
Full transcript: `test_results_after.txt`.
**Regression check — the whole suite** (125 tests, including CLI golden-file
tests and legacy/modern differential tests):
```
$ python -m pytest tests/
====================== 124 passed, 1 skipped in 0.66s =======================
```
**Standalone reproduction** (no package install needed): `repro/` contains
`truncate_buggy.py` and `truncate_fixed.py` — the exact function extracted
from each commit — plus `test_repro.py`, which runs all 13 upstream cases
against both and prints the table (also saved as `repro_output.txt`):
```
input sep max wb | expected buggy fixed ok
---------------------------------------------------------------
one--two - 5 N | one one- one PASS
one--two :: 6 N | one one:: one PASS
--one - 2 N | - PASS
x--two x 3 N | x xx x PASS
...
buggy: 5/13 correct fixed: 13/13 correct
```
Run it: `cd repro && python test_repro.py` (table) or
`python -m pytest test_repro.py -v` (pinned assertions).
## 5. Prevention
What would stop this class of bug in my code (and in a codebase like this):
1. **A property-based test for the truncator.** The invariant is simple and
worth pinning: *for every input, `len(output) <= max_length` and
`output == output.strip(separator)`* (when a hard cut happened). A
`hypothesis` strategy over random texts/separators/limits would have caught
this in one line of property, not 13 hand-picked cases.
2. **Length budgeting as a single source of truth.** The bug came from
updating `length` in two places with subtly different rules
(`min(len(word), remaining)` vs. the delimiter logic). A small
"budget" helper that both reserves and consumes would make the
bookkeeping impossible to desync.
3. **Emit-then-check → check-then-emit discipline.** Any loop that appends to
an output list and then breaks on a boundary should be reviewed for the
"did I append a partial unit?" question. I now grep my own code for
`append(...)` followed by `break` patterns.
4. **Golden tests on the public API.** The repo already has
`check_goldens()` over thousands of cases — this bug survived because the
golden corpus didn't include post-replacement text with consecutive
separators. When the API gains a new option (`replacements`), the golden
generator should be extended in the same PR.
5. **CI runs the differential legacy/modern test on every PR** (this repo
does — `check_differential` over 2,688 cases); the bug slipped in because
the new option path wasn't exercised by the differential set at the time.
## Files in this folder
| File | What it is |
|---|---|
| `bugfix-case-study.md` | this document |
| `bugfix.diff` | the minimal 7-line source fix |
| `test_results_before.txt` | full pytest transcript: 2 failed (buggy code) |
| `test_results_after.txt` | full pytest transcript: 2 passed (fixed code) |
| `repro/truncate_buggy.py` | exact buggy `_modern_truncate`, extracted from `8f9a550^` |
| `repro/truncate_fixed.py` | exact fixed `_modern_truncate`, extracted from `8f9a550` |
| `repro/test_repro.py` | standalone before/after reproduction + pinned tests |
| `repro/repro_output.txt` | the before/after table from a real run |
|