Skip to content

Commit bf0bac3

Browse files
committed
fix(templates): find the positions in a template from a line index built once
Each position in a template was counted from its start: collecting the filters of a template applying n of them read it n times, in time quadratic in its size (#288). A template of 2 MB applying 160,000 filters on one line took 49 s, where Django compiles and renders it in 2.7 s. The line of each include and extends, and of each load the engine cannot resolve, was counted the same way. The start of each line of a template is now found once, when it is read, and the line of each position by bisection. The positions do not change: templates are read with universal newlines, so their text holds only line feeds, which both count alike.
1 parent c16c595 commit bf0bac3

2 files changed

Lines changed: 71 additions & 8 deletions

File tree

‎src/coretrace_python/taint/templates.py‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@
7979
analyze_scopes,
8080
)
8181
from coretrace_python.semantic.symbols import SymbolId, analyze_symbols
82-
from coretrace_python.source import SourceId, SourceManager, SourceSpan
82+
from coretrace_python.source import LineIndex, SourceId, SourceManager, SourceSpan
8383
from coretrace_python.taint.models import ModelTable
8484

8585
TEMPLATES_DIRECTORY = "templates"
@@ -1315,9 +1315,10 @@ def _read_scopes(text: str, source: SourceId, libraries: Mapping[str, _Library])
13151315
blocks: list[tuple[list[tuple[str, int, frozenset[str]]], set[str]]] = []
13161316
loaded: list[_Load] = []
13171317
unresolved: dict[_Load, None] = {}
1318+
lines = LineIndex(text)
13181319

13191320
def span(offset: int) -> SourceSpan:
1320-
line, column = _position(text, offset)
1321+
line, column = lines.position(offset)
13211322
return SourceSpan(source, line, column)
13221323

13231324
def free(names: frozenset[str]) -> frozenset[str]:
@@ -1706,12 +1707,6 @@ def _expressions(text: str) -> Iterator[tuple[int, str, bool]]:
17061707
yield match.start(2), tag, True
17071708

17081709

1709-
def _position(text: str, offset: int) -> tuple[int, int]:
1710-
"""The one-based line and column of ``offset`` in ``text``."""
1711-
1712-
return text.count("\n", 0, offset) + 1, offset - text.rfind("\n", 0, offset)
1713-
1714-
17151710
class EscapedTemplates(Analysis[frozenset[str]]):
17161711
"""The names of the project templates that escape everything they render, provided
17171712
by the engine for a project; none on its own."""

‎tests/test_template_positions.py‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
"""Acceptance tests for issue #288: the positions of a template's filters, includes and
2+
loads are found in time linear in the template.
3+
4+
Each position was counted from the start of the file, so collecting the filters of a
5+
template applying n of them took time quadratic in its size, where Django compiles and
6+
renders it in linear time. The start of each line of a template is now found once, when
7+
it is read, and each position by bisection.
8+
"""
9+
10+
from __future__ import annotations
11+
12+
import json
13+
import subprocess
14+
import sys
15+
from pathlib import Path
16+
17+
import pytest
18+
19+
TIMEOUT = 60
20+
COUNT = 200_000
21+
# The template's number of filters and the last one's line and column, then the number
22+
# of unread entries and the last one.
23+
DESCRIBE = (
24+
"import json, sys\n"
25+
"from pathlib import Path\n"
26+
"from coretrace_python.taint.templates import project_templates\n"
27+
"found = project_templates(Path(sys.argv[1]))\n"
28+
"filters = found.filters.get('page.html', ())\n"
29+
"last = [filters[-1].location.start_line, filters[-1].location.start_column] if filters else None\n"
30+
"print(json.dumps([len(filters), last, len(found.unread), found.unread[-1:]]))\n"
31+
)
32+
33+
34+
@pytest.mark.parametrize(
35+
("unit", "expected"),
36+
[
37+
("{{ v|upper }}", [COUNT, [1, 13 * (COUNT - 1) + 6], 0, []]),
38+
(
39+
"{% include v %}\n",
40+
[0, None, COUNT, [f"app/templates/page.html:{COUNT} names a template by an expression"]],
41+
),
42+
(
43+
"{% load missing %}{{ v|upper }}\n",
44+
[0, None, COUNT, [f"app/templates/page.html:{COUNT} loads 'missing', not found"]],
45+
),
46+
],
47+
ids=["filters-on-one-line", "includes-named-by-an-expression", "loads-not-found"],
48+
)
49+
def test_the_positions_in_a_large_template_are_found_in_linear_time(
50+
tmp_path: Path, unit: str, expected: list[object]
51+
) -> None:
52+
# Counted from the start of the file each time, these positions took minutes.
53+
templates = tmp_path / "app" / "templates"
54+
templates.mkdir(parents=True)
55+
(templates / "page.html").write_text(unit * COUNT, encoding="utf-8")
56+
try:
57+
completed = subprocess.run(
58+
[sys.executable, "-c", DESCRIBE, str(tmp_path)],
59+
capture_output=True,
60+
text=True,
61+
check=False,
62+
timeout=TIMEOUT,
63+
)
64+
except subprocess.TimeoutExpired:
65+
pytest.fail(f"finding the positions did not end within {TIMEOUT} s")
66+
67+
assert completed.returncode == 0, completed.stderr
68+
assert json.loads(completed.stdout) == expected

0 commit comments

Comments
 (0)