Skip to content

Commit fe9b2c8

Browse files
committed
[IMP] snippets: move all work from parent to mp workers
In `convert_html_columns()`, we select 100MiB worth of DB tuples and pass them to a ProcessPoolExecutor together with a converter callable. So far, the converter returns all tuples, changed or unchanged together with the information if it has changed something. All this is returned through IPC to the parent process. In the parent process, the caller only acts on the changed tuples, though, the rest is ignored. In any scenario I've seen, only a small proportion of the input tuples is actually changed, meaning that a large proportion is returned through IPC unnecessarily. What makes it worse is that processing of the converted results in the parent process is often slower than the conversion, leading to two effects: 1) The results of all workers sit in the parent process's memory, possibly leading to MemoryError (upg-2021031) 2) The parallel processing is being serialized on the feedback, defeating a large part of the intended performance gains To improve this, this commit - moves all work into the workers, meaning not just the conversion filter, but also the DB query as well as the DB updates. - by doing so reduces the amount of data passed by IPC to just the query texts - by doing so distributes the data held in memory to all worker processes - reduces the chunk size by one order of magnitude, which means - a lot less memory used at a time - a lot better distribution of "to-be-changed" rows when these rows are clustered in the table All in all, in my test case, this - reduces maximum process size in memory to 300MiB for all processes compared to formerly >2GiB (and MemoryError) in the parent process - reduces runtime from 17 minutes to less than 2 minutes
1 parent 36dbf4c commit fe9b2c8

File tree

2 files changed

+63
-37
lines changed

2 files changed

+63
-37
lines changed

src/base/tests/test_util.py

Lines changed: 32 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
except ImportError:
1414
import mock
1515

16+
from odoo import SUPERUSER_ID, api
1617
from odoo.osv.expression import FALSE_LEAF, TRUE_LEAF
1718
from odoo.tools import mute_logger
1819
from odoo.tools.safe_eval import safe_eval
@@ -1443,33 +1444,37 @@ def not_doing_anything_converter(el):
14431444

14441445
class TestHTMLFormat(UnitTestCase):
14451446
def testsnip(self):
1446-
view_arch = """
1447-
<html>
1448-
<div class="fake_class_not_doing_anything"><br/></div>
1449-
<script>
1450-
(event) =&gt; {
1451-
};
1452-
</script>
1453-
</html>
1454-
"""
1455-
view_id = self.env["ir.ui.view"].create(
1456-
{
1457-
"name": "not_for_anything",
1458-
"type": "qweb",
1459-
"mode": "primary",
1460-
"key": "test.htmlconvert",
1461-
"arch_db": view_arch,
1462-
}
1463-
)
1464-
cr = self.env.cr
1465-
snippets.convert_html_content(
1466-
cr,
1467-
snippets.html_converter(
1468-
not_doing_anything_converter, selector="//*[hasclass('fake_class_not_doing_anything')]"
1469-
),
1470-
)
1471-
util.invalidate(view_id)
1472-
res = self.env["ir.ui.view"].search_read([("id", "=", view_id.id)], ["arch_db"])
1447+
# util.convert_html_columns() commits the cursor, use a new transaction to not mess up the test_cr
1448+
with self.registry.cursor() as cr:
1449+
env = api.Environment(cr, SUPERUSER_ID, {})
1450+
view_arch = """
1451+
<html>
1452+
<div class="fake_class_not_doing_anything"><br/></div>
1453+
<script>
1454+
(event) =&gt; {
1455+
};
1456+
</script>
1457+
</html>
1458+
"""
1459+
view_id = env["ir.ui.view"].create(
1460+
{
1461+
"name": "not_for_anything",
1462+
"type": "qweb",
1463+
"mode": "primary",
1464+
"key": "test.htmlconvert",
1465+
"arch_db": view_arch,
1466+
}
1467+
)
1468+
snippets.convert_html_content(
1469+
cr,
1470+
snippets.html_converter(
1471+
not_doing_anything_converter, selector="//*[hasclass('fake_class_not_doing_anything')]"
1472+
),
1473+
)
1474+
util.invalidate(view_id)
1475+
res = env["ir.ui.view"].search_read([("id", "=", view_id.id)], ["arch_db"])
1476+
# clean up committed data
1477+
view_id.unlink()
14731478
self.assertEqual(len(res), 1)
14741479
oneline = lambda s: re.sub(r"\s+", " ", s.strip())
14751480
self.assertEqual(oneline(res[0]["arch_db"]), oneline(view_arch))

src/util/snippets.py

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
# -*- coding: utf-8 -*-
2+
import concurrent
3+
import contextlib
24
import inspect
35
import logging
46
import re
@@ -11,6 +13,9 @@
1113
from psycopg2.extensions import quote_ident
1214
from psycopg2.extras import Json
1315

16+
with contextlib.suppress(ImportError):
17+
from odoo.sql_db import db_connect
18+
1419
from .const import NEARLYWARN
1520
from .exceptions import MigrationError
1621
from .helpers import table_of_model
@@ -243,11 +248,19 @@ def _dumps(self, node):
243248

244249

245250
class Convertor:
246-
def __init__(self, converters, callback):
251+
def __init__(self, converters, callback, dbname, update_query):
247252
self.converters = converters
248253
self.callback = callback
254+
self.dbname = dbname
255+
self.update_query = update_query
256+
257+
def __call__(self, query):
258+
with db_connect(self.dbname).cursor() as cr:
259+
cr.execute(query)
260+
for changes in filter(None, map(self._convert_row, cr.fetchall())):
261+
cr.execute(self.update_query, changes)
249262

250-
def __call__(self, row):
263+
def _convert_row(self, row):
251264
converters = self.converters
252265
columns = self.converters.keys()
253266
converter_callback = self.callback
@@ -267,7 +280,7 @@ def __call__(self, row):
267280
changes[column] = new_content
268281
if has_changed:
269282
changes["id"] = res_id
270-
return changes
283+
return changes if "id" in changes else None
271284

272285

273286
def convert_html_columns(cr, table, columns, converter_callback, where_column="IS NOT NULL", extra_where="true"):
@@ -305,17 +318,25 @@ def convert_html_columns(cr, table, columns, converter_callback, where_column="I
305318
update_sql = ", ".join(f'"{column}" = %({column})s' for column in columns)
306319
update_query = f"UPDATE {table} SET {update_sql} WHERE id = %(id)s"
307320

321+
cr.commit()
308322
with ProcessPoolExecutor(max_workers=get_max_workers()) as executor:
309-
convert = Convertor(converters, converter_callback)
310-
for query in log_progress(split_queries, logger=_logger, qualifier=f"{table} updates"):
311-
cr.execute(query)
312-
for data in executor.map(convert, cr.fetchall(), chunksize=1000):
313-
if "id" in data:
314-
cr.execute(update_query, data)
323+
convert = Convertor(converters, converter_callback, cr.dbname, update_query)
324+
futures = [executor.submit(convert, query) for query in split_queries]
325+
for future in log_progress(
326+
concurrent.futures.as_completed(futures),
327+
logger=_logger,
328+
qualifier=f"{table} updates",
329+
size=len(split_queries),
330+
estimate=False,
331+
log_hundred_percent=True,
332+
):
333+
# just for raising any worker exception
334+
future.result()
335+
cr.commit()
315336

316337

317338
def determine_chunk_limit_ids(cr, table, column_arr, where):
318-
bytes_per_chunk = 100 * 1024 * 1024
339+
bytes_per_chunk = 10 * 1024 * 1024
319340
columns = ", ".join(quote_ident(column, cr._cnx) for column in column_arr if column != "id")
320341
cr.execute(
321342
f"""

0 commit comments

Comments
 (0)