Repository navigation
Description
Bug description
df_to_escaped_csv (superset/utils/csv.py) escapes CSV values one cell at a time with df.at[label, name] = escape_value(value). The cost is per string cell, and it dominates large full CSV exports. The actual to_csv write is a small fraction of the total.
Real-world impact (6.0.1). A "Download → Export to full .CSV" of a raw table chart had about 810k rows × 47 columns, 26 of them string columns (about 21M string cells). The source was BigQuery with the Storage Read API enabled.
| Step | Local (Apple M-series, 2 CPUs) | Web pod (AWS Graviton2) |
|---|---|---|
| Query + fetch + DataFrame | ~30s | ~100s |
| Per-cell escape loop | 75s | ~11 min |
to_csv |
4.5s | — |
The request exceeded our 300s gateway timeout, so users got a 504. The web worker kept working for several more minutes after the client was gone.
Still present on master. The loop now iterates labels with column.items(), but it is still one df.at write per cell, so the cost is the same.
Reproduction (synthetic, no external data). 500k rows: 10 object columns of short strings (some formula-like), 5 int columns, and 1 object column of nullable ints. Run with the df_to_escaped_csv from current master, pandas 2.1.4, numpy 1.26.4, 1 CPU:
to_csv only (no escaping) 0.57s
master df_to_escaped_csv (per-cell df.at) 20.32s
column-wise np.frompyfunc (proposed) 1.75s
identical output: True
benchmark script
import importlib.util, time, sys
import numpy as np, pandas as pd
spec = importlib.util.spec_from_file_location("master_csv", "superset/utils/csv.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
N = 500_000
rng = np.random.default_rng(0)
words = np.array(["alpha", "beta", "gamma", "delta", "=SUM(A1)", "-5", "@cmd", "x|y", "", "한글"], dtype=object)
data = {f"s{i}": rng.choice(words, N) for i in range(10)}
data.update({f"n{i}": rng.integers(-1000, 1000, N) for i in range(5)})
data["nullable_int"] = pd.Series(np.where(rng.random(N) < 0.1, None, rng.integers(0, 9, N)).astype(object))
df = pd.DataFrame(data)
def t(label, fn):
s = time.perf_counter(); out = fn(); print(f"{label:<44} {time.perf_counter()-s:7.2f}s"); return out
t("to_csv only (no escaping)", lambda: df.to_csv(index=False))
cur = t("master df_to_escaped_csv (per-cell df.at)", lambda: m.df_to_escaped_csv(df.copy(), index=False))
def column_wise(d, **kw):
d = d.copy()
esc = np.frompyfunc(lambda v: m.escape_value(v) if isinstance(v, str) else v, 1, 1)
for i in range(d.shape[1]):
if pd.api.types.is_string_dtype(d.dtypes.iloc[i]):
col = d.iloc[:, i]
d.isetitem(i, pd.Series(esc(col.to_numpy()), index=col.index, dtype=object))
return d.to_csv(escapechar="\\", **kw)
new = t("column-wise np.frompyfunc (proposed)", lambda: column_wise(df, index=False))
print("identical output:", cur == new)Proposed fix. Apply the same escape_value once per string column and write the column back once, keeping it an object column:
escape_column = np.frompyfunc(escape_values, 1, 1)
for position in range(df.shape[1]):
if pd.api.types.is_string_dtype(df.dtypes.iloc[position]):
column = df.iloc[:, position]
df.isetitem(
position,
pd.Series(escape_column(column.to_numpy()), index=column.index, dtype=object),
)- The escaping rules don't change: the same function runs on every string cell, and non-strings are returned as-is.
- It works by position, so non-default and duplicate labels are handled the same way as the current label-based loop.
Pitfall to avoid. We first tried Series.map. It re-infers the dtype, so an object column like [1, None, 3] becomes float64 and exports as 1.0/3.0. Superset returns nullable BigQuery INT64 columns in exactly this shape, so the bug is easy to hit (related: #20151). datetime objects also gained a .000000 suffix. np.frompyfunc avoids both problems.
We have run the np.frompyfunc version in production on 6.0.1 as a local patch. Its output matched the current implementation on all 632 comparison cases:
- ints, big ints, bool,
Decimal,date,datetime,pd.NA, lists and bytes, each mixed with NULLs - formula-like strings and non-ASCII headers
- empty frames
- 300 randomized frames
- each case with and without the index
The 810k-row export produced byte-identical output (same md5). End to end, that export dropped from ~13 min to under 3 min on the Graviton2 pod.
I'm happy to open a PR with this change and tests.
Screenshots/recordings
No response
Superset version
master / latest-dev (also reproduced on 6.0.1)
Python version
3.10 (not in the dropdown; the code path is not version-specific)
Node version
Not applicable
Browser
Not applicable
Additional context
No stack trace. The request is slow, not failing; the 504 comes from the gateway timeout.
Checklist
- I have searched Superset docs and Slack and didn't find a solution to my problem.
- I have searched the GitHub issue tracker and didn't find a similar bug report.
- I have checked Superset's logs for errors and if I found a relevant Python stacktrace, I included it here as text in the "additional context" section.
Activity
itzmzn commentedon Nov 27, 2026
Cause
This line is slow:
It runs one time for every string cell. A big file has millions of cells, so it takes a long time. The
to_csvpart is fast.Fix
Work on one column at a time, not one cell at a time:
Notes
np.frompyfunc, notSeries.map.mapchanges the data type. For example,[1, None, 3]becomes[1.0, NaN, 3.0].escape_valueis not changed. The escape rules are the same as before.Test result
Data: 200,000 rows, 10 string columns, 1 number column.
The CSV output is the same.
I also tested mixed data (numbers, empty values, dates, decimals, true/false, and text that starts with
=or-). The output was the same as the old code.bumhwan commentedon Nov 27, 2026
Thanks for looking into this. I've opened #46627 with the same approach: column-wise
np.frompyfuncinstead of per-celldf.at, keeping each column's original dtype so nullable integers aren't re-inferred.It also covers a few cases beyond the snippet above:
strcolumns. master now runs pandas 3.1, where the per-cell loop grows faster than linearly: 160k rows take 83s vs 0.56s.Reviews are welcome there.
itzmzn commentedon Nov 27, 2026
bumhwan commentedon Nov 27, 2026
Thanks