Skip to content

Commit 9ba22c9

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 062d11a commit 9ba22c9

File tree

2 files changed

+68
-41
lines changed

2 files changed

+68
-41
lines changed

src/base/tests/test_util.py

+30-27
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
@@ -1436,33 +1437,35 @@ def not_doing_anything_converter(el):
14361437

14371438
class TestHTMLFormat(UnitTestCase):
14381439
def testsnip(self):
1439-
view_arch = """
1440-
<html>
1441-
<div class="fake_class_not_doing_anything"><br/></div>
1442-
<script>
1443-
(event) =&gt; {
1444-
};
1445-
</script>
1446-
</html>
1447-
"""
1448-
view_id = self.env["ir.ui.view"].create(
1449-
{
1450-
"name": "not_for_anything",
1451-
"type": "qweb",
1452-
"mode": "primary",
1453-
"key": "test.htmlconvert",
1454-
"arch_db": view_arch,
1455-
}
1456-
)
1457-
cr = self.env.cr
1458-
snippets.convert_html_content(
1459-
cr,
1460-
snippets.html_converter(
1461-
not_doing_anything_converter, selector="//*[hasclass('fake_class_not_doing_anything')]"
1462-
),
1463-
)
1464-
util.invalidate(view_id)
1465-
res = self.env["ir.ui.view"].search_read([("id", "=", view_id.id)], ["arch_db"])
1440+
with self.registry.cursor() as cr:
1441+
env = api.Environment(cr, SUPERUSER_ID, {})
1442+
view_arch = """
1443+
<html>
1444+
<div class="fake_class_not_doing_anything"><br/></div>
1445+
<script>
1446+
(event) =&gt; {
1447+
};
1448+
</script>
1449+
</html>
1450+
"""
1451+
view_id = env["ir.ui.view"].create(
1452+
{
1453+
"name": "not_for_anything",
1454+
"type": "qweb",
1455+
"mode": "primary",
1456+
"key": "test.htmlconvert",
1457+
"arch_db": view_arch,
1458+
}
1459+
)
1460+
snippets.convert_html_content(
1461+
cr,
1462+
snippets.html_converter(
1463+
not_doing_anything_converter, selector="//*[hasclass('fake_class_not_doing_anything')]"
1464+
),
1465+
)
1466+
util.invalidate(view_id)
1467+
res = env["ir.ui.view"].search_read([("id", "=", view_id.id)], ["arch_db"])
1468+
view_id.unlink()
14661469
self.assertEqual(len(res), 1)
14671470
oneline = lambda s: re.sub(r"\s+", " ", s.strip())
14681471
self.assertEqual(oneline(res[0]["arch_db"]), oneline(view_arch))

src/util/snippets.py

+38-14
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# -*- coding: utf-8 -*-
2+
import concurrent
23
import inspect
34
import logging
45
import re
@@ -11,6 +12,11 @@
1112
from psycopg2.extensions import quote_ident
1213
from psycopg2.extras import Json
1314

15+
try:
16+
from odoo.sql_db import db_connect
17+
except ImportError:
18+
from openerp.sql_db import db_connect
19+
1420
from .const import NEARLYWARN
1521
from .exceptions import MigrationError
1622
from .helpers import table_of_model
@@ -243,16 +249,26 @@ def _dumps(self, node):
243249

244250

245251
class Convertor:
246-
def __init__(self, converters, callback):
252+
def __init__(self, converters, callback, dbname, update_query):
247253
self.converters = converters
248254
self.callback = callback
255+
self.dbname = dbname
256+
self.update_query = update_query
257+
258+
def __call__(self, query):
259+
with db_connect(self.dbname).cursor() as cr:
260+
cr.execute(query)
261+
for self.row in cr.fetchall():
262+
self._convert_row()
263+
if "id" in self.changes:
264+
cr.execute(self.update_query, self.changes)
249265

250-
def __call__(self, row):
266+
def _convert_row(self):
251267
converters = self.converters
252268
columns = self.converters.keys()
253269
converter_callback = self.callback
254-
res_id, *contents = row
255-
changes = {}
270+
res_id, *contents = self.row
271+
self.changes = {}
256272
for column, content in zip(columns, contents):
257273
if content and converters[column]:
258274
# jsonb column; convert all keys
@@ -264,10 +280,10 @@ def __call__(self, row):
264280
new_content = Json(new_content)
265281
else:
266282
has_changed, new_content = converter_callback(content)
267-
changes[column] = new_content
283+
self.changes[column] = new_content
268284
if has_changed:
269-
changes["id"] = res_id
270-
return changes
285+
self.changes["id"] = res_id
286+
return self.changes
271287

272288

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

324+
cr.commit()
308325
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)
326+
convert = Convertor(converters, converter_callback, cr.dbname, update_query)
327+
futures = [executor.submit(convert, query) for query in split_queries]
328+
for future in log_progress(
329+
concurrent.futures.as_completed(futures),
330+
logger=_logger,
331+
qualifier=f"{table} updates",
332+
size=len(split_queries),
333+
estimate=False,
334+
log_hundred_percent=True,
335+
):
336+
# just for raising any worker exception
337+
future.result()
338+
cr.commit()
315339

316340

317341
def determine_chunk_limit_ids(cr, table, column_arr, where):
318-
bytes_per_chunk = 100 * 1024 * 1024
342+
bytes_per_chunk = 10 * 1024 * 1024
319343
columns = ", ".join(quote_ident(column, cr._cnx) for column in column_arr if column != "id")
320344
cr.execute(
321345
f"""

0 commit comments

Comments
 (0)