agent-first-psql 0.7.1

A PostgreSQL interface for AI agents: reliable, structured, explicit, and read-only by default.
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
use crate::conn::resolve_session_name;
use crate::db::{
    DbExecutor, ExecError, ExecOutcome, ExecRequest, PostgresExecutor, RowSink, StreamOutcome,
    TransportLogContext,
};
use crate::protocol::{command_tag, error_code, log_event};
use crate::types::*;
use serde_json::Value;
use std::sync::Arc;
use std::sync::atomic::{AtomicU8, Ordering};
use std::time::Instant;
use tokio::sync::{Mutex, RwLock, mpsc};

const QUERY_QUEUED: u8 = 0;
const QUERY_RUNNING: u8 = 1;
const QUERY_FINISHED: u8 = 2;
const QUERY_CANCELLED: u8 = 3;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum QueryPhase {
    Queued,
    Running,
    Finished,
    Cancelled,
}

pub struct QueryState {
    phase: AtomicU8,
}

impl QueryState {
    pub fn queued() -> Self {
        Self {
            phase: AtomicU8::new(QUERY_QUEUED),
        }
    }

    pub fn phase(&self) -> QueryPhase {
        match self.phase.load(Ordering::SeqCst) {
            QUERY_RUNNING => QueryPhase::Running,
            QUERY_FINISHED => QueryPhase::Finished,
            QUERY_CANCELLED => QueryPhase::Cancelled,
            _ => QueryPhase::Queued,
        }
    }

    pub fn set_phase(&self, phase: QueryPhase) {
        let value = match phase {
            QueryPhase::Queued => QUERY_QUEUED,
            QueryPhase::Running => QUERY_RUNNING,
            QueryPhase::Finished => QUERY_FINISHED,
            QueryPhase::Cancelled => QUERY_CANCELLED,
        };
        self.phase.store(value, Ordering::SeqCst);
    }

    pub fn try_start(&self) -> bool {
        self.phase
            .compare_exchange(
                QUERY_QUEUED,
                QUERY_RUNNING,
                Ordering::SeqCst,
                Ordering::SeqCst,
            )
            .is_ok()
    }

    pub fn is_finished(&self) -> bool {
        matches!(self.phase(), QueryPhase::Finished | QueryPhase::Cancelled)
    }
}

#[derive(Clone)]
pub struct InFlightQuery {
    pub cancel_slot: crate::db::CancelSlot,
    pub state: Arc<QueryState>,
}

impl InFlightQuery {
    pub async fn cancel_server_query(&self) -> Result<bool, String> {
        crate::db::cancel_query(&self.cancel_slot).await
    }
}

pub struct App {
    pub capability: crate::Capability,
    pub locked_readonly_profile: std::sync::atomic::AtomicBool,
    pub config: RwLock<RuntimeConfig>,
    pub executor: Arc<dyn DbExecutor>,
    pub writer: mpsc::Sender<Output>,
    pub in_flight: Mutex<std::collections::HashMap<String, InFlightQuery>>,
    pub requests_total: std::sync::atomic::AtomicU64,
    pub start_time: Instant,
}

impl App {
    pub fn new(
        config: RuntimeConfig,
        writer: mpsc::Sender<Output>,
        capability: crate::Capability,
    ) -> Self {
        Self {
            capability,
            locked_readonly_profile: std::sync::atomic::AtomicBool::new(false),
            config: RwLock::new(config),
            executor: Arc::new(PostgresExecutor::new()),
            writer,
            in_flight: Mutex::new(std::collections::HashMap::new()),
            requests_total: std::sync::atomic::AtomicU64::new(0),
            start_time: Instant::now(),
        }
    }
}

pub async fn execute_query(
    app: &Arc<App>,
    id: Option<String>,
    session: Option<String>,
    sql: String,
    params: Vec<Value>,
    options: QueryOptions,
    cancel_slot: Option<crate::db::CancelSlot>,
) {
    let start = Instant::now();
    let cfg = app.config.read().await.clone();
    let resolved_session = resolve_session_name(&cfg, session.as_deref());

    let Some(session_cfg) = cfg.sessions.get(&resolved_session).cloned() else {
        let trace = Trace::only_duration(start.elapsed().as_millis() as u64);
        let _ = app
            .writer
            .send(Output::Error {
                id: id.clone(),
                error_code: error_code::CONNECT_FAILED.to_string(),
                error: format!("unknown session: {resolved_session}"),
                sqlstate: None,
                message: None,
                detail: None,
                hint: Some(
                    "check --host/--port or PGHOST/PGPORT environment variables".to_string(),
                ),
                retryable: true,
                trace: trace.clone(),
            })
            .await;
        emit_log(
            app,
            log_event::QUERY_ERROR,
            id.as_deref(),
            Some(&resolved_session),
            Some(error_code::CONNECT_FAILED),
            None,
            &trace,
        )
        .await;
        return;
    };

    let resolved_opts = match cfg.resolve_options_for_session(&options, &session_cfg) {
        Ok(opts) => opts,
        Err(message) => {
            let trace = Trace::only_duration(start.elapsed().as_millis() as u64);
            let readonly_write = app.capability == crate::Capability::ReadOnly
                && options
                    .permission
                    .is_some_and(|value| !value.is_read_only());
            let (message, hint) = if readonly_write {
                (
                    "write permission is unavailable in afpsql-readonly".to_string(),
                    crate::readonly_hint().to_string(),
                )
            } else {
                (message, permission_error_hint(&options, &session_cfg))
            };
            let _ = app
                .writer
                .send(Output::Error {
                    id: id.clone(),
                    error_code: error_code::INVALID_REQUEST.to_string(),
                    error: message,
                    sqlstate: None,
                    message: None,
                    detail: None,
                    hint: Some(hint),
                    retryable: false,
                    trace: trace.clone(),
                })
                .await;
            emit_log(
                app,
                log_event::QUERY_ERROR,
                id.as_deref(),
                Some(&resolved_session),
                Some(error_code::INVALID_REQUEST),
                None,
                &trace,
            )
            .await;
            return;
        }
    };

    let readonly_policy_error = if app.capability == crate::Capability::ReadOnly {
        crate::readonly_policy::validate_session_with_trust(
            &session_cfg,
            app.locked_readonly_profile.load(Ordering::Relaxed),
        )
        .err()
        .map(|error| (error, crate::readonly_local_capability_hint()))
        .or_else(|| {
            crate::readonly_policy::validate_sql(&sql)
                .err()
                .map(|error| (error, crate::readonly_hint()))
        })
    } else {
        None
    };
    if readonly_policy_error.is_some()
        || (app.capability == crate::Capability::ReadOnly && !resolved_opts.read_only)
    {
        let trace = Trace::only_duration(start.elapsed().as_millis() as u64);
        let (error, hint) = readonly_policy_error.unwrap_or_else(|| {
            (
                "write permission is unavailable in afpsql-readonly".to_string(),
                crate::readonly_hint(),
            )
        });
        let _ = app
            .writer
            .send(Output::Error {
                id: id.clone(),
                error_code: error_code::INVALID_REQUEST.to_string(),
                error,
                sqlstate: None,
                message: None,
                detail: None,
                hint: Some(hint.to_string()),
                retryable: false,
                trace: trace.clone(),
            })
            .await;
        emit_log(
            app,
            log_event::QUERY_ERROR,
            id.as_deref(),
            Some(&resolved_session),
            Some(error_code::INVALID_REQUEST),
            None,
            &trace,
        )
        .await;
        return;
    }

    let cancel_slot_for_suppression = cancel_slot.clone();

    if resolved_opts.stream_rows {
        let mut sink = OutputRowSink::new(
            app.clone(),
            id.clone().unwrap_or_else(|| "cli".to_string()),
            Some(resolved_session.clone()),
            resolved_opts.batch_rows,
            resolved_opts.batch_bytes,
        );
        let result = app
            .executor
            .execute_streaming(
                ExecRequest {
                    session_name: &resolved_session,
                    session_cfg: &session_cfg,
                    sql: &sql,
                    params: &params,
                    opts: &resolved_opts,
                    cancel_slot: cancel_slot.clone(),
                    transport_log: Some(TransportLogContext {
                        session: resolved_session.clone(),
                        log: cfg.log.clone(),
                        writer: app.writer.clone(),
                    }),
                },
                &mut sink,
            )
            .await;
        if cancel_requested(&cancel_slot_for_suppression) {
            return;
        }
        if !try_claim_terminal_emit(&cancel_slot_for_suppression) {
            return;
        }
        handle_streaming_result(app, id, resolved_session, result, sink, start).await;
        return;
    }

    let result = app
        .executor
        .execute(ExecRequest {
            session_name: &resolved_session,
            session_cfg: &session_cfg,
            sql: &sql,
            params: &params,
            opts: &resolved_opts,
            cancel_slot: cancel_slot.clone(),
            transport_log: Some(TransportLogContext {
                session: resolved_session.clone(),
                log: cfg.log.clone(),
                writer: app.writer.clone(),
            }),
        })
        .await;

    if cancel_requested(&cancel_slot) {
        return;
    }
    if !try_claim_terminal_emit(&cancel_slot) {
        return;
    }

    match result {
        Ok(ExecOutcome::Rows {
            columns,
            rows,
            truncated,
            truncated_at_rows,
            truncated_at_bytes,
        }) => {
            let status = emit_rows_result(
                app,
                id.clone(),
                Some(resolved_session.clone()),
                columns,
                rows,
                InlineTruncation {
                    truncated,
                    at_rows: truncated_at_rows,
                    at_bytes: truncated_at_bytes,
                },
                start,
                &resolved_opts,
            )
            .await;
            let RowEmitStatus::Sent { trace } = status;
            emit_log(
                app,
                log_event::QUERY_RESULT,
                id.as_deref(),
                Some(&resolved_session),
                None,
                Some(command_tag::SELECT),
                &trace,
            )
            .await;
        }
        Ok(ExecOutcome::Command { affected }) => {
            emit_command_result(app, id, &resolved_session, affected, start).await;
        }
        Err(err) => emit_exec_error(app, id, &resolved_session, err, start).await,
    }
}

fn permission_error_hint(options: &QueryOptions, session: &SessionConfig) -> String {
    match (session.transport_kind(), options.permission) {
        (Ok(TransportKind::Ssh), Some(permission)) if !permission.allows_ssh() => format!(
            "this session uses afpsql SSH transport, so permission `{}` is invalid; use `ssh-read` for reads or `ssh-write` for writes",
            permission.as_str()
        ),
        (Ok(TransportKind::Container), Some(permission)) if !permission.allows_container() => format!(
            "this session uses afpsql container transport, so permission `{}` is invalid; use `container-read` for reads or `container-write` for writes",
            permission.as_str()
        ),
        (Ok(TransportKind::Direct), Some(permission)) if permission.allows_ssh() => format!(
            "this session does not use afpsql SSH transport, so permission `{}` is invalid; use `read` for reads or `write` for writes",
            permission.as_str()
        ),
        (Ok(TransportKind::Direct), Some(permission)) if permission.allows_container() => format!(
            "this session does not use afpsql container transport, so permission `{}` is invalid; use `read` for reads or `write` for writes",
            permission.as_str()
        ),
        (Err(message), _) => message,
        _ => {
            "use read/write for direct connections, ssh-read/ssh-write for afpsql SSH transport, and container-read/container-write for afpsql container transport"
                .to_string()
        }
    }
}

/// Returns true if the caller wins the right to emit the terminal event
/// (`result`/`sql_error`/`error`) for this query id. CLI mode (no
/// cancel_slot) always wins. Pipe mode wins when the cancel dispatcher
/// hasn't already claimed and emitted `cancelled`.
fn try_claim_terminal_emit(cancel_slot: &Option<crate::db::CancelSlot>) -> bool {
    cancel_slot
        .as_ref()
        .map(|slot| slot.claim_terminal_emit())
        .unwrap_or(true)
}

fn cancel_requested(cancel_slot: &Option<crate::db::CancelSlot>) -> bool {
    cancel_slot
        .as_ref()
        .map(|slot| slot.is_cancelled())
        .unwrap_or(false)
}

pub async fn handle_session_info(app: &Arc<App>, id: Option<String>, session: Option<String>) {
    let start = Instant::now();
    let cfg = app.config.read().await.clone();
    let resolved_session = resolve_session_name(&cfg, session.as_deref());

    let Some(session_cfg) = cfg.sessions.get(&resolved_session).cloned() else {
        let trace = Trace::only_duration(start.elapsed().as_millis() as u64);
        let _ = app
            .writer
            .send(Output::Error {
                id: id.clone(),
                error_code: error_code::INVALID_REQUEST.to_string(),
                error: format!("unknown session: {resolved_session}"),
                sqlstate: None,
                message: None,
                detail: None,
                hint: Some(
                    "list active sessions with a `config` request, or pick the default session by omitting `session`"
                        .to_string(),
                ),
                retryable: false,
                trace,
            })
            .await;
        return;
    };

    let transport_kind = match session_cfg.transport_kind() {
        Ok(kind) => kind,
        Err(message) => {
            let trace = Trace::only_duration(start.elapsed().as_millis() as u64);
            let _ = app
                .writer
                .send(Output::Error {
                    id: id.clone(),
                    error_code: error_code::INVALID_REQUEST.to_string(),
                    error: message,
                    sqlstate: None,
                    message: None,
                    detail: None,
                    hint: Some(
                        "this session's transport flags are inconsistent; update the session via a `config` request before requesting `session_info`"
                            .to_string(),
                    ),
                    retryable: false,
                    trace,
                })
                .await;
            return;
        }
    };

    let permission_default = match transport_kind {
        TransportKind::Direct => Permission::Read,
        TransportKind::Ssh => Permission::SshRead,
        TransportKind::Container => Permission::ContainerRead,
    };

    let resolved_opts = match cfg
        .resolve_options_for_session(&QueryOptions::default(), &session_cfg)
    {
        Ok(opts) => opts,
        Err(message) => {
            let trace = Trace::only_duration(start.elapsed().as_millis() as u64);
            let _ = app
                .writer
                .send(Output::Error {
                    id: id.clone(),
                    error_code: error_code::INVALID_REQUEST.to_string(),
                    error: message,
                    sqlstate: None,
                    message: None,
                    detail: None,
                    hint: Some(
                        "the runtime config could not resolve query defaults for this session; update inline_max_rows/inline_max_bytes via `config` and retry"
                            .to_string(),
                    ),
                    retryable: false,
                    trace,
                })
                .await;
            return;
        }
    };

    let (database, user, host, port, server_version) =
        probe_session_identity(app, &resolved_session, &session_cfg, &resolved_opts).await;

    let trace = Trace::only_duration(start.elapsed().as_millis() as u64);
    let _ = app
        .writer
        .send(Output::SessionInfo {
            id,
            session: resolved_session,
            transport_kind: transport_kind.as_str().to_string(),
            permission_default: permission_default.as_str().to_string(),
            stream_rows_default: resolved_opts.stream_rows,
            batch_rows: resolved_opts.batch_rows,
            batch_bytes: resolved_opts.batch_bytes,
            inline_max_rows: resolved_opts.inline_max_rows,
            inline_max_bytes: resolved_opts.inline_max_bytes,
            statement_timeout_ms: resolved_opts.statement_timeout_ms,
            lock_timeout_ms: resolved_opts.lock_timeout_ms,
            database,
            user,
            host,
            port,
            server_version,
            trace,
        })
        .await;
}

async fn probe_session_identity(
    app: &Arc<App>,
    session_name: &str,
    session_cfg: &SessionConfig,
    resolved_opts: &ResolvedOptions,
) -> (
    Option<String>,
    Option<String>,
    Option<String>,
    Option<u16>,
    Option<String>,
) {
    let probe = app
        .executor
        .execute(ExecRequest {
            session_name,
            session_cfg,
            sql: "select current_database()::text as database, \
                  current_user::text as user, \
                  inet_server_addr()::text as host, \
                  inet_server_port() as port, \
                  current_setting('server_version') as server_version",
            params: &[],
            opts: resolved_opts,
            cancel_slot: None,
            transport_log: None,
        })
        .await;

    if let Ok(ExecOutcome::Rows { rows, .. }) = probe
        && let Some(row) = rows.first().and_then(|v| v.as_object())
    {
        let s = |key: &str| -> Option<String> {
            row.get(key).and_then(|v| v.as_str().map(|s| s.to_string()))
        };
        let port = row
            .get("port")
            .and_then(|v| v.as_i64())
            .and_then(|n| u16::try_from(n).ok())
            .or_else(|| {
                row.get("port")
                    .and_then(|v| v.as_str())
                    .and_then(|s| s.parse().ok())
            });
        return (
            s("database").or_else(|| session_cfg.dbname.clone()),
            s("user").or_else(|| session_cfg.user.clone()),
            s("host").or_else(|| session_cfg.host.clone()),
            port.or(session_cfg.port),
            s("server_version"),
        );
    }

    (
        session_cfg.dbname.clone(),
        session_cfg.user.clone(),
        session_cfg.host.clone(),
        session_cfg.port,
        None,
    )
}

async fn handle_streaming_result(
    app: &Arc<App>,
    id: Option<String>,
    resolved_session: String,
    result: Result<StreamOutcome, ExecError>,
    mut sink: OutputRowSink,
    start: Instant,
) {
    match result {
        Ok(StreamOutcome::Rows {
            row_count,
            payload_bytes,
        }) => {
            let _ = sink.flush_batch().await;
            let trace = Trace {
                duration_ms: start.elapsed().as_millis() as u64,
                row_count: Some(row_count),
                payload_bytes: Some(payload_bytes),
            };
            let _ = app
                .writer
                .send(Output::ResultEnd {
                    id: sink.id.clone(),
                    session: Some(resolved_session.clone()),
                    command_tag: command_tag::rows(row_count),
                    trace: trace.clone(),
                })
                .await;
            emit_log(
                app,
                log_event::QUERY_RESULT,
                id.as_deref(),
                Some(&resolved_session),
                None,
                Some(command_tag::SELECT),
                &trace,
            )
            .await;
        }
        Ok(StreamOutcome::Command { affected }) => {
            emit_command_result(app, id, &resolved_session, affected, start).await;
        }
        Err(err) => {
            emit_exec_error(app, id, &resolved_session, err, start).await;
        }
    }
}

async fn emit_command_result(
    app: &Arc<App>,
    id: Option<String>,
    resolved_session: &str,
    affected: usize,
    start: Instant,
) {
    let command_tag = command_tag::execute(affected);
    let trace = Trace {
        duration_ms: start.elapsed().as_millis() as u64,
        row_count: Some(0),
        payload_bytes: Some(0),
    };
    let _ = app
        .writer
        .send(Output::Result {
            id: id.clone(),
            session: Some(resolved_session.to_string()),
            command_tag: command_tag.clone(),
            columns: vec![],
            rows: vec![],
            row_count: 0,
            truncated: false,
            truncated_at_rows: None,
            truncated_at_bytes: None,
            trace: trace.clone(),
        })
        .await;
    emit_log(
        app,
        log_event::QUERY_RESULT,
        id.as_deref(),
        Some(resolved_session),
        None,
        Some(command_tag::EXECUTE),
        &trace,
    )
    .await;
}

pub(crate) async fn emit_exec_error(
    app: &Arc<App>,
    id: Option<String>,
    resolved_session: &str,
    err: ExecError,
    start: Instant,
) {
    match err {
        ExecError::Cancelled => {
            let trace = Trace::only_duration(start.elapsed().as_millis() as u64);
            let _ = app
                .writer
                .send(Output::Error {
                    id: id.clone(),
                    error_code: error_code::CANCELLED.to_string(),
                    error: "query cancelled".to_string(),
                    sqlstate: None,
                    message: None,
                    detail: None,
                    hint: Some(
                        "cancellation is final; submit a new query with a fresh id to retry"
                            .to_string(),
                    ),
                    retryable: false,
                    trace: trace.clone(),
                })
                .await;
            emit_log(
                app,
                log_event::QUERY_ERROR,
                id.as_deref(),
                Some(resolved_session),
                Some(error_code::CANCELLED),
                None,
                &trace,
            )
            .await;
        }
        ExecError::Connect(connect) => {
            let connect = *connect;
            let trace = Trace::only_duration(start.elapsed().as_millis() as u64);
            let _ = app
                .writer
                .send(Output::Error {
                    id: id.clone(),
                    error_code: error_code::CONNECT_FAILED.to_string(),
                    error: connect.error,
                    sqlstate: connect.sqlstate,
                    message: connect.message,
                    detail: connect.detail,
                    hint: connect.hint,
                    retryable: connect.retryable,
                    trace: trace.clone(),
                })
                .await;
            emit_log(
                app,
                log_event::QUERY_ERROR,
                id.as_deref(),
                Some(resolved_session),
                Some(error_code::CONNECT_FAILED),
                None,
                &trace,
            )
            .await;
        }
        ExecError::Config { message, hint } => {
            let trace = Trace::only_duration(start.elapsed().as_millis() as u64);
            let _ = app
                .writer
                .send(Output::Error {
                    id: id.clone(),
                    error_code: error_code::INVALID_REQUEST.to_string(),
                    error: message,
                    sqlstate: None,
                    message: None,
                    detail: None,
                    hint,
                    retryable: false,
                    trace: trace.clone(),
                })
                .await;
            emit_log(
                app,
                log_event::QUERY_ERROR,
                id.as_deref(),
                Some(resolved_session),
                Some(error_code::INVALID_REQUEST),
                None,
                &trace,
            )
            .await;
        }
        ExecError::InvalidParams(message) => {
            let trace = Trace::only_duration(start.elapsed().as_millis() as u64);
            let _ = app
                .writer
                .send(Output::Error {
                    id: id.clone(),
                    error_code: error_code::INVALID_PARAMS.to_string(),
                    error: message,
                    sqlstate: None,
                    message: None,
                    detail: None,
                    hint: Some(
                        "check that `params` count and types match the $1, $2, ... placeholders in `sql`"
                            .to_string(),
                    ),
                    retryable: false,
                    trace: trace.clone(),
                })
                .await;
            emit_log(
                app,
                log_event::QUERY_ERROR,
                id.as_deref(),
                Some(resolved_session),
                Some(error_code::INVALID_PARAMS),
                None,
                &trace,
            )
            .await;
        }
        ExecError::ResultTooLarge {
            row_count,
            payload_bytes,
        } => {
            let trace = Trace {
                duration_ms: start.elapsed().as_millis() as u64,
                row_count: Some(row_count),
                payload_bytes: Some(payload_bytes),
            };
            let _ = app
                .writer
                .send(Output::Error {
                    id: id.clone(),
                    error_code: error_code::RESULT_TOO_LARGE.to_string(),
                    error: "result exceeds inline limits".to_string(),
                    sqlstate: None,
                    message: None,
                    detail: None,
                    hint: Some(result_too_large_hint()),
                    retryable: false,
                    trace: trace.clone(),
                })
                .await;
            emit_log(
                app,
                log_event::QUERY_ERROR,
                id.as_deref(),
                Some(resolved_session),
                Some(error_code::RESULT_TOO_LARGE),
                None,
                &trace,
            )
            .await;
        }
        ExecError::Sql {
            sqlstate,
            message,
            detail,
            hint,
            position,
        } => {
            let trace = Trace::only_duration(start.elapsed().as_millis() as u64);
            let _ = app
                .writer
                .send(Output::SqlError {
                    id: id.clone(),
                    session: Some(resolved_session.to_string()),
                    sqlstate: sqlstate.clone(),
                    message,
                    detail,
                    hint,
                    position,
                    trace: trace.clone(),
                })
                .await;
            emit_log(
                app,
                log_event::QUERY_SQL_ERROR,
                id.as_deref(),
                Some(resolved_session),
                Some(&sqlstate),
                None,
                &trace,
            )
            .await;
        }
        ExecError::Internal(message) => {
            let trace = Trace::only_duration(start.elapsed().as_millis() as u64);
            let _ = app
                .writer
                .send(Output::Error {
                    id: id.clone(),
                    error_code: error_code::INVALID_REQUEST.to_string(),
                    error: message,
                    sqlstate: None,
                    message: None,
                    detail: None,
                    hint: Some(
                        "afpsql hit an internal error; retry the query, then restart the session if it persists"
                            .to_string(),
                    ),
                    retryable: false,
                    trace: trace.clone(),
                })
                .await;
            emit_log(
                app,
                log_event::QUERY_ERROR,
                id.as_deref(),
                Some(resolved_session),
                Some(error_code::INVALID_REQUEST),
                None,
                &trace,
            )
            .await;
        }
    }
}

struct OutputRowSink {
    app: Arc<App>,
    id: String,
    session: Option<String>,
    batch: Vec<Value>,
    batch_bytes: usize,
    batch_rows_limit: usize,
    batch_bytes_limit: usize,
}

impl OutputRowSink {
    fn new(
        app: Arc<App>,
        id: String,
        session: Option<String>,
        batch_rows_limit: usize,
        batch_bytes_limit: usize,
    ) -> Self {
        Self {
            app,
            id,
            session,
            batch: vec![],
            batch_bytes: 0,
            batch_rows_limit,
            batch_bytes_limit,
        }
    }

    async fn flush_batch(&mut self) -> Result<(), ExecError> {
        if self.batch.is_empty() {
            return Ok(());
        }
        let n = self.batch.len();
        let rows = std::mem::take(&mut self.batch);
        self.batch_bytes = 0;
        self.app
            .writer
            .send(Output::ResultRows {
                id: self.id.clone(),
                rows,
                rows_batch_count: n,
            })
            .await
            .map_err(|_| ExecError::Internal("output channel closed".to_string()))
    }
}

#[async_trait::async_trait]
impl RowSink for OutputRowSink {
    async fn start(&mut self, columns: Vec<ColumnInfo>) -> Result<(), ExecError> {
        self.app
            .writer
            .send(Output::ResultStart {
                id: self.id.clone(),
                session: self.session.clone(),
                columns,
            })
            .await
            .map_err(|_| ExecError::Internal("output channel closed".to_string()))
    }

    async fn row(&mut self, row: Value, row_bytes: usize) -> Result<(), ExecError> {
        self.batch_bytes += row_bytes;
        self.batch.push(row);
        if self.batch.len() >= self.batch_rows_limit || self.batch_bytes >= self.batch_bytes_limit {
            self.flush_batch().await?;
        }
        Ok(())
    }
}

#[derive(Clone)]
enum RowEmitStatus {
    Sent { trace: Trace },
}

/// Carry the inline-truncation flags from the executor's row collector into
/// `emit_rows_result` without ballooning the function's argument list.
#[derive(Clone, Copy, Default)]
pub(crate) struct InlineTruncation {
    pub truncated: bool,
    pub at_rows: Option<usize>,
    pub at_bytes: Option<usize>,
}

#[allow(clippy::too_many_arguments)]
async fn emit_rows_result(
    app: &Arc<App>,
    id: Option<String>,
    session: Option<String>,
    columns: Vec<ColumnInfo>,
    rows: Vec<Value>,
    truncation: InlineTruncation,
    start: Instant,
    opts: &ResolvedOptions,
) -> RowEmitStatus {
    if opts.stream_rows {
        let req_id = id.clone().unwrap_or_else(|| "cli".to_string());
        let _ = app
            .writer
            .send(Output::ResultStart {
                id: req_id.clone(),
                session: session.clone(),
                columns: columns.clone(),
            })
            .await;

        let mut batch: Vec<Value> = vec![];
        let mut batch_bytes = 0usize;
        let mut total_bytes = 0usize;
        let mut row_count = 0usize;

        for row in rows {
            let sz = serde_json::to_vec(&row).map(|b| b.len()).unwrap_or(0);
            batch_bytes += sz;
            total_bytes += sz;
            row_count += 1;
            batch.push(row);

            if batch.len() >= opts.batch_rows || batch_bytes >= opts.batch_bytes {
                let n = batch.len();
                let _ = app
                    .writer
                    .send(Output::ResultRows {
                        id: req_id.clone(),
                        rows: std::mem::take(&mut batch),
                        rows_batch_count: n,
                    })
                    .await;
                batch_bytes = 0;
            }
        }

        for tail in std::iter::once(batch).filter(|r| !r.is_empty()) {
            let n = tail.len();
            let _ = app
                .writer
                .send(Output::ResultRows {
                    id: req_id.clone(),
                    rows: tail,
                    rows_batch_count: n,
                })
                .await;
        }

        let trace = Trace {
            duration_ms: start.elapsed().as_millis() as u64,
            row_count: Some(row_count),
            payload_bytes: Some(total_bytes),
        };
        let _ = app
            .writer
            .send(Output::ResultEnd {
                id: req_id,
                session,
                command_tag: command_tag::rows(row_count),
                trace: trace.clone(),
            })
            .await;

        return RowEmitStatus::Sent { trace };
    }

    let mut payload_bytes = 0usize;
    for row in &rows {
        payload_bytes += serde_json::to_vec(row).map(|b| b.len()).unwrap_or(0);
    }

    let row_count = rows.len();
    let trace = Trace {
        duration_ms: start.elapsed().as_millis() as u64,
        row_count: Some(row_count),
        payload_bytes: Some(payload_bytes),
    };
    let _ = app
        .writer
        .send(Output::Result {
            id,
            session,
            command_tag: command_tag::rows(row_count),
            columns,
            rows,
            row_count,
            truncated: truncation.truncated,
            truncated_at_rows: truncation.at_rows,
            truncated_at_bytes: truncation.at_bytes,
            trace: trace.clone(),
        })
        .await;

    RowEmitStatus::Sent { trace }
}

fn result_too_large_hint() -> String {
    "retry with stream_rows=true, or increase --inline-max-rows/--inline-max-bytes".to_string()
}

async fn emit_log(
    app: &Arc<App>,
    event: &str,
    request_id: Option<&str>,
    session: Option<&str>,
    error_code: Option<&str>,
    command_tag: Option<&str>,
    trace: &Trace,
) {
    let enabled = {
        let cfg = app.config.read().await;
        cfg.log.enabled(event)
    };
    if !enabled {
        return;
    }

    let _ = app
        .writer
        .send(Output::Log {
            event: event.to_string(),
            request_id: request_id.map(std::string::ToString::to_string),
            session: session.map(std::string::ToString::to_string),
            error_code: error_code.map(std::string::ToString::to_string),
            command_tag: command_tag.map(std::string::ToString::to_string),
            version: None,
            config: None,
            args: None,
            env: None,
            chain: None,
            trace: trace.clone(),
        })
        .await;
}

#[cfg(test)]
#[path = "../tests/support/unit_handler.rs"]
mod tests;