-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
1403 lines (1126 loc) · 45 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>reveal.js</title>
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/league.css">
<!-- Theme used for syntax highlighting of code -->
<link rel="stylesheet" href="lib/css/zenburn.css">
<link rel="stylesheet" href="css/fitn.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
</head>
<body>
<div class="reveal">
<div class="slides">
<section data-background="resources/pictures/background-plane_crash.jpg">
<section class="vsep left">
<div class="left">
<img src="resources/me.jpg" />
</div>
<div class="right">
<h2>Romain Monceau</h2>
<ul class="contacts">
<li><img src="resources/icons/twitter.png" class="icon" />@RomainMonceau</li>
<li><img src="resources/icons/birthday.png" class="icon" />~ 25 years old</li>
<li><img src="resources/icons/php.png" class="icon" />+15 years</li>
<li><img src="resources/icons/akeneo.png" class="icon" /> Lead Developer @Akeneo </li>
</ul>
</div>
<aside class="notes">
Akeneo<br />
Solution PIM opensource -> outil de gestion de catalogues produits destinés aux équipes marketing<br />
Enrichir les données puis diffusion sur des canaux de vente<br />
Travail sur des volumétries de 10M de produits<br />
Retour d'XP<br />
</aside>
</section>
<section>
<h2>The worst best idea:</h2>
<h4>Doing batch with PHP and Doctrine</h4>
<aside class="notes">
Problèmes rencontrés chez Akeneo avec Doctrine et les traitements de masse<br />
Qui travaille sur un projet qui utilise Doctrine ?<br />
Apprendre des choses, astuces<br />
Pourquoi ce titre ?<br />
</aside>
</section>
<section>
<div><img src="resources/icons/php.png" class="medium-icon" /></div>
<h3>PHP has not been done for batch processes</h3>
<ul>
<li>HTTP requests</li>
<li>Timeout</li>
<li>Memory consumption</li>
</ul>
<aside class="notes">
Pas de cli à l'origine<br />
Stack qui évolue toujours bien entendu<br />
</aside>
</section>
<section>
<div><img src="resources/icons/doctrine-orm.png" class="medium-icon" /></div>
<h3>Doctrine has not been done for batch processes</h3>
<img src="resources/img/doctrine_batch_doc.png" />
<aside class="notes">
First error! Ne pas lire la doc<br />
Pester sur Doctriner pour corriger NOS erreurs<br />
Puis on s'est rendu compte qu'on l'utilisait mal<br />
</aside>
</section>
<section>
<img src="resources/img/paul.jpg" width="50%" /><img src="resources/img/mickey-mouse.png" width="35%" />
</section>
</section>
<section data-background="resources/pictures/background-model.jpg">
<section>
<h2>Site web</h2>
<ul>
<li>PHP 7</li>
<li>MySQL 5.7</li>
<li>Symfony 3.3</li>
<li>Doctrine 2.5</li>
</ul>
<aside class="notes">
Bière =)<br />
Appli pour illustrer ma prez<br />
Site web avec Bières et Brasseries<br />
</aside>
</section>
<section>
<h2>Model presentation</h2>
<img src="resources/img/doctrine_example_model.png" class="schema"/>
<aside class="notes">
Code unique<br />
Explain what is for!<br />
Relation manyToOne unidirectional from Beer entity<br />
</aside>
</section>
<section>
<h4>Doctrine mapping: Beer.orm.yml</h4>
<pre><code class="yml">BeerBundle\Entity\Beer:
type: entity
table: beer
repositoryClass: BeerBundle\Entity\Repository\EntityRepository
indexes:
searchcode_idx:
columns:
- code
uniqueConstraints:
searchunique_idx:
columns:
- code</code></pre>
<aside class="notes">Just a specific repository class to search entity from code</aside>
</section>
<section>
<h4>Entity Repository</h4>
<pre><code class="php">
// BeerBundle\Entity\Repository\EntityRepository
public function findOneByIdentifier(string $code)
{
$qb = $this->createQueryBuilder('c');
$qb->andWhere(
$qb->expr()->eq('c.code', $qb->expr()->literal($code))
);
$results = $qb->getQuery()->execute();
// ...
return $results[0];
}
</code></pre>
</section>
<section>
<h4>Doctrine mapping: Beer.orm.yml</h4>
<pre><code class="yml">BeerBundle\Entity\Beer:
type: entity
table: beer
repositoryClass: BeerBundle\Entity\Repository\EntityRepository
fields:
id:
[...]
code:
[...]
name:
[...]
description:
[...]
percent:
[...]
quotation:
[...]</code></pre>
<aside class="notes">
</aside>
</section>
<section>
<h4>Doctrine mapping: Beer.orm.yml</h4>
<pre><code class="yml">BeerBundle\Entity\Beer:
type: entity
table: beer
manyToOne:
brewery:
targetEntity: BeerBundle\Entity\Brewery
joinColumn:
name: brewery_id
referencedColumnName: id
category:
targetEntity: BeerBundle\Entity\Category
joinColumn:
name: category_id
referencedColumnName: id
</code></pre>
</section>
<section>
<h4>Beer application is ready!</h4>
<h4 class="fragment">Oh wait! We need to import data!</h4>
<div class="fragment"><img src="resources/gif/piti_chat_milk.gif" height="300" /></div>
<aside class="notes">
Create 1 = Create 10k<br />
Contrainte de temps, TMA, limiter les régressions, pas de contraintes de perf...<br />
Reuse stack s'est fait naturellement chez Akeneo (events, entities, mapping, queries, validators, etc.)<br />
Decrease time + No regression<br />
Akeneo Target = 5k<br />
</aside>
</section>
</section>
<section data-background="resources/pictures/background-brewery.jpg">
<section>
<h2>Import breweries (1000 lines)</h2>
<pre><code class="yaml">code;name;description
abbey-ales;Abbey Ales Brewery;Abbey Ales Brewery
black-sheep;Black Sheep Brewery;A black sheep brewery
oakkham;Oakham Ales;The famous Oakham brewery</code></pre>
<aside class="notes">
Bdd vierge => CREATE<br />
Sf Command with filepath as input<br />
</aside>
</section>
<section>
<h4>Command to import breweries</h4>
<pre><code class="php">// Read file content
$fd = fopen($filepath, 'r+');
$headers = fgetcsv($fd, null, ';');
while ($csvRow = fgetcsv($fd, null, ';')) {
$csvRow = array_combine($headers, $csvRow);
// Process data row
$brewery = $this->process($csvRow);
// Validate brewery entity
$violations = $this->getValidator()->validate($brewery);
if ($violations->count() === 0) {
// Persist brewery
$this->getEntityManager()->persist($brewery);
$this->getEntityManager()->flush();
} else {
$this->printViolations($violations, $brewery);
}
}</code></pre>
<aside class="notes">
`process()` permet d'instancier ou de récupérer de la base un objet<br />
Puis mettre à jour ses valeurs<br />
Voir slide suivant<br />
</aside>
</section>
<section>
<h4>Command to import breweries</h4>
<pre><code class="php">private function process(array $item)
{
$brewery = $this->findOrCreateBrewery($item['code']);
$brewery->setName($item['name']);
$brewery->setDescription($item['description']);
$brewery->setAddress($item['address']);
// ...
return $brewery;
}
private function findOrCreateBrewery(string $code)
{
$brewery = $this->getRepository()->findOneByIdentifier($code);
if (null === $brewery) {
$brewery = new Brewery();
$brewery->setCode($code);
}
return $brewery;
}</code></pre>
<aside class="notes">
</aside>
</section>
<section>
<h4>Launch breweries import</h4>
<pre><code class="bash">$ bin/console batch:import:brewery breweries.csv
Memory: 8.39M
1001 entity written
Time: 23.77s - Memory: 29.36M - Diff: 20.97M</code></pre>
<pre class="fragment"><code class="bash">$ bin/console batch:import:brewery breweries.csv --env=prod
Memory: 6.29M
1001 entity written
Time: 21.24s - Memory: 20.97M - Diff: 14.68M</code></pre>
<aside class="notes">
Take care! By default, commands are launched in dev environment!!!<br />
Dev env keeps track on all entities<br />
</aside>
</section>
<section>
<h4>What is happening?</h4>
<pre><code class="sql">[...]
DEBUG: SELECT [...] FROM brewery b0_ WHERE b0_.code = 'id-quia'
DEBUG: SELECT [...] FROM brewery t0 WHERE t0.code = ? ["id-quia"]
DEBUG: "START TRANSACTION" [] []
DEBUG: INSERT INTO brewery [...] []
DEBUG: "COMMIT" [] []
DEBUG: SELECT [...] FROM brewery b0_ WHERE b0_.code LIKE 'abbey-ales'
DEBUG: SELECT [...] FROM brewery t0 WHERE t0.code = ? ["abbey-ales"]
DEBUG: "START TRANSACTION" [] []
DEBUG: INSERT INTO brewery [...] []
DEBUG: "COMMIT" [] []
[...]</code></pre>
<aside class="notes">
- 2 queries per item (find + unicity)<br />
- lot of transactions (1 per item)<br />
Doctrine advices (and SGBD) is to flush sooner<br />
Calculate the right ratio item per flush (You need to test)<br />
Possibilité de faire un begin transaction tout au début et d'avoir une grande transaction<br />
</aside>
</section>
<section>
<h4>Increase batch size to 100</h4>
<pre><code class="php">// Write entity
$this->getEntityManager()->persist($entity);
if (0 === ++$writeCount % 100) {
$this->getEntityManager()->flush();
}</code></pre>
<aside class="notes">
I relaunch the same import<br />
</aside>
</section>
<section>
<h4>Increase batch size to 100</h4>
<pre><code class="bash">$ bin/console batch:import:brewery breweries.csv --env=prod
[Doctrine\DBAL\Exception\UniqueConstraintViolationException]
[Doctrine\DBAL\Driver\PDOException]
[PDOException]
SQLSTATE[23000]: Integrity constraint violation:
1062 Duplicate entry 'id-quia' for key 'searchunique_idx'</code></pre>
<aside class="notes">
2 times the same code in my file<br />
Exception thrown by MySQL<br />
Not the Unique constraint
</aside>
</section>
<section>
<h4>Validation process: batch size 1</h4>
<img src="resources/img/doctrine_batch_schema_step1_batchsize_1.png" class="schema" />
<aside class="notes">
Doctrine UOW<br />
Service responsable de gérer toutes les entités en relation avec la BDD<br />
$brewery = 'id-quia'<br />
</aside>
</section>
<section>
<h4>Validation process: batch size 100</h4>
<img src="resources/img/doctrine_batch_schema_step1_batchsize_100.png" class="schema" />
<aside class="notes">
Think about another way for validators!!!
</aside>
</section>
<section>
<h4>Rework validator</h4>
<pre><code class="php">class UniqueEntityCodeValidator extends ConstraintValidator {
private $codeSet = [];
public function validate($entity, Constraint $constraint) {
if (isset($this->codeSet[$entity->getCode()])) {
$this->context
->buildViolation($constraint->message)
->setParameter('%unique_code%', $entity->getCode())
->addViolation();
return;
}
$this->codeSet[$entity->getCode()] = $entity->getCode();
}
}</code></pre>
<aside class="notes">
Il faut trouver un moyen de purger ce tableau de codes<br />
</aside>
</section>
<section>
<h4>Relaunch the import!</h4>
<h5>Batch size 1</h5>
<pre><code class="bash">Memory: 6.29M
1001 entity written
Time: 21.24s - Memory: 20.97M - Diff: 14.68M</code></pre>
<div class="frament">
<h5>Batch size = 100</h5>
<pre><code class="bash">Memory: 6.29M
Entity "id-quia" not valid:
The value "id-quia" is already set in another entity
1000 entity written
Time: 1.95s - Memory: 20.97M - Diff: 14.68M</code></pre>
</div>
<aside class="notes">Nette augmentation des perfs grâce au batch size</aside>
</section>
</section>
<section data-background="resources/pictures/background-update.jpg">
<section>
<h2>Update Breweries</h2>
<pre><code class="yaml">code;name
id-quia;Lorem ipsum dolor sit amet[...]</code></pre>
<aside class="notes">
Another file with 1 line<br />
This file contains a name longer than expected (> 100 chars)<br />
</aside>
</section>
<section>
<h4>Update breweries</h4>
<pre><code class="bash">$ bin/console batch:import:brewery breweries_update.csv --env=prod
Memory: 6.29M
Entity "id-quia" not valid: This value is too long.
It should have 100 characters or less.
0 entity written
[Doctrine\DBAL\Exception\DriverException]
[Doctrine\DBAL\Driver\PDOException]
[PDOException]
SQLSTATE[22001]: String data, right truncated:
1406 Data too long for column 'name' at row 1</code></pre>
<aside class="notes">
Validation done and error thrown<br />
UPDATE query<br />
Error from MySQL mais on peut en imaginer d'autres<br />
Before MySQL 5.7, update with truncated value!!! Merci MySQL !!<br />
</aside>
</section>
<section>
<h4>What happens?!</h4>
<img src="resources/img/doctrine_batch_schema_step_3.png" class="schema" />
<aside class="notes">
No persist<br />
UOW est responsable de calculer le diff depuis la dernière synchro avec la BDD<br />
Entity has been changed<br />
Analyze how diff is calculated to prepare update<br />
</aside>
</section>
<section>
<h3>Change Tracking Policy</h3>
<blockquote>
"It is the process of determining what has changed in managed entities since the last time they were synchronized with the db"
</blockquote>
<a href="http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/change-tracking-policies.html">
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/change-tracking-policies.html
</a>
<aside class="notes">
Defined per entity<br />
</aside>
</section>
<section>
<h3>Change Tracking Policy</h3>
<ul>
<li>Deferred implicit (default)</li>
<li>Deferred explicit</li>
<li>Notify</li>
</ul>
<aside class="notes">
Implicit: Doctrine detects the change by a property-by property comparison at commit time. EntityManager::flush(); everything<br />
Explicit: Same but need to call explicitely EntityManager::persist(). More efficient ;)<br />
Notify: You need to implement by yourself the changes using listeners. It's far more efficient.
</aside>
</section>
<section>
<h4>Deferred explicit implementation</h4>
<pre><code class="yml">BeerBundle\Entity\Brewery:
type: entity
table: brewery
repositoryClass: BeerBundle\Entity\Repository\EntityRepository
changeTrackingPolicy: DEFERRED_EXPLICIT</code></pre>
<aside class="notes">
+ explicite<br />
+ efficace surtout en update (diff que sur ce qu'on persiste)<br />
</aside>
</section>
<section>
<h4>Relaunch the job</h4>
<pre><code class="bash smaller">$ bin/console batch:import:brewery breweries_update.csv --env=prod
Memory: 6.29M
Entity "id-quia" not valid:
This value is too long. It should have 100 characters or less.
0 entity written
Time: 0.05s - Memory: 14.68M - Diff: 8.39M</code></pre>
<img src="resources/gif/dancing_zebra.gif" />
<aside class="notes">
Does not resolve scalability problem<br />
Niveau performance, la diff se verra sur une grosse volumétrie<br />
</aside>
</section>
</section>
<section data-background="resources/pictures/background-beers.jpg">
<section>
<h2>Import Beers (10000 lines)</h2>
<pre><code class="yaml small">code;name;description;brewery;category
kronenbourg;Kronenbourg;A beer to piss;kronenbourg_brewery;piss
stella;Stella Artois;A beer that does not respect its country;Artois;pils
33_export;33 Export;The best competitor of Kronenbourg;heineken;piss</code></pre>
<aside class="notes">
I like beer<br />
No respect!<br />
</aside>
</section>
<section>
<h4>Import beers (10000 lines)</h4>
<pre><code class="bash">$ bin/console batch:import:beer beers_10k.csv --env=prod
Memory: 6.29M
10000 entity written
Time: 32.3s - Memory: 92.27M - Diff: 85.98M</code></pre>
<div class="fragment">
<h4>Import beers (20000 lines)</h4>
<pre><code class="bash">$ bin/console batch:import:beer beers_20k.csv --env=prod
Memory: 6.29M
PHP Fatal error:
Allowed memory size of 134217728 bytes exhausted
(tried to allocate 20480 bytes)</code></pre>
</div>
<aside class="notes">
Useless to increase PHP memory limit,<br />
it will probably break later with a bigger file
</aside>
</section>
<section>
<h4>Memory consumption</h4>
<img src="resources/img/chart-doctrine-memory-leak.png" width="50%" /><br />
<img src="resources/gif/truck_explosion.gif" width="25%" class="fragment" />
<aside class="notes">
Every 5000 items<br />
300k items
</aside>
</section>
<section>
<h3>Explanation memory leak problems</h3>
<ul>
<li class="fragment">Increase memory usage</li>
<li class="fragment">GC is run more often...</li>
<li class="fragment">and for nothing!</li>
<li class="fragment">Decrease performance</li>
</ul>
<aside class="notes">
3. not able to free memory (objects still used in UOW)<br />
4. It leads to an increase of CPU usage of the process<br />
Mais comment savoir quels objets sont en mémoire et à quoi ils sont liés<br />
</aside>
</section>
</section>
<section data-background="resources/pictures/background-meminfo.jpg">
<section>
<h2>Extension php-meminfo</h2>
<ul>
<li>Give insight about PHP memory content</li>
<li>Free & open source PHP extension</li>
<li><a href="https://github.com/BitOne/php-meminfo">https://github.com/BitOne/php-meminfo</a></li>
</ul>
<aside class="notes">
License MIT<br />
Its main goal is to help you understand memory leaks from memory dumps<br />
by looking at data present in memory, you can better understand your application behaviour.<br />
Deep into php-meminfo<br />
</aside>
</section>
<section>
<h3>php-meminfo: How it works?</h3>
<ol>
<li class="fragment">Dump memory content</li>
<li class="fragment">Analyze content (summary)</li>
<li class="fragment">Analyze memory for an object type</li>
<li class="fragment">Analyze memory path for a specific object</li>
</ol>
</section>
<section>
<h4>Dump memory content</h4>
<pre><code class="php">// EntityWriter
$this->em->flush();
meminfo_info_dump(fopen('/tmp/doctrine_batch.log', 'w'));</code></pre>
<pre class="fragment"><code class="json">{
"header": {
"memory_usage":89735424,
"memory_usage_real":92274688,
"peak_memory_usage":90107432,
"peak_memory_usage_real":92274688
},
"items": {
"0x7f64be256100" : {
"type" : "array",
"size" : "72",
"symbol_name" : "_GET",
"is_root" : true,
"frame" : "BatchBundle\\Job\\Job->execute()",
"children" : {}
},
...
}
}</code></pre>
<aside class="notes">
After flush because we don't need entities already saved in DB<br />
No need to test on 1M<br />
Goal is to reproduce the leak<br />
</aside>
</section>
<section>
<img src="resources/gif/oh_my_god_afraid.gif" />
<div class="fragment">No worries! Analyzers are provided in php-meminfo</div>
<aside class="notes">
</aside>
</section>
<section>
<h4>Summarize content</h4>
<pre><code class="bash">$ bin/analyzer summary /tmp/doctrine_batch.log</code></pre>
<div class="fragment">
<table class="small">
<thead>
<tr>
<td>Type</td>
<td>Instances Count</td>
</tr>
</thead>
<tbody>
<tr><td>BeerBundle\Entity\Brewery</td><td>21000</td></tr>
<tr><td>BeerBundle\Entity\Category</td><td>20139</td></tr>
<tr><td>Doctrine\ORM\Query\ResultSetMapping</td><td>11145</td></tr>
<tr><td>Doctrine\ORM\Query\ParserResult</td><td>11139</td></tr>
<tr><td>Doctrine\ORM\Query\Exec\SingleSelectExecutor</td><td>11139</td></tr>
<tr><td>BeerBundle\Entity\Beer</td><td>10000</td></tr>
</tbody>
</table>
</div>
<aside class="notes">
10k Beer => exactly the number in the file<br />
La taille mémoire cumulée des objets est également disponible mais masquée ici
</aside>
</section>
<section>
<h4>Analyze memory for an object type</h4>
<pre><code class="bash smaller">$ bin/analyzer query -f "class=BeerBundle\\Entity\\Beer" -v /tmp/doctrine_batch.log</code></pre>
<div class="fragment">
<table>
<thead>
<tr>
<td>Item ids</td>
<td>Item data</td>
<td>Children</td>
</tr>
</thead>
<tbody>
<tr>
<td>0x7f64ab801028</td>
<td>
Type: object<br />
Class: BeerBundle\Entity\Beer<br />
[...]
</td>
<td>
id: 0x7f64a8d354e0<br />
code: 0x7f64a8d35500<br />
[...]<br />
brewery: 0x7f64a8d355a0<br />
category: 0x7f64a8d355c0
</td>
</tr>
</tbody>
</table>
</div>
<aside class="notes">
Take one object randomly (not necessary the first)<br />
</aside>
</section>
<section>
<h4>Analyze memory path for a specific object</h4>
<pre><code class="bash">$ bin/analyzer ref-path /tmp/doctrine_batch.log 0x7f64ab801028
Found 3 paths
0x7f64ab801028
↑
1 (0x7f64afa4a920)
↑
BeerBundle\Entity\Beer (0x7f64a8c65c80)
↑
identityMap (0x7f64a8c6d320)
↑
unitOfWork (0x7f64afdbe7c0)
↑
doctrine.orm.default_entity_manager (0x7f64af9c08e0)
↑
services (0x7f64af9c1280)
↑
container (0x7f64be256280)</code></pre>
<aside class="notes"></aside>
</section>
</section>
<section data-background="resources/pictures/background-deep_uow.jpg">
<section>
<h2>Deep into the UOW</h2>
</section>
<section>
<h3>The identity map</h3>
<div>
<ul>
<li>Stores references to all managed entities</li>
<li>Entities are grouped by their class name</li>
<li>Avoid entity duplication</li>
</ul>
</div>
<div class="fragment">
<pre><code class="php">$this->identityMap[$className][$idHash] = $entity;</code></pre>
<pre><code class="php">$breweryA = $breweryRepo->findOneBy(['code' => 'id-quia']);
$breweryB = $breweryRepo->findOneBy(['name' => 'Dietrich Group']);
$this->assertSame($breweryA, $breweryB);</code></pre>
</div>
<aside class="notes">
4 status of your entity (New, Managed, Detached, Removed)<br />
Ne signifie pas qu'il n'y a pas de query SQL<br />
</aside>
</section>
<section>
<h3>Detach versus clear</h3>
3 ways to remove from the UOW:
<pre class="fragment"><code class="php">$em->detach($entity);</code></pre>
<pre class="fragment"><code class="php">$em->clear('BeerBundle\Entiy\Beer');</code></pre>
<pre class="fragment"><code class="php">$em->clear();</code></pre>
<aside class="notes">
detach: Detach an entity from the UOW. Does not remove updateCollections, removeCollections, etc. done by commit();<br />
clear($className): Detach all entities of the class name<br />
clear(): Clears UOW
</aside>
</section>
<section>
<h4>Detach entities</h4>
<pre><code class="php">$this->em->flush();
$this->em->clear('BeerBundle\Entity\Beer');
// or loop on items and call detach
foreach ($items as $item) {
$this->em->detach($item);
}</code></pre>
<h4>Previously:</h4>
<pre><code class="bash">$ bin/console batch:import:beer beers_10k.csv --env=prod
Time: 21.95s - Memory: 92.27M - Diff: 85.98M</code></pre>
<div class="fragment">
<h4>Now:</h4>
<pre><code class="bash">$ bin/console batch:import:beer beers_10k.csv --env=prod
Time: 21.89s - Memory: 69.21M - Diff: 62.92M</code></pre>
</div>
<aside class="notes">
A bit less performant on 10k<br />
Same perf between loop detach and clear($className)
</aside>
</section>
<section>
<h4>Analyze memory</h4>
<table class="small">
<thead>
<tr>
<td>Type</td>
<td>Instances Count</td>
</tr>
</thead>
<tbody>
<tr><td>Doctrine\ORM\Query\ResultSetMapping</td><td>11145</td></tr>
<tr><td>Doctrine\ORM\Query\ParserResult</td><td>11139</td></tr>
<tr><td>Doctrine\ORM\Query\Exec\SingleSelectExecutor</td><td>11139</td></tr>
<tr><td>BeerBundle\Entity\Brewery</td><td>1000</td></tr>
<tr><td>BeerBundle\Entity\Category</td><td>139</td></tr>
</tbody>
</table>
<aside class="notes">
Categories and Breweries still in memory but, this number won't increase!
</aside>
</section>
<section>
<h3>Detach entities</h3>
<ul>
<li>Categories and Breweries are not detached</li>
<li>No cascade detach (ManyToOne)</li>
<li>Not the same lifecycle</li>
</ul>
<img src="resources/gif/the_office_oh_yeah.gif" class="fragment" />
<aside class="notes">
Categories and Breweries exist without Beers<br />
Don't want to cascade detach<br />
Categories needs to stay in the UOW as they can be used by another Beer
</aside>
</section>
<section>
<h4>Clear UOW</h4>
<pre><code class="php">$this->em->flush();
$this->em->clear();</code></pre>
<h4>Previously:</h4>
<pre><code class="bash">$ bin/console batch:import:beer beers_10k.csv --env=prod
Time: 21.89s - Memory: 69.21M - Diff: 62.92M</code></pre>
<div class="fragment">
<h4>Now:</h4>
<pre><code class="bash">$ bin/console batch:import:beer beers_10k.csv --env=prod
Time: 22.16s - Memory: 67.11M - Diff: 60.82M</code></pre>
</div>
<aside class="notes">
A bit longer as we rehydrate each time categories and breweries
</aside>
</section>
<section>
<h4>Clear UOW</h4>
<table class="small">
<thead>
<tr>
<td>Type</td>
<td>Instances Count</td>
</tr>
</thead>
<tbody>
<tr><td>Doctrine\ORM\Query\ResultSetMapping</td><td>11145</td></tr>
<tr><td>Doctrine\ORM\Query\ParserResult</td><td>11139</td></tr>
<tr><td>Doctrine\ORM\Query\Exec\SingleSelectExecutor</td><td>11139</td></tr>
</tbody>
</table>
<img src="resources/gif/barney_stinson_good.gif" />
<aside class="notes">
2M less than previous execution<br />
No more Brewery nor Category<br />
Not necessary to clear the whole UOW in this case<br />
10000 beers + 1000 breweries + 139 categories
</aside>
</section>
</section>
<section data-background="resources/pictures/background-hunt.jpg">
<section>
<h2>Let's hunt last memory leaks</h2>
<ul class="fragment">
<li class="grow">SingleSelectExecutor</li>
<li class="grow">ResultSetMapping</li>
<li class="grow">ParserResult</li>
</ul>
<aside class="notes">
1. Executes SQL statement from DQL select statement<br />
2. Maps results set of SQL query to Doctrine results<br />
3. Encapsulates results from DQL parsing<br />
Object link to ORM\Query<br />
</aside>
</section>
<section>
<h4>Dedicated repository</h4>
<pre><code class="php">public function findOneByIdentifier(string $code) {
$qb = $this->createQueryBuilder('c');
$qb->andWhere(
$qb->expr()->eq('c.code', $qb->expr()->literal($code))
);
$results = $qb->getQuery()->execute();
//...
return $results[0];
}</code></pre>
<img src="resources/gif/mister_bean_nawak.gif" class="fragment" />