udb 0.4.28

Universal Data Broker — a Rust gRPC broker over multiple databases (Postgres, MySQL, SQLite, MongoDB, ClickHouse, Cassandra, MSSQL, Redis, Qdrant, S3, Neo4j, …) with per-tenant RLS, 2PC, sagas, and CDC.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
<?php

declare(strict_types=1);

namespace Fahara02\UdbLaravel\Generated;

use Fahara02\UdbLaravel\Exceptions\UdbConfigurationException;
use Fahara02\UdbLaravel\Exceptions\UdbRpcException;
use Fahara02\UdbLaravel\UdbMetadata;
use Grpc\BaseStub;
use Grpc\ChannelCredentials;

/**
 * {{GENERATED_NOTE}}
 *
 * GeneratedClient — robustness / forwarding layer over the buf-generated gRPC
 * service stubs (the `*Client` classes under `gen/`). It is regenerated from
 * the embedded proto descriptor set by `udb sdk generate`, so its surface can
 * never drift from the wire contract.
 *
 *   UDB version ...... {{UDB_VERSION}}
 *   Protocol version . {{PROTOCOL_VERSION}}
 *   Services ......... {{SERVICE_COUNT}}
 *   RPCs ............. {{RPC_COUNT}}
 *
 * This class COMPOSES WITH the hand-written layer; it does not replace it:
 *   - it reuses {@see UdbMetadata} for the eight broker headers,
 *   - it throws the existing {@see UdbRpcException} / {@see UdbConfigurationException},
 *   - the hand-written {@see \Fahara02\UdbLaravel\UdbClient} and
 *     {@see \Fahara02\UdbLaravel\UdbAuthClient} remain the ergonomic entry
 *     points; this generated client is the exhaustive, every-RPC surface.
 *
 * Each unary wrapper forwards to the underlying stub method of the same name
 * and adds: per-call deadline, retry with exponential backoff + jitter on
 * transient gRPC codes (DEADLINE_EXCEEDED only for read-only RPCs),
 * TLS/credentials wiring, metadata injection, and typed error mapping (it
 * unpacks the `udb-error-detail-bin` trailer into an
 * {@see \Udb\Entity\V1\ErrorDetail} when the broker attaches one).
 *
 * Streaming RPCs are exposed as accessors returning the live gRPC call object
 * (metadata + deadline already applied); retry is intentionally not applied to
 * streams because re-driving a half-consumed stream is unsafe.
 *
 * Channel sharing: one gRPC channel per (host, credentials, options) tuple is
 * created lazily and shared across every service stub, matching the
 * long-lived-channel guidance in the hand-written {@see \Fahara02\UdbLaravel\UdbClient}.
 */
final class GeneratedClient
{
    /** gRPC status codes retried only for read-only unary calls. */
    private const RETRYABLE_CODES = [
        14, // UNAVAILABLE
        8,  // RESOURCE_EXHAUSTED
    ];

    /**
     * Proto-derived operation_kind per RPC, keyed by method name (globally unique):
     * "read_only" | "mutation" | "destructive". The SINGLE authoritative
     * state-change classification — used for retry safety and SDK conformance
     * probing. Never derived from the method name's spelling.
     *
     * @var array<string, string>
     */
    public const OPERATION_KIND = [
        // @@UDB_RPC_BEGIN
        "{{RPC_WIRE_NAME}}" => "{{RPC_OPERATION_KIND}}",
        // @@UDB_RPC_END
    ];

    /**
     * Proto-derived operation_kind per RPC, keyed by "Service/Method" for
     * cross-language metadata conformance and benchmark identity joins.
     *
     * @var array<string, string>
     */
    public const OPERATION_KIND_BY_RPC = [
        // @@UDB_RPC_BEGIN
        "{{SERVICE_NAME}}/{{RPC_WIRE_NAME}}" => "{{RPC_OPERATION_KIND}}",
        // @@UDB_RPC_END
    ];

    /**
     * Descriptor public alias per RPC, keyed by "Service/Method". This is
     * metadata for docs/benchmarks; dispatch still uses the generated stubs.
     *
     * @var array<string, string>
     */
    public const API_ALIAS = [
        // @@UDB_RPC_BEGIN
        "{{SERVICE_NAME}}/{{RPC_WIRE_NAME}}" => "{{RPC_ALIAS_SNAKE}}",
        // @@UDB_RPC_END
    ];

    /**
     * Descriptor REST operationId per RPC, keyed by "Service/Method".
     *
     * @var array<string, string>
     */
    public const OPERATION_ID = [
        // @@UDB_RPC_BEGIN
        "{{SERVICE_NAME}}/{{RPC_WIRE_NAME}}" => "{{REST_OPERATION_ID}}",
        // @@UDB_RPC_END
    ];

    /**
     * Descriptor REST HTTP method per RPC, keyed by "Service/Method".
     *
     * @var array<string, string>
     */
    public const HTTP_METHOD = [
        // @@UDB_RPC_BEGIN
        "{{SERVICE_NAME}}/{{RPC_WIRE_NAME}}" => "{{RPC_HTTP_METHOD}}",
        // @@UDB_RPC_END
    ];

    /**
     * Descriptor REST HTTP path per RPC, keyed by "Service/Method".
     *
     * @var array<string, string>
     */
    public const HTTP_PATH = [
        // @@UDB_RPC_BEGIN
        "{{SERVICE_NAME}}/{{RPC_WIRE_NAME}}" => "{{RPC_HTTP_PATH}}",
        // @@UDB_RPC_END
    ];

    /**
     * Proto-derived replay-safe flag per RPC, keyed by method name (globally
     * unique): from `method_idempotency_contract.replay_safe`. A mutation is
     * eligible for auto-retry on a transient failure ONLY when it is replay-safe
     * AND the caller supplied a non-empty idempotency key. RPCs absent from this
     * map are treated as NOT replay-safe (fail-closed). Read-only RPCs ignore
     * this map entirely (their retry safety comes from {@see OPERATION_KIND}).
     *
     * @var array<string, bool>
     */
    public const REPLAY_SAFE = [
        "Delete" => true,
        "Upsert" => true,
    ];

    /** @var array<string,array{table:string,primary_keys:list<string>,fields:list<string>,relations_json:string,version_field:string,tenant_field:string,project_field:string,php_type:string}> */
    public const ENTITIES = [
        // @@UDB_ENTITY_BEGIN
        "{{ENTITY_MESSAGE_TYPE}}" => ['table' => "{{ENTITY_TABLE}}", 'primary_keys' => [{{ENTITY_PRIMARY_KEYS}}], 'fields' => [{{ENTITY_JSON_FIELDS}}], 'relations_json' => {{ENTITY_RELATIONS_JSON_STRING}}, 'version_field' => "{{ENTITY_VERSION_FIELD}}", 'tenant_field' => "{{ENTITY_TENANT_FIELD}}", 'project_field' => "{{ENTITY_PROJECT_FIELD}}", 'php_type' => "{{ENTITY_PHP_TYPE}}"],
        // @@UDB_ENTITY_END
    ];

    /**
     * Public snake_case aliases advertised by the descriptor SDK surface. PHP's
     * concrete methods use camelCase by convention; __call routes snake aliases
     * to the same implementations so docs, benches, and callers can use either.
     *
     * @var array<string, string>
     */
    public const METHOD_ALIASES = [
        // @@UDB_RPC_BEGIN
{{PHP_METHOD_ALIAS_ENTRIES}}
        // @@UDB_RPC_END
    ];

    private ?UdbMetadata $boundContext = null;

    /** @var array<class-string, BaseStub> Lazily-built, channel-sharing stubs. */
    private array $stubs = [];

    /**
     * Initial (header) response metadata from the most recent unary call —
     * for reading header-only values such as `x-udb-approval-token`.
     *
     * @var array<string,list<string>>
     */
    private array $lastResponseMetadata = [];

    /** Shared channel options (incl. credentials) — built once, reused per stub. */
    private ?array $channelOptions = null;

    /**
     * @param  array{
     *   endpoint:string,
     *   tls?: array{enabled?:bool, root_certs?:?string, target?:?string},
     *   channel_options?: array<string,mixed>,
     *   deadline_ms?: int,
     *   retry?: array{max_attempts?:int, base_delay_ms?:int, max_delay_ms?:int},
     * }  $config
     */
    public function __construct(private readonly array $config)
    {
        if (! \extension_loaded('grpc')) {
            throw new UdbConfigurationException(
                'The "grpc" PHP extension is not loaded. Install via PECL '
                . '(`pecl install grpc`) and add "extension=grpc.so" to php.ini.'
            );
        }
        $endpoint = trim((string) ($this->config['endpoint'] ?? ''));
        if ($endpoint === '') {
            throw new UdbConfigurationException(
                'UDB endpoint is not configured. Set UDB_ENDPOINT or '
                . 'config/udb.php#endpoint to host:port (e.g. "127.0.0.1:50051").'
            );
        }
    }

    /**
     * Bind a request-scoped {@see UdbMetadata}. The Laravel middleware wires
     * this early in the request lifecycle so every subsequent RPC inherits the
     * tenant + correlation without the caller passing them explicitly.
     */
    public function bindContext(UdbMetadata $metadata): void
    {
        $this->boundContext = $metadata;
    }

    public function __call(string $name, array $arguments)
    {
        $target = self::METHOD_ALIASES[$name] ?? null;
        if ($target !== null && $target !== $name && method_exists($this, $target)) {
            return $this->{$target}(...$arguments);
        }

        throw new \BadMethodCallException("Undefined generated UDB method {$name}");
    }

    private function context(): UdbMetadata
    {
        if ($this->boundContext === null) {
            throw new UdbConfigurationException(
                'No UDB request context is bound. Run inside an HTTP request '
                . 'with UdbContextMiddleware enabled, call bindContext(), or '
                . 'pass an explicit UdbMetadata as the last RPC argument.'
            );
        }
        return $this->boundContext;
    }

    // ── Generated per-RPC wrappers ──────────────────────────────────────────
    //
    // One method per RPC across every service. Method name = lcfirst of the
    // proto method (PHP convention) while it forwards to the stub's PascalCase
    // method. Unary calls retry; streaming calls return the live call object.

    // @@UDB_RPC_BEGIN kind=unary
    /**
     * {{SERVICE_FULL}} / {{RPC_WIRE_NAME}} ({{RPC_KIND}}), public alias {{RPC_ALIAS_SNAKE}}.
     *
     * Forwards to {@see stubFor()}->{{RPC_WIRE_NAME}}(); retries transient codes.
     * Path: {{RPC_PATH}}
     *
     * @param  \Google\Protobuf\Internal\Message  $request
     * @return \Google\Protobuf\Internal\Message  the decoded {{RPC_OUTPUT}}
     */
    public function {{PHP_RPC_METHOD_CAMEL}}($request, ?UdbMetadata $metadata = null)
    {
        return $this->invokeUnary(
            '{{RPC_WIRE_NAME}}',
            '{{SERVICE_NAME}}',
            '{{SERVICE_PKG}}',
            fn (BaseStub $stub, array $md, array $opts) => $stub->{{RPC_WIRE_NAME}}($request, $md, $opts),
            $metadata,
            '{{RPC_OPERATION_KIND}}' === 'read_only',
            $request,
        );
    }
    // @@UDB_RPC_END

    // @@UDB_RPC_BEGIN kind=server_streaming
    /**
     * {{SERVICE_FULL}} / {{RPC_WIRE_NAME}} ({{RPC_KIND}}), public alias {{RPC_ALIAS_SNAKE}}.
     *
     * Returns the live {@see \Grpc\ServerStreamingCall}; iterate
     * `->responses()` then check `->getStatus()`. Path: {{RPC_PATH}}
     *
     * @param  \Google\Protobuf\Internal\Message  $request
     * @return \Grpc\ServerStreamingCall
     */
    public function {{PHP_RPC_METHOD_CAMEL}}($request, ?UdbMetadata $metadata = null)
    {
        $stub = $this->stubFor('{{SERVICE_NAME}}', '{{SERVICE_PKG}}');
        return $stub->{{RPC_WIRE_NAME}}($request, $this->headers($metadata), $this->callOptions());
    }
    // @@UDB_RPC_END

    // @@UDB_RPC_BEGIN kind=client_streaming
    /**
     * {{SERVICE_FULL}} / {{RPC_WIRE_NAME}} ({{RPC_KIND}}), public alias {{RPC_ALIAS_SNAKE}}.
     *
     * Returns the live {@see \Grpc\ClientStreamingCall}; `->write()` each
     * message then `->wait()`. Not retried — re-driving a partially-written
     * client stream is unsafe. Path: {{RPC_PATH}}
     *
     * @return \Grpc\ClientStreamingCall
     */
    public function {{PHP_RPC_METHOD_CAMEL}}(?UdbMetadata $metadata = null)
    {
        $stub = $this->stubFor('{{SERVICE_NAME}}', '{{SERVICE_PKG}}');
        return $stub->{{RPC_WIRE_NAME}}($this->headers($metadata), $this->callOptions());
    }
    // @@UDB_RPC_END

    // @@UDB_RPC_BEGIN kind=bidi
    /**
     * {{SERVICE_FULL}} / {{RPC_WIRE_NAME}} ({{RPC_KIND}}), public alias {{RPC_ALIAS_SNAKE}}.
     *
     * Returns the live {@see \Grpc\BidiStreamingCall}; `->write()` /
     * `->read()` / `->writesDone()`. Not retried. Path: {{RPC_PATH}}
     *
     * @return \Grpc\BidiStreamingCall
     */
    public function {{PHP_RPC_METHOD_CAMEL}}(?UdbMetadata $metadata = null)
    {
        $stub = $this->stubFor('{{SERVICE_NAME}}', '{{SERVICE_PKG}}');
        return $stub->{{RPC_WIRE_NAME}}($this->headers($metadata), $this->callOptions());
    }
    // @@UDB_RPC_END

    // ── Per-service stub accessors ──────────────────────────────────────────
    //
    // Direct, typed access to the underlying buf-generated stub for any caller
    // that wants the raw surface (or new methods a future regen adds).

    // @@UDB_SERVICE_BEGIN
    /**
     * Underlying buf-generated stub for {{SERVICE_FULL}} ({{SERVICE_RPC_COUNT}} RPC(s)).
     * Channel is shared with every other service stub on this client.
     *
     * @return BaseStub  a {{SERVICE_NAME}}Client
     */
    public function {{SERVICE_NAME}}Stub(): BaseStub
    {
        return $this->stubFor('{{SERVICE_NAME}}', '{{SERVICE_PKG}}');
    }
    // @@UDB_SERVICE_END

    // ── Internals ───────────────────────────────────────────────────────────

    /**
     * Resolve (and cache) the buf-generated stub for a service. The PSR-4 FQN
     * is derived from the proto package + service name following the buf-php
     * convention (`udb.core.apikey.services.v1` + `ApiKeyService` →
     * `\Udb\Core\Apikey\Services\V1\ApiKeyServiceClient`). Done at runtime so
     * no class list is hand-maintained.
     */
    private function stubFor(string $serviceName, string $servicePkg): BaseStub
    {
        $fqn = $this->stubClass($serviceName, $servicePkg);
        if (isset($this->stubs[$fqn])) {
            return $this->stubs[$fqn];
        }
        if (! class_exists($fqn)) {
            throw new UdbConfigurationException(
                "UDB generated stub `{$fqn}` was not found. Run `buf generate` "
                . 'so the gen/ stubs exist before using GeneratedClient.'
            );
        }
        /** @var BaseStub $stub */
        $stub = new $fqn((string) $this->config['endpoint'], $this->buildChannelOptions());
        $this->stubs[$fqn] = $stub;
        return $stub;
    }

    /**
     * Map proto package + service to the buf-php stub class FQN. Each dotted,
     * lowercase package segment is `ucfirst`-ed; the class is `<Service>Client`.
     */
    private function stubClass(string $serviceName, string $servicePkg): string
    {
        $ns = implode('\\', array_map('ucfirst', explode('.', $servicePkg)));
        return '\\' . $ns . '\\' . $serviceName . 'Client';
    }

    /**
     * Build the channel-options array (credentials + TLS + tuning) once and
     * reuse it for every stub so they multiplex over one channel.
     *
     * @return array<string,mixed>
     */
    private function buildChannelOptions(): array
    {
        if ($this->channelOptions !== null) {
            return $this->channelOptions;
        }

        $tls = (array) ($this->config['tls'] ?? []);
        if ((bool) ($tls['enabled'] ?? false)) {
            $rootCerts = $tls['root_certs'] ?? null;
            if ($rootCerts !== null && ! is_readable((string) $rootCerts)) {
                throw new UdbConfigurationException(
                    "UDB TLS root cert bundle not readable at: {$rootCerts}"
                );
            }
            $pem = $rootCerts !== null ? (string) file_get_contents((string) $rootCerts) : null;
            $credentials = ChannelCredentials::createSsl($pem);
        } else {
            $credentials = ChannelCredentials::createInsecure();
        }

        $options = (array) ($this->config['channel_options'] ?? []);
        $options['credentials'] = $credentials;

        $target = $tls['target'] ?? $this->config['endpoint'];
        if ($target !== $this->config['endpoint']) {
            $options['grpc.default_authority'] = (string) $target;
        }

        $this->channelOptions = $options;
        return $options;
    }

    /**
     * Per-call gRPC options — currently just the deadline, expressed as the
     * timeout (microseconds) the PHP gRPC extension expects.
     *
     * @return array<string,mixed>
     */
    private function callOptions(): array
    {
        $opts = [];
        $deadlineMs = (int) ($this->config['deadline_ms'] ?? 30_000);
        if ($deadlineMs > 0) {
            $opts['timeout'] = $deadlineMs * 1000;
        }
        return $opts;
    }

    /**
     * Resolve the metadata headers for a call, falling back to the bound
     * request context when no explicit override is supplied.
     *
     * @return array<string, list<string>>
     */
    private function headers(?UdbMetadata $metadata): array
    {
        return ($metadata ?? $this->context())->toGrpcMetadata();
    }

    /**
     * Shared unary invoker: deadline + metadata + retry with exponential
     * backoff & jitter on transient codes, then typed error mapping. Every
     * generated unary wrapper funnels through here so behaviour is uniform.
     *
     * @param  callable(BaseStub, array<string,list<string>>, array<string,mixed>):mixed  $invoker
     * @return \Google\Protobuf\Internal\Message
     */
    private function invokeUnary(
        string $rpcName,
        string $serviceName,
        string $servicePkg,
        callable $invoker,
        ?UdbMetadata $metadata,
        bool $readOnly,
        mixed $request = null,
    ) {
        $stub = $this->stubFor($serviceName, $servicePkg);
        $md = $this->headers($metadata);
        $opts = $this->callOptions();

        // Mutation retry gate (read from the proto-derived maps, never the name):
        //   replay-safe (REPLAY_SAFE[$rpcName]) AND a non-empty idempotency key on
        //   the request. Both are mandatory; read-only RPCs ignore them.
        $replaySafe = (bool) (self::REPLAY_SAFE[$rpcName] ?? false);
        $hasIdempotencyKey = $this->hasIdempotencyKey($request);

        $retry = (array) ($this->config['retry'] ?? []);
        $maxAttempts = max(1, (int) ($retry['max_attempts'] ?? 4));
        $baseDelayMs = max(1, (int) ($retry['base_delay_ms'] ?? 50));
        $maxDelayMs = max($baseDelayMs, (int) ($retry['max_delay_ms'] ?? 2_000));

        $lastStatus = null;
        for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {
            /** @var \Grpc\UnaryCall $call */
            $call = $invoker($stub, $md, $opts);
            /** @var array{0: ?object, 1: object|array} $result */
            $result = $call->wait();
            [$response, $status] = $result;
            // Capture the call's INITIAL (header) metadata so callers can read
            // header-only values (e.g. `x-udb-approval-token`) via lastResponseMetadata().
            $this->lastResponseMetadata = method_exists($call, 'getMetadata')
                ? ((array) ($call->getMetadata() ?? []))
                : [];

            $code = $this->statusCode($status);
            if ($code === 0) {
                if ($response === null) {
                    throw new UdbRpcException(
                        status: 13, // INTERNAL
                        details: "UDB {$rpcName} returned OK status with empty body",
                        raw: $status,
                        rpcName: $rpcName,
                    );
                }
                return $response;
            }

            $lastStatus = $status;
            if ($attempt < $maxAttempts
                && $this->isRetryable($code, $readOnly, $replaySafe, $hasIdempotencyKey)) {
                $this->sleepBackoff($attempt, $baseDelayMs, $maxDelayMs);
                continue;
            }
            break;
        }

        throw $this->mapError($lastStatus, $rpcName);
    }

    /**
     * Initial (header) response metadata from the most recent unary call.
     * Keys are lower-cased; values are lists. e.g.
     * `$client->lastResponseMetadata()['x-udb-approval-token'][0] ?? ''`.
     *
     * @return array<string,list<string>>
     */
    public function lastResponseMetadata(): array
    {
        return $this->lastResponseMetadata;
    }

    // ── Neutral-IR typed query builder (master-plan items 2.5 / 10.1) ──────
    //
    // These builders emit the broker's canonical neutral-IR envelope and send it
    // through the EXISTING generated GenericDispatch RPC. They are not a second
    // client engine and they never set tenant/project/RequestContext on the
    // request body; caller scope still comes from UDB metadata / verified claims.

    public const DEFAULT_IR_BACKEND = 'postgres';

    private const ORM_TIERS_JSON = {{ORM_TIERS_STRING}};

    private const BACKEND_ROLES_JSON = {{BACKEND_ROLES_STRING}};

    public static function query(string $messageType): IrQuery
    {
        return new IrQuery($messageType);
    }

    public static function writeTo(string $messageType): IrWriteQuery
    {
        return new IrWriteQuery($messageType);
    }

    public static function deleteFrom(string $messageType): IrDeleteQuery
    {
        return new IrDeleteQuery($messageType);
    }

    public static function repository(string $messageType): EntityRepository
    {
        $binding = self::ENTITIES[$messageType] ?? null;
        if ($binding === null) {
            throw new \InvalidArgumentException("udb: unknown entity '{$messageType}'");
        }
        return new EntityRepository($messageType, $binding);
    }

    public static function unitOfWork(): UnitOfWork
    {
        return new UnitOfWork();
    }

    /** @return array<string,string> */
    public static function backendRoles(): array
    {
        $roles = json_decode(self::BACKEND_ROLES_JSON, true, 512, JSON_THROW_ON_ERROR);
        if (! is_array($roles)) {
            throw new UdbConfigurationException('UDB backend role map is invalid.');
        }
        return $roles;
    }

    /** @return array<string,string> */
    public static function ormTiers(): array
    {
        $tiers = json_decode(self::ORM_TIERS_JSON, true, 512, JSON_THROW_ON_ERROR);
        if (! is_array($tiers)) {
            throw new UdbConfigurationException('UDB ORM tier map is invalid.');
        }
        return $tiers;
    }

    public static function requireEagerIncludeBackend(string $backend): void
    {
        $tiers = self::ormTiers();
        $tier = $tiers[$backend] ?? null;
        if ($tier !== 'relational') {
            throw new EagerIncludeUnsupportedBackendException($backend, $tier);
        }
    }

    // @@UDB_ENTITY_BEGIN
    public static function {{ENTITY_ALIAS_CAMEL}}Repository(): EntityRepository
    {
        return self::repository("{{ENTITY_MESSAGE_TYPE}}");
    }
    // @@UDB_ENTITY_END

    public static function rawDispatchRequest(
        string $backend,
        string $operation,
        string $specJson,
        string $resourceName = '',
    ): object {
        $fqn = '\\Udb\\Entity\\V1\\GenericDispatchRequest';
        if (! class_exists($fqn)) {
            throw new UdbConfigurationException(
                'UDB GenericDispatchRequest class not found. Run buf generate before using IR builders.'
            );
        }
        $request = new $fqn();
        $request->setBackend($backend);
        $request->setOperation($operation);
        $request->setResourceName($resourceName);
        $request->setSpecJson($specJson);
        return $request;
    }

    private function statusCode(mixed $status): int
    {
        return is_object($status) ? (int) ($status->code ?? -1) : (int) ($status['code'] ?? -1);
    }

    /**
     * Decide whether a failed unary RPC may be auto-retried on the given gRPC
     * code. Fail-safe by default: anything not explicitly allowed returns false.
     *
     *   - Read-only RPCs: retried on the configured transient codes plus
     *     DEADLINE_EXCEEDED. Unchanged behaviour.
     *   - Mutations: retried ONLY when the RPC is proto-declared replay-safe AND
     *     the caller supplied a non-empty idempotency key. Both are mandatory.
     *     DEADLINE_EXCEEDED is NOT retried for mutations — the server may have
     *     applied the write before the deadline fired and the SDK cannot prove
     *     the dedup record landed, so DEADLINE stays a fail-closed terminal and
     *     only the configured transient codes (UNAVAILABLE / RESOURCE_EXHAUSTED,
     *     which fail before any server-side effect) are eligible.
     *   - Non-replay-safe mutations are NEVER retried, regardless of key.
     */
    private function isRetryable(int $code, bool $readOnly, bool $replaySafe, bool $hasIdempotencyKey): bool
    {
        if ($readOnly) {
            if ($code === 4) { // DEADLINE_EXCEEDED
                return true;
            }
            return in_array($code, self::RETRYABLE_CODES, true);
        }
        // Mutation: fail-closed unless proto-declared replay-safe AND idempotency-keyed.
        if (! $replaySafe || ! $hasIdempotencyKey) {
            return false;
        }
        return in_array($code, self::RETRYABLE_CODES, true);
    }

    /**
     * Whether the request proto carries a non-empty `idempotency_key`. Requests
     * without the accessor (the field is absent) return false. This is the
     * SDK-side gate that lets a replay-safe mutation be retried: without a key
     * the broker cannot dedup a replay, so we must not retry. Read via the
     * protoc-generated `getIdempotencyKey()` accessor — no per-message imports.
     */
    private function hasIdempotencyKey(mixed $request): bool
    {
        if (! is_object($request) || ! method_exists($request, 'getIdempotencyKey')) {
            return false;
        }
        try {
            return trim((string) $request->getIdempotencyKey()) !== '';
        } catch (\Throwable) {
            return false;
        }
    }

    // Retry safety is read from the proto-derived operation_kind + replay_safe
    // per RPC (each wrapper passes operation_kind === 'read_only' and the request
    // so REPLAY_SAFE / idempotency-key can be consulted) — never guessed from the name.

    /**
     * Exponential backoff with full jitter, capped at `max_delay_ms`. Sleeps
     * via `usleep` (microseconds). Honours a broker-supplied `retry_after_ms`
     * from the typed ErrorDetail when present (set by `mapError`-adjacent
     * decode in a follow-up; here we use the computed backoff).
     */
    private function sleepBackoff(int $attempt, int $baseDelayMs, int $maxDelayMs): void
    {
        $ceil = (int) min($maxDelayMs, $baseDelayMs * (2 ** ($attempt - 1)));
        $jittered = random_int(0, max(0, $ceil));
        if ($jittered > 0) {
            usleep($jittered * 1000);
        }
    }

    /**
     * Map a non-OK gRPC status to a typed {@see UdbRpcException}. When the
     * broker attached a binary `udb-error-detail-bin` trailer, decode it into
     * an {@see \Udb\Entity\V1\ErrorDetail} (if that generated class exists) and
     * carry it on the exception for typed capability/policy/quota branching.
     */
    private function mapError(mixed $status, string $rpcName): UdbRpcException
    {
        $detail = $this->decodeErrorDetail($status) ?? $this->synthesizeTransportErrorDetail($status);
        $exception = UdbRpcException::fromGrpcStatus($status, $rpcName);
        if ($detail !== null && property_exists($exception, 'errorDetail')) {
            // Forward-compatible: only set if the hand-written exception grows
            // an `errorDetail` slot. Until then the raw status (which carries
            // the trailer) is preserved on `$exception->raw`.
            $exception->errorDetail = $detail;
        }
        return $exception;
    }

    /**
     * Extract + prost-decode the `udb-error-detail-bin` trailer, if any.
     *
     * @return object|null  a \Udb\Entity\V1\ErrorDetail or null
     */
    private function decodeErrorDetail(mixed $status): ?object
    {
        $metadata = is_object($status) ? ($status->metadata ?? null) : ($status['metadata'] ?? null);
        if (! is_array($metadata)) {
            return null;
        }
        $values = $metadata['udb-error-detail-bin'] ?? null;
        if (! is_array($values) || $values === []) {
            return null;
        }
        $fqn = '\\Udb\\Entity\\V1\\ErrorDetail';
        if (! class_exists($fqn)) {
            return null;
        }
        try {
            /** @var \Google\Protobuf\Internal\Message $detail */
            $detail = new $fqn();
            $detail->mergeFromString((string) $values[0]);
            return $detail;
        } catch (\Throwable) {
            return null;
        }
    }

    /**
     * Build the same ErrorDetail shape for local transport statuses that never
     * reached the broker and therefore have no server trailer.
     *
     * @return object|null  a \Udb\Entity\V1\ErrorDetail or null
     */
    private function synthesizeTransportErrorDetail(mixed $status): ?object
    {
        $code = $this->statusCode($status);
        if (! in_array($code, [1, 4, 14], true)) { // CANCELLED, DEADLINE_EXCEEDED, UNAVAILABLE
            return null;
        }
        $detailFqn = '\\Udb\\Entity\\V1\\ErrorDetail';
        $kindFqn = '\\Udb\\Entity\\V1\\ErrorKind';
        if (! class_exists($detailFqn) || ! class_exists($kindFqn)) {
            return null;
        }
        $operation = match ($code) {
            1 => 'cancelled',
            4 => 'deadline_exceeded',
            14 => 'unavailable',
            default => 'transport',
        };
        try {
            /** @var \Udb\Entity\V1\ErrorDetail $detail */
            $detail = new $detailFqn();
            $detail->setBackend('transport');
            $detail->setOperation($operation);
            $detail->setRetryable($code !== 1);
            $detail->setRetryAfterMs(0);
            $detail->setKind($kindFqn::ERROR_KIND_RETRYABLE);
            return $detail;
        } catch (\Throwable) {
            return null;
        }
    }
}

final class IrJson
{
    private const COMPARISON_TOKENS = [
        'eq' => 'eq',
        'ne' => 'ne',
        'gt' => 'gt',
        'ge' => 'ge',
        'lt' => 'lt',
        'le' => 'le',
        'like' => 'like',
    ];

    public static function logicalValue(mixed $value): mixed
    {
        if ($value === null) {
            return 'Null';
        }
        if (is_bool($value)) {
            return ['Bool' => $value];
        }
        if (is_int($value)) {
            return ['Int' => $value];
        }
        if (is_float($value)) {
            return ['Float' => $value];
        }
        if (is_string($value)) {
            return ['String' => $value];
        }
        if ($value instanceof \DateTimeInterface) {
            $utc = \DateTimeImmutable::createFromInterface($value)
                ->setTimezone(new \DateTimeZone('UTC'));
            return ['Timestamp' => $utc->format('Y-m-d\TH:i:s.u\Z')];
        }
        if (is_array($value)) {
            if (array_is_list($value)) {
                return ['Array' => array_map([self::class, 'logicalValue'], $value)];
            }
            return ['Json' => $value];
        }
        return ['Json' => $value];
    }

    public static function logicalRecord(array $row): array
    {
        ksort($row, SORT_STRING);
        $out = [];
        foreach ($row as $key => $value) {
            $out[(string) $key] = self::logicalValue($value);
        }
        return $out;
    }

    public static function comparison(string $field, string $op, mixed $value): array
    {
        $token = self::COMPARISON_TOKENS[$op] ?? null;
        if ($token === null) {
            throw new \InvalidArgumentException("udb: unsupported IR operator '{$op}'");
        }
        return ['Comparison' => ['field' => $field, 'op' => $token, 'value' => self::logicalValue($value)]];
    }

    public static function inList(string $field, iterable $values): array
    {
        $encoded = [];
        foreach ($values as $value) {
            $encoded[] = self::logicalValue($value);
        }
        return ['InList' => ['field' => $field, 'values' => $encoded]];
    }

    public static function andFilter(array $predicates): array
    {
        return ['And' => array_values($predicates)];
    }

    public static function orFilter(array $predicates): array
    {
        return ['Or' => array_values($predicates)];
    }

    public static function filter(array $predicates): ?array
    {
        $count = count($predicates);
        if ($count === 0) {
            return null;
        }
        if ($count === 1) {
            return $predicates[0];
        }
        return ['And' => array_values($predicates)];
    }

    public static function specJson(array $body): string
    {
        return json_encode(
            ['ir' => $body],
            JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
        );
    }
}

abstract class IrPredicateBuilder
{
    /** @var list<array<string,mixed>> */
    protected array $predicates = [];

    public function where(string $field, string $op, mixed $value): static
    {
        if ($op === 'in') {
            return $this->whereIn($field, is_iterable($value) ? $value : [$value]);
        }
        $this->predicates[] = IrJson::comparison($field, $op, $value);
        return $this;
    }

    public function whereIn(string $field, iterable $values): static
    {
        $this->predicates[] = IrJson::inList($field, $values);
        return $this;
    }

    public function whereFilter(array $filter): static
    {
        $this->predicates[] = $filter;
        return $this;
    }
}

final class EagerIncludeUnsupportedBackendException extends \RuntimeException
{
    public function __construct(public readonly string $backend, public readonly ?string $tier = null)
    {
        parent::__construct(
            "udb: backend '{$backend}' is " . ($tier ?? 'unknown') . '; eager include requires a relational backend'
        );
    }
}

final class IrQuery extends IrPredicateBuilder
{
    /** @var list<string>|null */
    private ?array $projection = null;

    /** @var list<array{field:string,direction:string}> */
    private array $sorts = [];

    /** @var list<array{relation:string}> */
    private array $includes = [];

    private ?int $limit = null;
    private ?int $offset = null;

    public function __construct(private readonly string $messageType) {}

    public function select(string ...$fields): self
    {
        $this->projection = array_values($fields);
        return $this;
    }

    public function orderBy(string $field, string $direction = 'asc'): self
    {
        $this->sorts[] = ['field' => $field, 'direction' => $direction];
        return $this;
    }

    public function include(string $relation): self
    {
        if ($relation === '') {
            throw new \InvalidArgumentException('udb: include relation name is required');
        }
        $this->includes[] = ['relation' => $relation];
        return $this;
    }

    public function limit(int $n): self
    {
        $this->limit = $n;
        return $this;
    }

    public function offset(int $n): self
    {
        $this->offset = $n;
        return $this;
    }

    public function toEnvelope(): array
    {
        $body = ['op' => 'read', 'message_type' => $this->messageType];
        $filter = IrJson::filter($this->predicates);
        if ($filter !== null) {
            $body['filter'] = $filter;
        }
        if ($this->projection !== null && $this->projection !== []) {
            $body['projection'] = ['fields' => $this->projection];
        }
        if ($this->sorts !== []) {
            $body['sort'] = $this->sorts;
        }
        if ($this->includes !== []) {
            $body['include'] = $this->includes;
        }
        if ($this->limit !== null || $this->offset !== null) {
            $pagination = [];
            if ($this->limit !== null) {
                $pagination['limit'] = $this->limit;
            }
            if ($this->offset !== null) {
                $pagination['offset'] = $this->offset;
            }
            $body['pagination'] = $pagination;
        }
        return ['ir' => $body];
    }

    public function toSpecJson(): string
    {
        return IrJson::specJson($this->toEnvelope()['ir']);
    }

    public function toRequest(string $backend = GeneratedClient::DEFAULT_IR_BACKEND): object
    {
        if ($this->includes !== []) {
            GeneratedClient::requireEagerIncludeBackend($backend);
        }
        return GeneratedClient::rawDispatchRequest($backend, 'query', $this->toSpecJson());
    }

    public function execute(GeneratedClient $client, string $backend = GeneratedClient::DEFAULT_IR_BACKEND, ?UdbMetadata $metadata = null): object
    {
        return $client->genericDispatch($this->toRequest($backend), $metadata);
    }
}

final class IrWriteQuery
{
    /** @var list<array<string,mixed>> */
    private array $rows = [];

    private ?array $conflict = null;

    /** @var list<string> */
    private array $returnFields = [];

    public function __construct(private readonly string $messageType) {}

    public function record(array $row): self
    {
        $this->rows[] = $row;
        return $this;
    }

    public function records(iterable $rows): self
    {
        foreach ($rows as $row) {
            $this->rows[] = (array) $row;
        }
        return $this;
    }

    public function merge(): self
    {
        $this->conflict = ['kind' => 'replace'];
        return $this;
    }

    public function ignoreConflicts(): self
    {
        $this->conflict = ['kind' => 'ignore'];
        return $this;
    }

    public function updateOnConflict(array $fields, array $conflictOn = []): self
    {
        $this->conflict = ['kind' => 'update', 'fields' => array_values($fields)];
        if ($conflictOn !== []) {
            $this->conflict['conflict_on'] = array_values($conflictOn);
        }
        return $this;
    }

    public function returning(string ...$fields): self
    {
        array_push($this->returnFields, ...$fields);
        return $this;
    }

    public function toEnvelope(): array
    {
        if ($this->rows === []) {
            throw new \LogicException('udb: write requires at least one record(...)');
        }
        $body = [
            'op' => 'write',
            'message_type' => $this->messageType,
            'records' => array_map([IrJson::class, 'logicalRecord'], $this->rows),
        ];
        if ($this->conflict !== null) {
            $body['conflict'] = $this->conflict;
        }
        if ($this->returnFields !== []) {
            $body['return_fields'] = $this->returnFields;
        }
        return ['ir' => $body];
    }

    public function toSpecJson(): string
    {
        return IrJson::specJson($this->toEnvelope()['ir']);
    }

    public function toRequest(string $backend = GeneratedClient::DEFAULT_IR_BACKEND): object
    {
        return GeneratedClient::rawDispatchRequest($backend, 'mutate', $this->toSpecJson());
    }

    public function execute(GeneratedClient $client, string $backend = GeneratedClient::DEFAULT_IR_BACKEND, ?UdbMetadata $metadata = null): object
    {
        return $client->genericDispatch($this->toRequest($backend), $metadata);
    }
}

final class IrDeleteQuery extends IrPredicateBuilder
{
    /** @var list<string> */
    private array $returnFields = [];

    public function __construct(private readonly string $messageType) {}

    public function returning(string ...$fields): self
    {
        array_push($this->returnFields, ...$fields);
        return $this;
    }

    public function toEnvelope(): array
    {
        $filter = IrJson::filter($this->predicates);
        if ($filter === null) {
            throw new \LogicException('udb: delete requires at least one where(...) predicate (no delete-everything path)');
        }
        $body = ['op' => 'delete', 'message_type' => $this->messageType, 'filter' => $filter];
        if ($this->returnFields !== []) {
            $body['return_fields'] = $this->returnFields;
        }
        return ['ir' => $body];
    }

    public function toSpecJson(): string
    {
        return IrJson::specJson($this->toEnvelope()['ir']);
    }

    public function toRequest(string $backend = GeneratedClient::DEFAULT_IR_BACKEND): object
    {
        return GeneratedClient::rawDispatchRequest($backend, 'mutate', $this->toSpecJson());
    }

    public function execute(GeneratedClient $client, string $backend = GeneratedClient::DEFAULT_IR_BACKEND, ?UdbMetadata $metadata = null): object
    {
        return $client->genericDispatch($this->toRequest($backend), $metadata);
    }
}

final class EntityRepository
{
    /** @param array{table:string,primary_keys:list<string>,fields:list<string>,relations_json:string,version_field:string,tenant_field:string,project_field:string,php_type:string} $binding */
    public function __construct(
        private readonly string $messageType,
        private readonly array $binding,
    ) {
        if (($this->binding['primary_keys'] ?? []) === []) {
            throw new \InvalidArgumentException("udb: entity {$this->messageType} has no descriptor primary key");
        }
    }

    public function query(): IrQuery
    {
        return GeneratedClient::query($this->messageType);
    }

    public function messageType(): string
    {
        return $this->messageType;
    }

    /** @return array{table:string,primary_keys:list<string>,fields:list<string>,relations_json:string,version_field:string,tenant_field:string,project_field:string,php_type:string} */
    public function binding(): array
    {
        return $this->binding;
    }

    /** @return list<array<string,mixed>> */
    public function relations(): array
    {
        $raw = $this->binding['relations_json'] ?? '[]';
        $relations = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
        if (! is_array($relations)) {
            throw new \LogicException("udb: invalid relation metadata for entity {$this->messageType}");
        }
        return array_values($relations);
    }

    /** @return array<string,mixed>|null */
    public function relation(string $name): ?array
    {
        foreach ($this->relations() as $relation) {
            if (($relation['name'] ?? null) === $name) {
                return $relation;
            }
        }
        return null;
    }

    /** @return array<string,mixed> */
    public function requireRelation(string $name): array
    {
        $relation = $this->relation($name);
        if ($relation === null) {
            throw new \InvalidArgumentException("udb: unknown relation '{$name}' on entity {$this->messageType}");
        }
        $localFields = $relation['local_fields'] ?? [];
        $targetFields = $relation['target_fields'] ?? [];
        if ($localFields === [] || count($localFields) !== count($targetFields)) {
            throw new \LogicException("udb: relation '{$name}' on entity {$this->messageType} has invalid field mapping");
        }
        if (($relation['target_message_type'] ?? '') === '') {
            throw new \LogicException("udb: relation '{$name}' on entity {$this->messageType} has no target entity");
        }
        return $relation;
    }

    public function relationQuery(string $name, array $parent): IrQuery
    {
        $relation = $this->requireRelation($name);
        $query = GeneratedClient::query($relation['target_message_type']);
        foreach ($relation['local_fields'] as $idx => $localField) {
            if (! array_key_exists($localField, $parent)) {
                throw new \InvalidArgumentException("udb: relation '{$name}' missing parent field '{$localField}'");
            }
            $query->where($relation['target_fields'][$idx], 'eq', $parent[$localField]);
        }
        return $query;
    }

    /**
     * @param list<array<string,mixed>> $parents
     */
    public function relationBatchQuery(string $name, array $parents): IrQuery
    {
        $relation = $this->requireRelation($name);
        $localFields = array_values($relation['local_fields']);
        $targetFields = array_values($relation['target_fields']);
        if (count($localFields) !== count($targetFields)) {
            throw new \LogicException("udb: relation '{$name}' on entity {$this->messageType} has invalid field mapping");
        }
        if ($parents === []) {
            throw new \InvalidArgumentException("udb: relation '{$name}' batch query requires at least one parent");
        }
        if (count($localFields) === 1) {
            $localField = (string) $localFields[0];
            $values = [];
            $seen = [];
            foreach ($parents as $parent) {
                if (! array_key_exists($localField, $parent)) {
                    throw new \InvalidArgumentException("udb: relation '{$name}' missing parent field '{$localField}'");
                }
                $value = $parent[$localField];
                $key = json_encode($value, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                if (! array_key_exists($key, $seen)) {
                    $seen[$key] = true;
                    $values[] = $value;
                }
            }
            return GeneratedClient::query((string) $relation['target_message_type'])
                ->whereIn((string) $targetFields[0], $values);
        }
        $branches = [];
        $seen = [];
        foreach ($parents as $parent) {
            $comparisons = [];
            foreach ($localFields as $idx => $localField) {
                $localField = (string) $localField;
                if (! array_key_exists($localField, $parent)) {
                    throw new \InvalidArgumentException("udb: relation '{$name}' missing parent field '{$localField}'");
                }
                $comparisons[] = IrJson::comparison((string) $targetFields[$idx], 'eq', $parent[$localField]);
            }
            $key = json_encode($comparisons, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            if (! array_key_exists($key, $seen)) {
                $seen[$key] = true;
                $branches[] = IrJson::andFilter($comparisons);
            }
        }
        return GeneratedClient::query((string) $relation['target_message_type'])
            ->whereFilter(IrJson::orFilter($branches));
    }

{{ENTITY_PHP_RELATION_ACCESSORS}}

    public function find(array $key, GeneratedClient $client, string $backend = GeneratedClient::DEFAULT_IR_BACKEND, ?UdbMetadata $metadata = null): object
    {
        $query = $this->query()->limit(1);
        foreach ($this->binding['primary_keys'] as $field) {
            if (! array_key_exists($field, $key)) {
                throw new \InvalidArgumentException("udb: missing primary key field '{$field}'");
            }
            $query->where($field, 'eq', $key[$field]);
        }
        return $query->execute($client, $backend, $metadata);
    }

    public function first(IrQuery $query, GeneratedClient $client, string $backend = GeneratedClient::DEFAULT_IR_BACKEND, ?UdbMetadata $metadata = null): object
    {
        return $query->limit(1)->execute($client, $backend, $metadata);
    }

    public function all(IrQuery $query, GeneratedClient $client, string $backend = GeneratedClient::DEFAULT_IR_BACKEND, ?UdbMetadata $metadata = null): object
    {
        return $query->execute($client, $backend, $metadata);
    }

    public function upsert(array $record, GeneratedClient $client, string $backend = GeneratedClient::DEFAULT_IR_BACKEND, ?UdbMetadata $metadata = null): object
    {
        $this->validateRecord($record);
        foreach ($this->binding['primary_keys'] as $field) {
            if (! array_key_exists($field, $record)) {
                throw new \InvalidArgumentException("udb: missing primary key field '{$field}'");
            }
        }
        $updateFields = array_values(array_diff(array_keys($record), $this->binding['primary_keys']));
        if ($updateFields === []) {
            throw new \InvalidArgumentException('udb: upsert requires at least one non-primary-key field');
        }
        return GeneratedClient::writeTo($this->messageType)
            ->record($record)
            ->updateOnConflict($updateFields, $this->binding['primary_keys'])
            ->execute($client, $backend, $metadata);
    }

    public function delete(array $key, GeneratedClient $client, string $backend = GeneratedClient::DEFAULT_IR_BACKEND, ?UdbMetadata $metadata = null): object
    {
        $delete = GeneratedClient::deleteFrom($this->messageType);
        foreach ($this->binding['primary_keys'] as $field) {
            if (! array_key_exists($field, $key)) {
                throw new \InvalidArgumentException("udb: missing primary key field '{$field}'");
            }
            $delete->where($field, 'eq', $key[$field]);
        }
        return $delete->execute($client, $backend, $metadata);
    }

    private function validateRecord(array $record): void
    {
        $fields = $this->binding['fields'] ?? [];
        if ($fields === []) {
            return;
        }
        $allowed = array_flip($fields);
        foreach (array_keys($record) as $field) {
            if (! array_key_exists($field, $allowed)) {
                throw new \InvalidArgumentException("udb: field '{$field}' is not declared on entity {$this->messageType}");
            }
        }
    }
}

final class UnitOfWorkEntry
{
    public function __construct(
        public readonly EntityRepository $repository,
        public array $record,
        public string $snapshot,
    ) {}
}

class UnitOfWorkTxException extends \RuntimeException
{
    public function __construct(string $message, public readonly ?object $status = null)
    {
        parent::__construct($message);
    }
}

final class UnitOfWorkConflictException extends UnitOfWorkTxException {}

final class UnitOfWorkUnsupportedBackendException extends \RuntimeException
{
    public function __construct(public readonly string $backend, public readonly ?string $role = null)
    {
        parent::__construct("udb: backend '{$backend}' is " . ($role ?? 'unknown') . '; UnitOfWork requires a canonical transactional backend');
    }
}

final class UnitOfWork
{
    /** @var array<string,UnitOfWorkEntry> */
    private array $entries = [];

    public function attach(EntityRepository $repository, array $record): array
    {
        $binding = $repository->binding();
        self::requireVersionForTrackedWrite($repository->messageType(), $binding, $record);
        $this->entries[self::entityIdentity($repository->messageType(), $binding, $record)] = new UnitOfWorkEntry(
            $repository,
            $record,
            self::stableRecordJson($record),
        );
        return $record;
    }

    public function track(EntityRepository $repository, array $record): array
    {
        return $this->attach($repository, $record);
    }

    public function update(EntityRepository $repository, array $record): array
    {
        $binding = $repository->binding();
        self::requireVersionForTrackedWrite($repository->messageType(), $binding, $record);
        $identity = self::entityIdentity($repository->messageType(), $binding, $record);
        if (! isset($this->entries[$identity])) {
            return $this->attach($repository, $record);
        }
        $this->entries[$identity]->record = $record;
        return $record;
    }

    /** @return list<UnitOfWorkEntry> */
    public function dirtyEntries(): array
    {
        return array_values(array_filter(
            $this->entries,
            static fn (UnitOfWorkEntry $entry): bool => self::stableRecordJson($entry->record) !== $entry->snapshot,
        ));
    }

    /** @return list<object> */
    public function txMutations(): array
    {
        $fqn = self::mutationClass();
        return array_map(static function (UnitOfWorkEntry $entry) use ($fqn): object {
            $mutation = new $fqn();
            $mutation->setOperation('upsert');
            $mutation->setMessageType($entry->repository->messageType());
            $mutation->setRecordJson(self::stableRecordJson($entry->record));
            return $mutation;
        }, $this->dirtyEntries());
    }

    public function commitMutation(): object
    {
        $fqn = self::mutationClass();
        $mutation = new $fqn();
        $mutation->setCommit(true);
        return $mutation;
    }

    public function rollbackMutation(): object
    {
        $fqn = self::mutationClass();
        $mutation = new $fqn();
        $mutation->setRollback(true);
        return $mutation;
    }

    /** @return list<object> */
    public function txCommitBatch(string $backend = GeneratedClient::DEFAULT_IR_BACKEND): array
    {
        $this->requireTransactionalBackend($backend);
        return [...$this->txMutations(), $this->commitMutation()];
    }

    public function requireTransactionalBackend(string $backend = GeneratedClient::DEFAULT_IR_BACKEND): void
    {
        $role = GeneratedClient::backendRoles()[$backend] ?? null;
        if ($role !== 'canonical' && $role !== 'both') {
            throw new UnitOfWorkUnsupportedBackendException($backend, $role);
        }
    }

    public function validateTxStatuses(iterable $statuses): void
    {
        foreach ($statuses as $status) {
            $state = method_exists($status, 'getState') ? (string) $status->getState() : '';
            $message = method_exists($status, 'getMessage') ? (string) $status->getMessage() : '';
            if ($state !== '4' && ! str_contains(strtoupper($state), 'ERROR')) {
                continue;
            }
            $message = $message !== '' ? $message : 'udb: unit-of-work transaction failed';
            if (self::isTxConflictMessage($message)) {
                throw new UnitOfWorkConflictException($message, $status);
            }
            throw new UnitOfWorkTxException($message, $status);
        }
    }

    /** @return list<object> */
    public function flush(
        GeneratedClient $client,
        string $backend = GeneratedClient::DEFAULT_IR_BACKEND,
        ?UdbMetadata $metadata = null,
    ): array {
        if (! method_exists($client, 'beginTx')) {
            throw new UdbConfigurationException('GeneratedClient::beginTx is unavailable. Run sdk generation before UnitOfWork flush.');
        }
        $call = $client->beginTx($metadata);
        foreach ($this->txCommitBatch($backend) as $mutation) {
            $call->write($mutation);
        }
        $call->writesDone();
        $statuses = [];
        while (($status = $call->read()) !== null) {
            $statuses[] = $status;
        }
        $grpcStatus = method_exists($call, 'getStatus') ? $call->getStatus() : null;
        $code = is_object($grpcStatus) ? (int) ($grpcStatus->code ?? 0) : (int) (($grpcStatus['code'] ?? 0));
        if ($code !== 0) {
            throw UdbRpcException::fromGrpcStatus($grpcStatus, 'BeginTx');
        }
        $this->validateTxStatuses($statuses);
        $this->markClean();
        return $statuses;
    }

    public function markClean(): void
    {
        foreach ($this->entries as $entry) {
            $entry->snapshot = self::stableRecordJson($entry->record);
        }
    }

    private static function requireVersionForTrackedWrite(string $messageType, array $binding, array $record): void
    {
        $versionField = $binding['version_field'] ?? '';
        if ($versionField !== '' && ! array_key_exists($versionField, $record)) {
            throw new \InvalidArgumentException("udb: unit-of-work record for {$messageType} missing version field '{$versionField}'");
        }
    }

    private static function entityIdentity(string $messageType, array $binding, array $record): string
    {
        $scopeParts = [];
        foreach ([$binding['tenant_field'] ?? '', $binding['project_field'] ?? ''] as $field) {
            if ($field === '') {
                continue;
            }
            if (! array_key_exists($field, $record)) {
                throw new \InvalidArgumentException("udb: unit-of-work record for {$messageType} missing scope field '{$field}'");
            }
            $scopeParts[] = $field . '=' . json_encode($record[$field], JSON_THROW_ON_ERROR);
        }
        $parts = [];
        foreach ($binding['primary_keys'] as $field) {
            if (! array_key_exists($field, $record)) {
                throw new \InvalidArgumentException("udb: unit-of-work record for {$messageType} missing primary key field '{$field}'");
            }
            $parts[] = json_encode($record[$field], JSON_THROW_ON_ERROR);
        }
        return $messageType . ':' . implode(':', $scopeParts) . ':' . implode(':', $parts);
    }

    private static function stableRecordJson(array $record): string
    {
        ksort($record);
        return json_encode($record, JSON_THROW_ON_ERROR);
    }

    private static function mutationClass(): string
    {
        $fqn = '\\Udb\\Entity\\V1\\Mutation';
        if (! class_exists($fqn)) {
            throw new UdbConfigurationException('UDB Mutation class not found. Run buf generate before UnitOfWork flush.');
        }
        return $fqn;
    }

    private static function isTxConflictMessage(string $message): bool
    {
        $lower = strtolower($message);
        return str_contains($lower, 'aborted') || str_contains($lower, 'version') || str_contains($lower, 'conflict');
    }
}