Doc_chelvyn/Mito/Performa/Mito — Audit Memory Limit S...

797 lines
33 KiB
Markdown
Raw Permalink Normal View History

---
proyek: Mito
modul: mito_base · sale_product_pack · config
odoo: "18.0"
kategori: Performa
periode: 2026-09-30
status: 🔄 P0 fixed di repo (belum deploy) · P1–P2 belum dikerjakan
sumber: audit kode langsung (repo mito_odoo, branch cj/prod @ 6928229)
tags:
- mito
- performa
- memory
- sale-order
- audit
---
> Index: [[Mito — Index]] · Kategori: **Performa**
>
> Audit penyebab **memory limit / OOM** dari sisi kode saat user **add product di SO**.
> Biang keroknya satu: `_compute_snk_current_credit_limit_so` yang men-`search()`
> seluruh invoice customer setiap kali `amount_total` berubah. Dokumen ini berisi
> mekanisme lengkapnya, 6 temuan pendukung, dan kenapa memory-nya tidak pernah turun lagi.
# Audit Memory Limit — SO Add Product (MITO)
**Keluhan awal:** SO berat banget saat add product; line SO terasa lambat, server kena memory limit.
**Metode:** audit statis kode `sale.order` / `sale.order.line` di seluruh addons path Mito,
ditelusuri sampai ke source Odoo 18 core untuk membuktikan mekanismenya.
**Cakupan file yang diaudit:**
```
mito/mito_base/models/sale/sale_order.py 909 baris
mito/mito_base/models/sale/sale_order_line.py 453 baris
mito/mito_base/views/sale/sale_order_views.xml 166 baris
mito/snk_jobsheet_operation/models/sale_order.py 75 baris
addons_snk/sale_product_pack/models/ 169 + 66 baris
jubelio_connector/models/sale/sale_order.py 34 baris
addons_snk/base_tier_validation/models/tier_validation.py
config/odoo.conf · docker-compose.yml
```
---
## Ringkasan Prioritas
| # | Temuan | Lokasi | Dampak |
|---|---|---|---|
| 1 | `search()` semua invoice customer, dipicu `amount_total` | `sale_order.py:431-450` | **Memory bomb.** Terukur 34 MB + 598 ms per klik (5.000 invoice) |
| 2 | `store=True` di field yang stale + tampil di view | `sale_order.py:103` · `views/…:26` | Compute jalan 2× (onchange + save) |
| 3 | 7 `_logger.info` f-string di compute panas + `log_level=debug` | `sale_order.py:446-510` · `odoo.conf` | Alokasi + I/O sia-sia tiap onchange |
| 4 | Tab Discount: M2M non-stored × 22 kolom Monetary | `sale_order.py:272` · `views/…:131` | Payload onchange 2× lipat |
| 5 | `compute_all()` per line tanpa cache | `sale_order_line.py:86` | N× tax computation per save |
| 6 | `sale_product_pack` onchange + write hook | `addons_snk/sale_product_pack/` | Overhead; cek apakah dipakai |
| 7 | Threaded mode + `limit_time=0` + no memory limit | `odoo.conf` · `docker-compose.yml` | Tidak ada jaring pengaman; RSS ratchet |
---
## 🔴 P0 — `_compute_snk_current_credit_limit_so`
> [!success] Status: sudah di-fix di repo — **belum dideploy**
> Tanggal fix: **2026-09-30** · Branch: `cj/prod` · File: `mito/mito_base/models/sale/sale_order.py:431-469`
>
> Klasifikasi: **code-only fix** (tidak menyentuh struktur DB).
> Sesuai [[Mito — Upgrade Playbook Production]] **Bagian B**:
> tidak perlu `-u`, tidak perlu migration, tidak perlu version bump —
> **tapi WAJIB restart container Odoo di kedua app server**, karena Python module
> di-cache di memori proses.
>
> Yang **belum** dikerjakan dari P0: keputusan soal `store=True` (butuh migration
> drop kolom) — lihat callout di akhir bagian ini.
**File:** `mito/mito_base/models/sale/sale_order.py:431-450`
```python
@api.depends('partner_id', 'amount_total') # ← amount_total!
def _compute_snk_current_credit_limit_so(self):
for order in self:
total_in_payment = 0.0
if order.partner_id:
all_moves = self.env['account.move'].search([ # ← TANPA limit, TANPA filter state
('partner_id', '=', order.partner_id.id),
('move_type', 'in', ['out_invoice', 'out_refund']),
])
# 🔥 Filter manual pakai Python (karena status_in_payment bukan searchable)
unpaid_moves = all_moves.filtered(lambda m: m.status_in_payment == 'not_paid')
total_in_payment = sum(unpaid_moves.mapped('amount_total_in_currency_signed'))
_logger.info(f"[DEBUG] SO {order.name}: Total unpaid invoice = {total_in_payment}")
total_credit = total_in_payment + order.amount_total
_logger.info(f"[DEBUG] SO {order.name}: Current Credit Limit SO = {total_credit}")
order.snk_current_credit_limit_so = total_credit
```
### Rantai pemicunya
```
User add product
└→ order_line.price_subtotal berubah
└→ amount_total recompute
└→ _compute_snk_current_credit_limit_so JALAN
└→ search() SEMUA invoice customer (bisa ribuan baris, no limit)
└→ .filtered() baca status_in_payment
└→ Odoo _fetch_field() prefetch SELURUH kolom account_move
```
### Kenapa ini memory bomb, bukan cuma slow
Di `odoo/models.py:4101`, `_fetch_field()` mengambil **semua field di prefetch group
yang sama** — bukan cuma field yang diminta:
```python
def _fetch_field(self, field):
if self._context.get('prefetch_fields', True) and field.prefetch:
fnames = [
name
for name, f in self._fields.items()
if f.prefetch == field.prefetch # ← hampir semua field stored
if f.is_accessible(self.env)
]
self.fetch(fnames)
```
Jadi akses satu field (`status_in_payment` → `state` + `payment_state`) menarik
seluruh kolom `account_move` ke ORM cache. Dan `account.move` di Mito adalah model
**paling gendut di sistem**:
| Sumber | Jumlah field |
|---|---|
| `account` standar (Odoo 18) | 130 |
| `mito_base/models/account/snk_account_move.py` | 79 |
| `accounting_advance/payment_request` | 10 |
| `snk_moka_pos_integration` | 9 |
| `snk_base_coretax` | 5 |
| `ematerai_integration` | 4 |
| `currency_rate` · `snk_jobsheet_operation` | 3 + 3 |
| `cash_request` · `advance_budget` · `snk_ezmaterai` | 2 + 1 + 1 |
| **Subtotal custom** | **117** |
| Belum termasuk `sale`, `stock`, `l10n_id`, `mail`, `account_edi`, … | ~50+ |
**Angka terukur (2026-09-30, DB `MITO_DEV_JUN`):** `account_move` punya
**168 kolom** aktual di database.
> [!note] Koreksi angka
> Draft pertama menyebut "~300 kolom". Itu hasil menghitung deklarasi `fields.`
> di source, yang ikut menghitung compute/related **non-stored** — dan itu tidak
> membuat kolom DB. Angka sebenarnya di dev DB: **168 kolom**.
> Production bisa beda kalau modul terpasangnya beda — ukur sendiri dengan query
> di bagian *Langkah Verifikasi*.
Customer dengan 5.000 invoice = 5.000 × 168 = **840.000 cell** masuk cache Python
untuk **satu kali klik add product**. Terukur: **34,0 MB, 5.000 record di ORM
cache, 598 ms** — per klik.
> [!danger] Jalan dua kali
> Field ini `store=True` (`sale_order.py:103`) **dan** dipasang di form view
> (`views/sale/sale_order_views.xml:26`). Jadi compute jalan sekali saat **onchange**
> (in-memory, NewId) dan sekali lagi saat **save** (flush recompute).
> Tidak ada guard `isinstance(order.id, models.NewId)`.
### KOREKSI 2026-09-30 — komentar di kode itu BENAR, saya yang salah
> [!danger] Klaim awal audit ini salah dan sudah dicabut
> Draft pertama dokumen ini menyatakan komentar di kode keliru dan
> `status_in_payment` bisa dipakai di domain. **Itu salah untuk build yang
> benar-benar jalan di Mito.** Klaim itu datang dari checkout
> `odoo18comunity` lokal, yang ternyata lebih baru daripada image production
> (`18.0-20250918`).
>
> Di modul `account` yang benar-benar di-load container
> (`/usr/lib/python3/dist-packages/odoo/addons/account/models/account_move.py:556`):
>
> ```python
> status_in_payment = fields.Selection(
> selection=PAYMENT_STATE_SELECTION + [('draft', "Draft"), ('cancel', "Cancelled")],
> compute='_compute_status_in_payment',
> copy=False,
> )
> ```
>
> **Tidak ada `search=`. Tidak ada `store=True`.** Jadi komentar aslinya
> — `# 🔥 Filter manual pakai Python (karena status_in_payment bukan searchable)` —
> **benar**. Cara kerjanya yang bermasalah, bukan alasannya.
### Dan konsekuensinya lebih buruk dari error biasa
Fix versi pertama (yang sempat dipasang) memakai
`('status_in_payment', '=', 'not_paid')` di domain. Odoo **tidak** raise untuk
field non-searchable — dia **membuang leaf-nya secara senyap**:
`odoo/osv/expression.py:1166-1174`
```python
elif not field.store:
# Non-stored field should provide an implementation of search.
if not field.search:
# field does not support search!
_logger.error("Non-stored field %s cannot be searched.", field, exc_info=True)
...
# Ignore it: generate a dummy leaf.
domain = []
```
Jadi domainnya berubah menjadi:
```python
[('partner_id', 'in', ...), ('move_type', 'in', ...)] # ← filter status HILANG
```
Hasilnya: menjumlahkan **SEMUA** invoice customer — termasuk `draft`, `cancel`, dan
yang sudah `paid`. **Angka credit limit salah, tanpa exception apa pun.** Hanya
satu baris ERROR di log yang mudah terlewat.
Terukur di load test: ground truth `3.000.000.000` vs versi salah `5.000.000.000`.
**Kenapa hampir lolos:** benchmark pertama melaporkan "hasil identik ✓" karena
data seed saat itu seragam `posted/not_paid` — filter ada atau tidak, angkanya
sama. Seed sekarang sengaja dicampur state (lihat `tools/loadtest/README.md`),
plus ada kontrol negatif yang wajib terdeteksi salah.
### Yang akhirnya dipakai: expand ke field stored
Referensi lama (untuk versi Odoo yang **lebih baru** dari image Mito — tidak
berlaku di sini, disimpan sebagai catatan):
`odoo/addons/account/models/account_move.py:564-570`
```python
status_in_payment = fields.Selection(
selection=PAYMENT_STATE_SELECTION + [('draft', "Draft"), ('cancel', "Cancelled")],
search='_search_status_in_payment', # ← searchable
compute='_compute_status_in_payment',
copy=False,
)
```
`account_move.py:1278-1297` — `_search_status_in_payment()` menerima operator
`=`, `!=`, `in`, `not in` dan menerjemahkannya ke domain `state` / `payment_state`.
`account_move.py:1299-1308` — ada `_field_to_sql()`, jadi field ini bisa dipakai
di domain **dan** di `read_group`:
```python
def _field_to_sql(self, alias, fname, query=None, flush=True):
if fname == 'status_in_payment':
return SQL("CASE "
f"WHEN {alias}.state = 'draft' THEN 'draft' "
f"WHEN {alias}.state = 'cancel' THEN 'cancel' "
f"ELSE {alias}.payment_state "
"END")
```
**Versi lama yang di-comment** (`sale_order.py:412-428`) sebenarnya sudah benar arahnya,
cuma sintaksnya salah — pakai `=` dengan list:
```python
('status_in_payment', '=', ['not_paid']), # ← salah, harusnya 'in'
```
Bukan diperbaiki jadi `'in'`, filternya malah **dibuang total** dan diganti
`.filtered()` Python. Di situlah bug memory-nya lahir.
### Fix — agregasi di PostgreSQL, nol record ke cache
**Kode yang benar-benar dipasang** (2026-09-30):
```python
@api.depends('partner_id', 'amount_total')
def _compute_snk_current_credit_limit_so(self):
unpaid_by_partner = {}
partners = self.partner_id
if partners:
# 1 query agregat untuk seluruh recordset, nol record masuk cache.
groups = self.env['account.move']._read_group(
domain=[
('partner_id', 'in', partners.ids),
('move_type', 'in', ('out_invoice', 'out_refund')),
# JANGAN pakai status_in_payment di sini — tidak searchable di
# build ini, dan leaf-nya dibuang SENYAP oleh expression.py.
('state', 'not in', ('draft', 'cancel')),
('payment_state', '=', 'not_paid'),
],
groupby=['partner_id'],
aggregates=['amount_total_in_currency_signed:sum'],
)
unpaid_by_partner = {partner.id: total for partner, total in groups}
for order in self:
total_in_payment = unpaid_by_partner.get(order.partner_id.id, 0.0)
total_credit = total_in_payment + order.amount_total
_logger.debug(
"[SNK CREDIT LIMIT] SO %s: unpaid invoice=%s, credit limit=%s",
order.name, total_in_payment, total_credit,
)
order.snk_current_credit_limit_so = total_credit
```
**Yang didapat:**
| Aspek | Sebelum | Sesudah |
|---|---|---|
| Query | 1 `search` + 1–2 `SELECT` lebar **per order** | **1 query agregat** untuk seluruh recordset |
| Record ke ORM cache | 5.000 record × 168 kolom | **0** (terukur) |
| Data yang dibaca | seluruh baris invoice | 1 baris agregat per partner |
| Logging | 2× `_logger.info` f-string per order (eager) | 1× `_logger.debug` lazy |
### Keputusan teknis yang diambil saat fix
**1. Pakai `_read_group`, bukan `read_group`.**
Odoo 18 punya dua-duanya (`odoo/models.py:1965` dan `:2806`). `_read_group`
mengembalikan tuple langsung — tanpa overhead bikin dict `__domain` / `__count`
yang tidak dipakai. Pola ini **sudah dipakai di Mito**
(`mito_base/models/inventory/snk_stock_opname.py:569`), jadi konsisten dengan kode sekitarnya.
**2. Filter tetap `'not_paid'` saja — logika bisnis TIDAK diubah.**
Draft audit sempat mengusulkan `('not_paid', 'partial')`. Itu **tidak dipakai**
karena akan mengubah angka credit limit (invoice bayar sebagian jadi ikut dihitung).
Perubahan logika bisnis butuh persetujuan terpisah — lihat *Yang Masih Perlu Diputuskan*.
**3. Ekuivalen dengan versi lama — dan ini DIUJI, bukan cuma dinalar.**
Filter di-expand manual ke dua field yang **stored** (jadi benar-benar searchable):
```python
('state', 'not in', ('draft', 'cancel')),
('payment_state', '=', 'not_paid'),
```
Dasarnya definisi `_compute_status_in_payment`:
`move.state if move.state in ('draft','cancel') else move.payment_state`
→ `status_in_payment == 'not_paid'` ⟺ `state ∉ (draft, cancel)` **AND**
`payment_state == 'not_paid'`.
`payment_state` stored (`account_move.py:549-555`, `store=True`), `state` stored.
Keduanya aman di domain **dan** di `_read_group`.
Diverifikasi terhadap **ground truth SQL murni**, bukan cuma dibandingkan dengan
implementasi lama — lihat tabel hasil test di bawah.
**4. `ir.rule` tetap berlaku sama.**
`_read_group` lewat `_search()`, jadi rule `rule_account_move_operating_unit`
(`mito_base/models/base/ir_rule.py`) tetap diterapkan persis seperti `search()` sebelumnya.
Tidak ada kebocoran data antar operating unit.
**5. Lebih tahan NewId daripada versi lama.**
`partners.ids` memakai `origin_ids()` (`odoo/models.py:296-300`) yang otomatis
membuang `NewId` tanpa origin, jadi domain selalu berisi integer asli.
Versi lama meneruskan `order.partner_id.id` — yang bisa berupa `NewId` — langsung ke
`search()`. Jadi kalau user quick-create customer dari form SO, versi lama berpotensi
error; versi baru aman (`.get(NewId, 0.0)` → `0.0`).
> [!warning] Keputusan yang perlu diambil: `store=True` di field ini salah secara fungsional
> Dependency-nya cuma `partner_id` + `amount_total`. Kalau invoice customer dibayar,
> nilai tersimpan di SO **tidak ikut update** — tidak ada depends ke `account.move`.
> Jadi field ini **expensive sekaligus stale**. Fix `_read_group` di atas menghilangkan
> masalah memory-nya, **tapi tidak menghilangkan masalah stale-nya.**
>
> **Hasil pengecekan kode (2026-09-30):** `snk_current_credit_limit_so` hanya muncul di
> **2 tempat** — definisi field (`sale_order.py:103`) dan form view
> (`sale_order_views.xml:26`). **Tidak ada report, tidak ada BI, tidak ada kode lain**
> yang membacanya. Jadi secara kode, opsi A aman.
>
> **Belum bisa dipastikan:** apakah ada SQL view di `bi_sql_editor` / `query_deluxe`
> di DB production yang mereferensikan kolom ini. Ini harus dicek di DB dulu sebelum drop.
> [!warning] Keputusan yang perlu diambil: `store=True` di field ini salah secara fungsional
> Dependency-nya cuma `partner_id` + `amount_total`. Kalau invoice customer dibayar,
> nilai tersimpan di SO **tidak ikut update** — tidak ada depends ke `account.move`.
> Jadi field ini **expensive sekaligus stale**.
>
> Pilihan:
> - **A (disarankan)** — buang `store=True`. Nilainya cuma untuk dilihat di form, tidak dipakai report.
> - **B** — kalau memang dipakai report, pindahkan perhitungannya ke cron / `snk_queue_job`, jangan di jalur onchange.
>
> Perlu konfirmasi: apakah `snk_current_credit_limit_so` dipakai di report/BI mana pun?
---
## 🟠 P1 — Logging di dalam compute panas + `log_level = debug`
**File:** `sale_order.py` baris `446`, `449`, `461`, `476`, `486`, `493`, `510`
```python
_logger.info(f"[SNK COMPUTE AMOUNTS] SO {order.name}: Total lines={len(all_lines)}, Non-bundle lines={len(order_lines)}")
_logger.info(f"[SNK COMPUTE AMOUNTS] SO {order.name}: Untaxed={order.amount_untaxed}, Tax={order.amount_tax}, Total={order.amount_total}")
_logger.info(f"[SNK UNDISCOUNTED] SO {order.name}: Undiscounted={order.amount_undiscounted}")
_logger.info(f"[SNK TO INVOICE] SO {order.name}: To Invoice={order.amount_to_invoice}")
_logger.info(f"[SNK TAX TOTALS] SO {order.name}: Tax totals computed (excluding bundle)")
```
7 `_logger.info` tersebar di `_compute_amounts`, `_compute_tax_totals`,
`_compute_amount_undiscounted`, `_compute_amount_to_invoice`, dan
`_compute_snk_current_credit_limit_so` — **semuanya jalan tiap add product**.
Masalahnya berlapis:
1. **f-string di-evaluasi sebelum logger memutuskan mau log atau tidak.**
`order.name` + `len()` + akses `amount_total` jalan tanpa syarat, walaupun
level log-nya nanti di-filter.
2. `config/odoo.conf` set `log_level = debug` → semua ini **benar-benar ditulis**
ke `/etc/odoo/odoo.log`.
3. `_compute_amount_to_invoice` mengakses `order.amount_to_invoice` **di dalam log
line-nya sendiri**, tepat setelah di-assign — memaksa flush cache.
Ini bukan penyebab OOM langsung, tapi menambah alokasi string + I/O di jalur
terpanas, dan bikin log membengkak sampai error yang sebenarnya susah dicari.
**Fix:**
- Turunkan ke `_logger.debug` dengan **lazy formatting**: `_logger.debug("... %s", order.name)` — argumen tidak di-format kalau level-nya tidak aktif.
- Atau hapus saja; ini sisa debugging.
- `log_level = info` di `odoo.conf` untuk production.
---
## 🟠 P1 — Tab Discount: M2M compute non-stored × 22 kolom
**File:** `sale_order.py:272-289` + `views/sale/sale_order_views.xml:131-165`
```python
snk_discount_report_line_ids = fields.Many2many(
'sale.order.line',
string='Discount Report Lines',
compute='_compute_snk_discount_report_lines' # ← non-stored
)
@api.depends('order_line', 'order_line.product_id')
def _compute_snk_discount_report_lines(self):
discount_flags = [ ... 18 flag ... ]
for order in self:
order.snk_discount_report_line_ids = order.order_line.filtered(
lambda l: ... and not any(getattr(l.product_id, flag, False) for flag in discount_flags)
)
```
Tiap add product:
- Recompute → **18× `getattr`** per line
- Payload onchange mengembalikan **list kedua** berisi seluruh line dengan **22 kolom Monetary**
Di view, semua kolomnya `optional="show"` — jadi ikut di-fetch:
```xml
<field name="snk_discount_report_line_ids" mode="list" readonly="1">
<list string="Discount Lines" create="0" delete="0" editable="bottom">
<field name="snk_diskon_area" optional="show" sum="Total"/>
<field name="snk_diskon_cash" optional="show" sum="Total"/>
... 18 field diskon ...
<field name="snk_total_discount_item" optional="show" .../>
<field name="snk_nett_price" optional="show" .../>
<field name="snk_sub_total" optional="show" .../>
</list>
</field>
```
Jadi **satu klik add product = SO line list dikirim dua kali** ke browser, yang
kedua dengan 22 kolom. SO 100 line → payload onchange membengkak parah. Ini yang
bikin "SO line berat banget" terasa di sisi UI, bukan cuma di server.
**Fix:**
- Tab Discount tidak perlu live di form. Pindahkan ke tombol/action yang membuka
list view `sale.order.line` dengan domain `[('order_id','=',id)]`.
- Minimal: ganti semua `optional="show"` → `optional="hide"` supaya kolomnya tidak
di-fetch sampai user membukanya sendiri.
---
## 🟡 P2 — `_compute_snk_price_unit_dpp` memanggil `compute_all()` per line
**File:** `sale_order_line.py:86-89` → `_get_price_unit_before_tax()` `:92-124`
```python
@api.depends('price_unit', 'tax_id')
def _compute_snk_price_unit_dpp(self):
for line in self:
line.snk_price_unit_dpp = line._get_price_unit_before_tax() # ← compute_all() per line
```
`tax_id.compute_all()` mahal — membangun dict tax detail lengkap. Karena PPN
Indonesia sering `price_include`, justru jalur mahalnya yang kepakai. Field-nya
stored dengan depends `price_unit` → tiap ubah harga satu line, jalan.
Ironisnya, `_compute_snk_discounts` **di file yang sama** (`:160-180`) sudah punya
cache untuk problem yang persis sama:
```python
cache_key = (tuple(sorted(ln.tax_id.ids)), ln.price_unit)
if cache_key not in dpp_unit_cache:
res = ln.tax_id.compute_all(
ln.price_unit, currency=order.currency_id, quantity=1.0,
product=ln.product_id, partner=order.partner_id,
)
dpp_unit_cache[cache_key] = res['total_excluded']
dpp_unit = dpp_unit_cache[cache_key]
```
**Fix:** pakai pola cache yang sama di `_compute_snk_price_unit_dpp` — satu
`compute_all` per kombinasi `(tax_ids, price_unit)` unik, bukan per line.
---
## 🟡 P2 — `sale_product_pack` ikut jalan tiap add product
**File:** `addons_snk/sale_product_pack/models/sale_order.py:19-38`
```python
@api.onchange("order_line") # ← SETIAP perubahan order_line
def check_pack_line_unlink(self):
origin_line_ids = self._origin.order_line.ids
line_ids = self.order_line.ids
removed_line_ids = list(set(origin_line_ids) - set(line_ids))
removed_line = self.env["sale.order.line"].browse(removed_line_ids)
if removed_line.filtered(
lambda x: x.pack_parent_line_id
and not x.pack_parent_line_id.product_id.pack_modifiable
):
raise UserError(...)
```
**File:** `addons_snk/sale_product_pack/models/sale_order_line.py:93-98`
```python
def write(self, vals):
res = super().write(vals)
if "product_id" in vals or "product_uom_qty" in vals:
for record in self: # ← loop per record
record.expand_pack_line(write=True) # ← get_pack_lines() + filtered() per line
return res
```
Plus `create()` (`:75-91`) yang membuat line **satu per satu** (bukan batch) kalau
ada satu saja produk pack di dalam `vals_list`:
```python
if any(p.pack_ok and p.pack_type != "non_detailed" for p in products):
res = self.browse()
for elem in vals_list:
line = super().create([elem]) # ← N query, bukan 1
```
> [!question] Cek dulu: apakah Mito benar-benar pakai product pack?
> Kalau tidak, modul ini cuma menambah beban di jalur SO line tanpa manfaat apa pun.
>
> ```sql
> SELECT COUNT(*) FROM product_template WHERE pack_ok = true;
> ```
>
> - **0** → uninstall `sale_product_pack`.
> - **> 0** → guard `expand_pack_line` supaya tidak jalan untuk line non-pack.
---
## 🟡 P2 — `@api.depends` override **menambah** trigger, bukan mengganti
**File:** `sale_order.py:452`
```python
@api.depends('order_line.price_subtotal', 'order_line.snk_bundle',
'currency_id', 'company_id', 'payment_term_id')
def _compute_amounts(self):
```
Ini penting dipahami supaya tidak salah asumsi. Di `odoo/fields.py:559-596`,
`get_depends()` memakai `resolve_mro()` — depends dari **semua** override di MRO
**digabung**, tidak menimpa:
```python
def get_depends(self, model):
...
funcs = resolve_mro(model, self.compute, callable)
depends = []
for func in funcs:
deps = getattr(func, '_depends', ())
depends.extend(deps(model) if callable(deps) else deps) # ← union
return depends, depends_context
```
**Dua konsekuensi:**
1. ❌ `_compute_amounts` sekarang trigger dari depends standar **plus**
`currency_id`, `company_id`, `payment_term_id`. Ubah payment term → recompute
pajak seluruh SO, padahal tidak perlu.
2. ✅ Kabar baiknya: `_compute_tax_totals` (`:495`), `_compute_amount_undiscounted`
(`:478`), dan `_compute_amount_to_invoice` (`:488`) yang di-override **tanpa**
`@api.depends` **tidak** kehilangan dependency standarnya. Jadi **tidak ada
bug stale** di situ — ini sempat dicurigai, terbukti aman.
**Fix:** hapus `currency_id`, `company_id`, `payment_term_id` dari depends
`_compute_amounts` — depends standar sudah meng-cover apa yang perlu.
---
## 🔴 Kenapa memory-nya "limit" dan tidak pernah turun lagi
Bagian ini config, tapi langsung menjelaskan kenapa bug di atas berujung **OOM**
dan bukan cuma lambat.
**`config/odoo.conf`**
```ini
limit_time_real = 0 # ← request TIDAK PERNAH di-kill
limit_time_cpu = 0 # ← sama
# workers = ... ← TIDAK ADA
# limit_memory_soft = ... ← TIDAK ADA
# limit_memory_hard = ... ← TIDAK ADA
log_level = debug # ← lihat temuan P1
```
**`docker-compose.yml`**
```yaml
web:
command: odoo # ← tanpa --workers → THREADED mode
db:
shm_size: '256m' # ← kecil untuk volume Mito
```
Konsekuensinya berantai:
1. **Threaded mode** → `limit_memory_soft` / `limit_memory_hard` tidak di-enforce.
Odoo hanya memasang `setrlimit` per worker di mode **prefork**. Tidak ada
worker recycling sama sekali.
2. **`limit_time_real = 0`** → request yang meledak tidak pernah dihentikan; dia
terus alokasi sampai container OOM-killed.
3. Python tidak mengembalikan memory bebas ke OS dengan agresif → **RSS naik
terus (ratchet), tidak pernah turun**. Satu SO customer besar cukup untuk
menaikkan baseline permanen sampai service di-restart.
```
Bug P0 alokasi ratusan MB
→ tidak ada timeout yang membunuhnya (limit_time_real = 0)
→ tidak ada worker yang di-recycle (threaded mode)
→ RSS mentok
→ OOM
```
**Fix kode menghilangkan sumbernya; fix config memberi jaring pengaman.**
Dua-duanya perlu — lihat rekomendasi worker config di `CLAUDE.md` project (bagian
*Status Infrastruktur — CRITICAL ISSUES*).
---
## Hasil Test Terukur — 2026-09-30
Harness lengkap ada di repo: **`tools/loadtest/`** (5 script + README).
DB `MITO_DEV_JUN` · Odoo `18.0-20250918` · partner test 5.000 invoice ·
`account_move` 168 kolom.
> [!warning] Dev DB tidak bisa mereproduksi bug ini tanpa seed
> Dev DB cuma punya ~95 invoice `posted/not_paid` untuk **semua** partner, dan
> partner terbanyak ~100 invoice. Tanpa seed, test akan bilang "tidak ada bedanya"
> dan kita salah menyimpulkan fix-nya tidak perlu.
>
> Seed-nya juga **wajib mencampur state** (posted/draft/cancel/paid/partial).
> Kalau seragam, filter apa pun menghasilkan angka sama dan test tidak bisa
> menangkap bug filter yang hilang — itu yang bikin fix salah hampir lolos.
### Uji kebenaran (paling penting)
Ground truth dari SQL murni: **3.000.000.000,00**
| Implementasi | Hasil | |
|---|---|---|
| Sebelum fix (`search`+`filtered`) | 3.000.000.000,00 | ✅ benar |
| Sesudah fix (`state`+`payment_state`) | 3.000.000.000,00 | ✅ benar |
| Kontrol negatif (`status_in_payment` di domain) | 5.000.000.000,00 | ✅ tertangkap salah |
Kontrol negatif sengaja dipasang di harness supaya kalau suatu hari ada yang
menulis ulang filter ini pakai `status_in_payment`, test-nya langsung gagal.
### Performa — compute terisolasi (`02_bench_credit_limit.py`)
| | waktu | query | peak mem | move di ORM cache |
|---|---|---|---|---|
| Sebelum | 597,6 ms | 7 | 34,0 MB | 5.000 |
| Sesudah | 6,1 ms | 2 | 0,1 MB | **0** |
| **perbaikan** | **97×** | 3,5× | **634×** | ∞ |
Batch 20 SO: 1.102,6 ms → 6,6 ms (**167×**) — karena versi baru 1 query agregat
untuk seluruh recordset, sedangkan versi lama 1 `search` **per** SO.
### Performa — jalur onchange asli (`03_bench_form_50products.py`)
Pakai `odoo.tests.Form`, jalur yang sama dengan web client. Jadi angka ini mencakup
**semua** temuan, bukan cuma P0.
| | sebelum | sesudah | |
|---|---|---|---|
| total 50 line | 16,44 s | **7,28 s** | 2,3× |
| per line rata-rata | 297,7 ms | **121,9 ms** | 2,4× |
| per line p95 | 337,7 ms | 161,9 ms | |
| query per line | 120 | 115 | ~sama |
> [!important] Jumlah query BUKAN ukuran kemenangan di sini
> Versi lama menarik 5.000 baris `account_move` ke ORM cache, dan cache itu ikut
> melayani query lain sehingga total query-nya tampak mirip. Yang berbeda jauh
> adalah **volume data** dan **memory**, bukan jumlah round-trip.
>
> Dan **~115 query untuk menambah SATU line masih tinggi.** Itu biaya onchange
> Odoo standar + temuan P1/P2 yang belum di-fix. Target berikutnya.
### Beban konkuren (`04_loadtest_concurrent.py`)
| Konkurensi | sukses | throughput | p50 | p95 | p99 | RSS |
|---|---|---|---|---|---|---|
| **100 user** × 50 product | **26/100** | 23,1 write/s | 991 ms | 1.307 ms | 1.441 ms | 216→251 MB |
| **25 user** × 50 product | **25/25** | 25,9 write/s | 913 ms | 1.139 ms | 1.231 ms | 250→251 MB |
> [!danger] 74 dari 100 user GAGAL — dan itu bukan karena kode
> ```
> psycopg2.pool.PoolError: The Connection Pool Is Full (150× di log)
> config: db_maxconn = 32
> ```
> Odoo menolak request **sebelum** kodenya dijalankan sama sekali. Config sekarang
> **tidak bisa** melayani 100 user konkuren, secepat apa pun kodenya.
>
> Ini bukti langsung untuk temuan #7: `db_maxconn` terlalu kecil **dan** `workers`
> tidak di-set. Fix kode P0 tidak menolong di sini — yang perlu diperbaiki config.
**Soal RSS:** pertumbuhan terlihat kecil (+35 MB) karena beban terbesar sudah
dialokasi saat warm-up dan Python **menahan arena-nya**. Justru itu buktinya:
RSS naik ke high-water mark lalu **tidak pernah turun**. Di mode threaded tidak ada
worker recycling, jadi baseline naik permanen sampai restart.
---
## Langkah Verifikasi Sebelum Fix
Buktikan dulu hipotesis P0 di production, jangan menebak.
```sql
-- Customer mana yang paling banyak invoice? Ini yang bikin SO-nya paling berat.
SELECT p.id, p.name, COUNT(*) AS jml_invoice
FROM account_move am
JOIN res_partner p ON p.id = am.partner_id
WHERE am.move_type IN ('out_invoice', 'out_refund')
GROUP BY p.id, p.name
ORDER BY jml_invoice DESC
LIMIT 20;
-- Berapa lebar sebenarnya tabel account_move?
SELECT COUNT(*) AS jml_kolom
FROM information_schema.columns
WHERE table_name = 'account_move';
-- Apakah product pack benar-benar dipakai? (temuan P2)
SELECT COUNT(*) FROM product_template WHERE pack_ok = true;
```
**Uji A/B:** buat SO baru untuk customer nomor 1 di list itu, add product,
lalu bandingkan dengan customer yang invoice-nya sedikit.
Kalau selisih waktunya jauh → **P0 terkonfirmasi**.
---
## Rencana Eksekusi
| Urutan | Aksi | File | Butuh migration? |
|---|---|---|---|
| 1 | Verifikasi dengan 3 query di atas | — | — |
| 2 | ✅ **SELESAI 2026-09-30** — rewrite `_compute_snk_current_credit_limit_so` → `_read_group` | `sale_order.py:431-469` | Tidak |
| 2b | ⏳ Deploy: build/pull ke **kedua** app server + **restart container** (Bagian B playbook) | — | Tidak |
| 3 | **Keputusan:** buang `store=True` di `snk_current_credit_limit_so` | `sale_order.py:103` | **Ya** — hapus kolom, lihat [[Mito — Upgrade Playbook Production]] |
| 4 | `_logger.info` → `_logger.debug` lazy · `log_level = info` | `sale_order.py` · `odoo.conf` | Tidak |
| 5 | Tab Discount → `optional="hide"` atau pindah ke action | `sale_order_views.xml:131` | Tidak |
| 6 | Cache `compute_all()` di `_compute_snk_price_unit_dpp` | `sale_order_line.py:86` | Tidak |
| 7 | Cek & putuskan nasib `sale_product_pack` | `addons_snk/sale_product_pack/` | Tergantung hasil |
| 8 | Bersihkan depends berlebih di `_compute_amounts` | `sale_order.py:452` | Tidak |
| 9 | Config: `workers`, `limit_memory_*`, `limit_time_real` | `odoo.conf` · `docker-compose.yml` | Tidak — tapi perlu restart |
> [!warning] Langkah 3 menghapus kolom DB
> Kalau `store=True` dibuang, kolom `snk_current_credit_limit_so` harus di-drop lewat
> migration script — Odoo tidak pernah auto-drop kolom. Dan karena production Mito
> **2 app server share 1 RDS**, migration wajib di-commit ke repo, bukan fix manual
> di satu server. Lihat [[Mito — Upgrade Playbook Production]] dan catatan insiden drift
> `snk_financial_report`.
---
## Yang Masih Perlu Diputuskan
| Hal | Butuh apa |
|---|---|
| Ada SQL view `bi_sql_editor`/`query_deluxe` yang pakai kolom `snk_current_credit_limit_so`? | Query `pg_views` di production. Kode sudah dipastikan tidak ada yang pakai selain form view — ini pengecekan terakhir sebelum drop kolom |
| Credit limit harus ikut hitung invoice **bayar sebagian** (`partial`) atau `not_paid` saja? | Keputusan finance. Fix 2026-09-30 sengaja **mempertahankan `not_paid` saja** supaya angka tidak berubah |
| Tab Discount di SO: masih dipakai user sehari-hari? | Menentukan `optional="hide"` cukup, atau dipindah ke action terpisah |
| `sale_product_pack` dipakai? | Hasil query `pack_ok = true` → uninstall atau guard |
| Nilai `workers` untuk server production | Butuh jumlah CPU core server sebenarnya — formula `(2 × core) + 1` |
---
## Catatan
- Audit ini **statis** (baca kode + source Odoo core). Belum ada profiling runtime
(`py-spy`, `--dev=profile`, atau `EXPLAIN ANALYZE`) karena container Mito tidak
sedang jalan saat audit dilakukan.
- Belum ada file yang diubah. Semua temuan di sini masih rekomendasi.
- Area yang **diperiksa dan terbukti aman** (supaya tidak diaudit ulang):
- `_compute_tax_totals` / `_compute_amount_to_invoice` — depends standar tetap utuh (lihat P2 `@api.depends`)
- `snk_diskon_*_ok` di `product.product` — related **stored** (`snk_product_product.py:123-148`), jadi `getattr()` baca kolom, bukan traversal
- `_compute_need_validation` (`base_tier_validation/models/tier_validation.py:247`) — sudah ada early-return untuk `NewId`, murah saat onchange
- `mito_base/models/base/ir_rule.py` — one-off setter, bukan jalur panas
- Tidak ada `@api.onchange('product_id')` custom di `sale.order.line` Mito