Repository navigation
Expand file tree
/
Copy pathAgentRunStore.java
More file actions
1648 lines (1554 loc) · 66.9 KB
/
Copy pathAgentRunStore.java
File metadata and controls
1648 lines (1554 loc) · 66.9 KB
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
/*******************************************************************************
* Copyright 2015 Defense Health Agency (DHA)
*
* If your use of this software does not include any GPLv2 components:
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ----------------------------------------------------------------------------
* If your use of this software includes any GPLv2 components:
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*******************************************************************************/
package prerna.reactor.agent.run;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.javatuples.Pair;
import com.google.gson.Gson;
import prerna.auth.AccessToken;
import prerna.auth.User;
import prerna.engine.api.IRDBMSEngine;
import prerna.om.Insight;
import prerna.query.querystruct.SelectQueryStruct;
import prerna.query.querystruct.filters.SimpleQueryFilter;
import prerna.query.querystruct.selectors.QueryColumnSelector;
import prerna.reactor.agent.AgentRunContext;
import prerna.util.ConnectionUtils;
import prerna.util.QueryExecutionUtility;
import prerna.util.SystemEngineRegistry;
import prerna.util.Utility;
import prerna.util.ValueUtils;
/**
* All SQL against the {@code AGENT_RUN} table: inserts, status transitions,
* queue queries, and the user-facing reads.
*
* <p>
* The table is the durable record of a run, so some of the concurrency rules
* are expressed here as SQL rather than as Java.
* {@link #markRunningIfSubmitted} is the conditional update that decides which
* node gets to execute a run, and {@link #isOldestSubmittedRunForRoom} is the
* per-room FIFO order the worker honors before claiming anything.
*
* <p>
* Reads made on a user's behalf are scoped by {@code USER_ID} so one user
* cannot read another's runs. The two queue queries the worker uses are
* deliberately unscoped, because the worker serves every user on the node and
* has no caller identity of its own. So are the {@code ...ForAutomation} reads,
* made once Automation has authorized the trace, and the {@code ...ForAdmin}
* reads behind the admin Agent Runs page, made once the reactor has checked the
* caller is an admin, or by a user closing their own room, which keeps only
* their own runs.
*/
public final class AgentRunStore {
private static final Gson GSON = new Gson();
private static final String ACTIVITY_LOG_COLUMNS = "ar.RUN_ID, ar.PARENT_RUN_ID, ar.ROOM_ID, ar.WORKSPACE_ID, ar.MODEL_ID, "
+ "ar.HARNESS_TYPE, ar.JOB_ID, ar.STATUS, ar.INPUT, ar.INPUT_MESSAGE_ID, ar.FINAL_OUTPUT, ar.FINAL_OUTPUT_MESSAGE_ID, "
+ "ar.ERROR_MESSAGE, ar.PROGRESS_JSON, ar.DATE_CREATED, ar.STARTED_AT, ar.COMPLETED_AT, ar.USER_ID, ar.USER_TYPE, "
+ "r.ROOM_NAME, r.IS_ACTIVE AS ROOM_IS_ACTIVE";
// Rooms are keyed per user, so the name join must match on both columns.
private static final String ACTIVITY_LOG_FROM = "FROM AGENT_RUN ar "
+ "LEFT JOIN ROOM r ON ar.ROOM_ID = r.ROOM_ID AND ar.USER_ID = r.USER_ID";
/** The statuses of a run that has not finished */
private static final List<AgentRunStatus> ACTIVE_STATUSES = List.of(AgentRunStatus.SUBMITTED,
AgentRunStatus.RUNNING, AgentRunStatus.INPUT_REQUIRED);
/**
* When a group of runs was last active: the latest time any of them ended,
* started or was made
*/
private static final String LAST_ACTIVITY_COLUMN = "MAX(COALESCE(ar.COMPLETED_AT, ar.STARTED_AT, ar.DATE_CREATED)) "
+ "AS LAST_ACTIVITY_AT";
/**
* The runs that put a room on the admin Agent Runs page: in a room, and not a
* subagent run
*/
private static final String ROOM_ROOT_RUN_CONDITION = "ar.ROOM_ID IS NOT NULL AND ar.PARENT_RUN_ID IS NULL";
/**
* One row per room and user for a list of rooms with agent runs: its agent, its
* user's login type, how many runs it holds, how many are still going or
* failed, whether the room is closed, and when it started and was last active.
* The login type is the one any of its runs stores, since a run can have none.
* The two counts take the active statuses, then FAILED; the room is closed when
* its IS_ACTIVE is the false that follows them.
*/
private static final String ROOM_LIST_COLUMNS = "ar.ROOM_ID, ar.USER_ID, MAX(ar.USER_TYPE) AS USER_TYPE, "
+ "MAX(ar.WORKSPACE_ID) AS AGENT_ID, " + "MAX(r.ROOM_NAME) AS ROOM_NAME, COUNT(*) AS RUN_COUNT, "
+ "SUM(CASE WHEN ar.STATUS IN (?, ?, ?) THEN 1 ELSE 0 END) AS ACTIVE_RUN_COUNT, "
+ "SUM(CASE WHEN ar.STATUS = ? THEN 1 ELSE 0 END) AS FAILED_RUN_COUNT, "
+ "MAX(CASE WHEN r.IS_ACTIVE = ? THEN 1 ELSE 0 END) AS ROOM_CLOSED, "
+ "MIN(ar.DATE_CREATED) AS FIRST_RUN_AT, " + LAST_ACTIVITY_COLUMN;
/**
* Which rooms a list of rooms with agent runs holds: the admin Agent Runs page,
* or an agent's Activity tab, for its user's own.
*
* @param agentId rooms holding a run of this agent, or null for every
* agent
* @param userId rooms of this user, or null for every user
* @param userType the login type of {@code userId}, or null to match the
* id under any type
* @param search rooms whose name or id contains this text, in any case,
* or null for every room
* @param statuses rooms holding a run in one of these statuses, or empty
* for any status
* @param subagentRooms whether a room holding only subagent runs is listed, as
* an agent's Activity tab lists the rooms it ran in as
* another's subagent; the admin page shows those nested in
* their parent's room instead
*/
public record RoomFilter(String agentId, String userId, String userType, String search,
Set<AgentRunStatus> statuses, boolean subagentRooms) {
/**
* A filter that leaves out rooms holding only subagent runs.
*
* @param agentId rooms holding a run of this agent, or null for every agent
* @param userId rooms of this user, or null for every user
* @param userType the login type of {@code userId}, or null to match the id
* under any type
* @param search rooms whose name or id contains this text, or null
* @param statuses rooms holding a run in one of these statuses, or empty
*/
public RoomFilter(String agentId, String userId, String userType, String search, Set<AgentRunStatus> statuses) {
this(agentId, userId, userType, search, statuses, false);
}
}
private AgentRunStore() {
}
/**
* Records a run waiting for a worker to pick it up.
*
* @param runId durable id of the run
* @param request the submission the run is created from
* @param userId owner of the run
* @param userType login type of the owner's {@code userId}
*/
public static void insertSubmitted(String runId, AgentRunRequest request, String userId, String userType) {
insert(runId, request, userId, userType, AgentRunStatus.SUBMITTED);
}
// Human children start waiting; no worker ever picks them up.
static void insertInputRequired(String runId, AgentRunRequest request, String userId, String userType) {
insert(runId, request, userId, userType, AgentRunStatus.INPUT_REQUIRED);
}
private static void insert(String runId, AgentRunRequest request, String userId, String userType,
AgentRunStatus status) {
IRDBMSEngine db = SystemEngineRegistry.getModelInferenceLogsDb();
PreparedStatement ps = null;
try {
String query = "INSERT INTO AGENT_RUN (RUN_ID, PARENT_RUN_ID, ROOM_ID, WORKSPACE_ID, MODEL_ID, HARNESS_TYPE, JOB_ID, "
+ "STATUS, INPUT, REQUEST_JSON, INPUT_MESSAGE_ID, FINAL_OUTPUT, FINAL_OUTPUT_MESSAGE_ID, ERROR_MESSAGE, "
+ "DATE_CREATED, STARTED_AT, COMPLETED_AT, USER_ID, USER_TYPE) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
ps = db.getPreparedStatement(query);
int idx = 1;
ps.setString(idx++, runId);
setNullableString(ps, idx++, request.getParentRunId());
setNullableString(ps, idx++, request.getRoomId());
setNullableString(ps, idx++, request.getWorkspaceId());
setNullableString(ps, idx++, request.getEngineIdFallback());
setNullableString(ps, idx++, request.getHarnessType());
ps.setString(idx++, runId);
ps.setString(idx++, status.name());
setClob(db, ps, idx++, request.getInput());
setClob(db, ps, idx++, GSON.toJson(request.toPersistedMap()));
ps.setNull(idx++, Types.VARCHAR);
ps.setNull(idx++, Types.CLOB);
ps.setNull(idx++, Types.VARCHAR);
ps.setNull(idx++, Types.CLOB);
ps.setTimestamp(idx++, Utility.getCurrentSqlTimestampUTC());
ps.setNull(idx++, Types.TIMESTAMP);
ps.setNull(idx++, Types.TIMESTAMP);
setNullableString(ps, idx++, userId);
setNullableString(ps, idx++, userType);
ps.executeUpdate();
commitIfNeeded(ps);
} catch (Exception e) {
throw new IllegalStateException("Failed to create AGENT_RUN row for runId=" + runId, e);
} finally {
ConnectionUtils.closeAllConnectionsIfPooling(db, null, ps, null);
}
}
public static AgentRunRecord getRun(String runId, Insight insight) {
IRDBMSEngine db = SystemEngineRegistry.getModelInferenceLogsDb();
PreparedStatement ps = null;
ResultSet rs = null;
try {
String userId = resolveInsightUserId(insight);
String query = "SELECT RUN_ID, PARENT_RUN_ID, ROOM_ID, WORKSPACE_ID, MODEL_ID, HARNESS_TYPE, STATUS, INPUT, REQUEST_JSON, "
+ "USER_ID, USER_TYPE, JOB_ID FROM AGENT_RUN WHERE RUN_ID = ? AND USER_ID = ?";
ps = db.getPreparedStatement(query);
ps.setString(1, runId);
ps.setString(2, userId);
rs = ps.executeQuery();
if (!rs.next()) {
return null;
}
AgentRunRequest request = requestFromRow(rs, insight);
return new AgentRunRecord(rs.getString("RUN_ID"), rs.getString("ROOM_ID"),
parseRunStatus(rs.getString("STATUS")), request, rs.getString("USER_ID"), rs.getString("USER_TYPE"),
rs.getString("JOB_ID"));
} catch (Exception e) {
if (e instanceof SecurityException) {
throw (SecurityException) e;
}
throw new IllegalStateException("Failed to load AGENT_RUN row for runId=" + runId, e);
} finally {
ConnectionUtils.closeAllConnectionsIfPooling(db, null, ps, rs);
}
}
/**
* Loads an agent run without applying the owning-user predicate.
*
* <p>
* This method is reserved for Automation APIs that have already verified
* project access and the exact persisted Automation run, node, and agent-run
* trace. Generic agent APIs must use {@link #getRun(String, Insight)}.
*
* @param runId agent run identifier
* @param insight current Automation editor insight used to reconstruct the
* request
* @return matching run, or {@code null} when it does not exist
*/
public static AgentRunRecord getRunForAutomation(String runId, Insight insight) {
IRDBMSEngine db = SystemEngineRegistry.getModelInferenceLogsDb();
try {
SelectQueryStruct qs = new SelectQueryStruct();
qs.addSelector(new QueryColumnSelector("AGENT_RUN__RUN_ID", "runId"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__PARENT_RUN_ID", "parentRunId"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__ROOM_ID", "roomId"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__WORKSPACE_ID", "workspaceId"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__MODEL_ID", "modelId"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__HARNESS_TYPE", "harnessType"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__STATUS", "status"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__INPUT", "input"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__REQUEST_JSON", "requestJson"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__USER_ID", "userId"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__USER_TYPE", "userType"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__JOB_ID", "jobId"));
qs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter("AGENT_RUN__RUN_ID", "==", runId));
List<Map<String, Object>> rows = QueryExecutionUtility.flushRsToMap(db, qs);
if (rows.isEmpty()) {
return null;
}
Map<String, Object> row = rows.get(0);
AgentRunRequest request = requestFromMap(row, insight);
return new AgentRunRecord(ValueUtils.toStringOrNull(row.get("runId")),
ValueUtils.toStringOrNull(row.get("roomId")),
parseRunStatus(ValueUtils.toStringOrNull(row.get("status"))), request,
ValueUtils.toStringOrNull(row.get("userId")), ValueUtils.toStringOrNull(row.get("userType")),
ValueUtils.toStringOrNull(row.get("jobId")));
} catch (Exception e) {
throw new IllegalStateException("Failed to load Automation AGENT_RUN row for runId=" + runId, e);
}
}
public static Map<String, Object> getRunMap(String runId, Insight insight) {
IRDBMSEngine db = SystemEngineRegistry.getModelInferenceLogsDb();
PreparedStatement ps = null;
ResultSet rs = null;
try {
String userId = resolveInsightUserId(insight);
String query = "SELECT " + ACTIVITY_LOG_COLUMNS + ", ar.REQUEST_JSON " + ACTIVITY_LOG_FROM
+ " WHERE ar.RUN_ID = ? AND ar.USER_ID = ?";
ps = db.getPreparedStatement(query);
ps.setString(1, runId);
ps.setString(2, userId);
rs = ps.executeQuery();
if (!rs.next()) {
return null;
}
return runMapFromRow(rs);
} catch (Exception e) {
if (e instanceof SecurityException) {
throw (SecurityException) e;
}
throw new IllegalStateException("Failed to load AGENT_RUN details for runId=" + runId, e);
} finally {
ConnectionUtils.closeAllConnectionsIfPooling(db, null, ps, rs);
}
}
/**
* Loads agent-run details without applying the owning-user predicate.
*
* <p>
* This is the detail-map equivalent of
* {@link #getRunForAutomation(String, Insight)} and is only valid after
* Automation trace authorization succeeds.
*
* @param runId agent run identifier
* @return matching run details, or {@code null} when it does not exist
*/
public static Map<String, Object> getRunMapForAutomation(String runId) {
IRDBMSEngine db = SystemEngineRegistry.getModelInferenceLogsDb();
try {
SelectQueryStruct qs = new SelectQueryStruct();
qs.addSelector(new QueryColumnSelector("AGENT_RUN__RUN_ID", "runId"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__PARENT_RUN_ID", "parentRunId"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__ROOM_ID", "roomId"));
qs.addSelector(new QueryColumnSelector("ROOM__ROOM_NAME", "roomName"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__WORKSPACE_ID", "workspaceId"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__MODEL_ID", "modelId"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__HARNESS_TYPE", "harnessType"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__JOB_ID", "jobId"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__STATUS", "status"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__INPUT", "input"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__INPUT_MESSAGE_ID", "inputMessageId"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__FINAL_OUTPUT", "finalText"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__FINAL_OUTPUT_MESSAGE_ID", "finalOutputMessageId"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__ERROR_MESSAGE", "errorMessage"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__DATE_CREATED", "dateCreated"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__STARTED_AT", "startedAt"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__COMPLETED_AT", "completedAt"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__USER_ID", "userId"));
qs.addSelector(new QueryColumnSelector("AGENT_RUN__USER_TYPE", "userType"));
qs.addRelation("AGENT_RUN__ROOM_ID", "ROOM__ROOM_ID", "left.outer.join");
qs.addRelation("AGENT_RUN__USER_ID", "ROOM__USER_ID", "left.outer.join");
qs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter("AGENT_RUN__RUN_ID", "==", runId));
List<Map<String, Object>> rows = QueryExecutionUtility.flushRsToMap(db, qs);
if (rows.isEmpty()) {
return null;
}
Map<String, Object> run = rows.get(0);
run.put("dateCreated", ValueUtils.toStringOrNull(run.get("dateCreated")));
run.put("startedAt", ValueUtils.toStringOrNull(run.get("startedAt")));
run.put("completedAt", ValueUtils.toStringOrNull(run.get("completedAt")));
run.put("artifacts", new ArrayList<>());
return run;
} catch (Exception e) {
throw new IllegalStateException("Failed to load Automation AGENT_RUN details for runId=" + runId, e);
}
}
/**
* Return one page of runs for an agent owned by the current user, newest first.
*
* @param insight current request insight, used to scope the query to its user
* @param agentId agent workspace identifier used to scope the runs
* @param limit maximum number of runs to return
* @param offset number of matching runs to skip
* @return the requested page of agent runs
*/
public static List<Map<String, Object>> getActivityLog(Insight insight, String agentId, long limit, long offset) {
if (agentId == null || agentId.trim().isEmpty()) {
throw new IllegalArgumentException("agentId is required");
}
if (limit <= 0) {
throw new IllegalArgumentException("limit must be greater than 0");
}
if (offset < 0) {
throw new IllegalArgumentException("offset must be greater than or equal to 0");
}
String userId = resolveInsightUserId(insight);
IRDBMSEngine db = SystemEngineRegistry.getModelInferenceLogsDb();
PreparedStatement ps = null;
ResultSet rs = null;
try {
StringBuilder query = new StringBuilder("SELECT " + ACTIVITY_LOG_COLUMNS + " " + ACTIVITY_LOG_FROM
+ " WHERE ar.USER_ID = ? AND ar.WORKSPACE_ID = ? ORDER BY ar.DATE_CREATED DESC, ar.RUN_ID DESC");
db.getQueryUtil().addLimitOffsetToQuery(query, limit, offset);
ps = db.getPreparedStatement(query.toString());
ps.setString(1, userId);
ps.setString(2, agentId.trim());
rs = ps.executeQuery();
List<Map<String, Object>> runs = new ArrayList<>();
while (rs.next()) {
runs.add(runMapFromRow(rs));
}
return runs;
} catch (Exception e) {
if (e instanceof SecurityException) {
throw (SecurityException) e;
}
throw new IllegalStateException("Failed to load AGENT_RUN activity log", e);
} finally {
ConnectionUtils.closeAllConnectionsIfPooling(db, null, ps, rs);
}
}
/**
* Return every run in a room owned by the current user, newest first.
*
* @param insight current request insight, used to scope the query to its user
* @param roomId room whose complete run history should be returned
* @return all current-user runs for the room
*/
public static List<Map<String, Object>> getRunsForRoom(Insight insight, String roomId) {
if (roomId == null || roomId.trim().isEmpty()) {
throw new IllegalArgumentException("roomId is required");
}
String userId = resolveInsightUserId(insight);
IRDBMSEngine db = SystemEngineRegistry.getModelInferenceLogsDb();
PreparedStatement ps = null;
ResultSet rs = null;
try {
String query = "SELECT " + ACTIVITY_LOG_COLUMNS + " " + ACTIVITY_LOG_FROM
+ " WHERE ar.USER_ID = ? AND ar.ROOM_ID = ? ORDER BY ar.DATE_CREATED DESC, ar.RUN_ID DESC";
ps = db.getPreparedStatement(query);
ps.setString(1, userId);
ps.setString(2, roomId.trim());
rs = ps.executeQuery();
List<Map<String, Object>> runs = new ArrayList<>();
while (rs.next()) {
runs.add(runMapFromRow(rs));
}
return runs;
} catch (Exception e) {
throw new IllegalStateException("Failed to load AGENT_RUN rows for roomId=" + roomId, e);
} finally {
ConnectionUtils.closeAllConnectionsIfPooling(db, null, ps, rs);
}
}
/**
* Return every direct subagent run for a parent run owned by the current user,
* newest first.
*
* @param insight current request insight, used to scope the query to its
* user
* @param parentRunId parent run whose direct subagent runs should be returned
* @return all current-user runs with the supplied parent run ID
*/
public static List<Map<String, Object>> getSubagentRuns(Insight insight, String parentRunId) {
if (parentRunId == null || parentRunId.trim().isEmpty()) {
throw new IllegalArgumentException("runId is required");
}
return querySubagentRuns(parentRunId.trim(), resolveInsightUserId(insight));
}
/**
* Return the direct subagent runs of any user's run, newest first, for the
* admin Agent Runs page.
*
* @param access proof that the caller is an admin
* @param parentRunId parent run whose direct subagent runs should be returned
* @return every run with the supplied parent run ID
* @throws SecurityException when {@code access} is missing
*/
public static List<Map<String, Object>> getSubagentRunsForAdmin(AdminAccess access, String parentRunId) {
AdminAccess.require(access);
return getSubagentRunsOfAnyUser(parentRunId);
}
/**
* Return the direct subagent runs of any user's run, newest first, for closing
* a room, which keeps only the runs of the room's user.
*
* @param parentRunId parent run whose direct subagent runs should be returned
* @return every run with the supplied parent run ID
*/
static List<Map<String, Object>> getSubagentRunsOfAnyUser(String parentRunId) {
if (parentRunId == null || parentRunId.trim().isEmpty()) {
throw new IllegalArgumentException("runId is required");
}
return querySubagentRuns(parentRunId.trim(), null);
}
/**
* Reads the direct subagent runs of a run, each marked with whether a person or
* an agent ran it.
*
* @param parentRunId parent run whose direct subagent runs are read
* @param userId the user whose runs are read, or null for every user's
* @return the subagent runs, newest first
*/
private static List<Map<String, Object>> querySubagentRuns(String parentRunId, String userId) {
IRDBMSEngine db = SystemEngineRegistry.getModelInferenceLogsDb();
PreparedStatement ps = null;
ResultSet rs = null;
try {
String query = "SELECT " + ACTIVITY_LOG_COLUMNS + ", ar.REQUEST_JSON " + ACTIVITY_LOG_FROM
+ " WHERE ar.PARENT_RUN_ID = ?" + (userId == null ? "" : " AND ar.USER_ID = ?")
+ " ORDER BY ar.DATE_CREATED DESC, ar.RUN_ID DESC";
ps = db.getPreparedStatement(query);
ps.setString(1, parentRunId);
if (userId != null) {
ps.setString(2, userId);
}
rs = ps.executeQuery();
List<Map<String, Object>> runs = new ArrayList<>();
while (rs.next()) {
Map<String, Object> run = runMapFromRow(rs);
// Lets child cards tell a person's task from an agent's.
AgentRunRequest request = requestFromJson(rs.getString("REQUEST_JSON"));
boolean human = request != null && request.isHumanExecutor();
run.put("executorType", human ? "HUMAN" : "AGENT");
run.put("executorLabel", human ? request.getHumanExecutorLabel() : null);
runs.add(run);
}
return runs;
} catch (Exception e) {
throw new IllegalStateException("Failed to load subagent AGENT_RUN rows for parentRunId=" + parentRunId, e);
} finally {
ConnectionUtils.closeAllConnectionsIfPooling(db, null, ps, rs);
}
}
// ------------------------------------------------------------------------
// rooms and their runs: the caller's own, matched by the id and login type of
// their primary login, and any user's, for the admin Agent Runs page, which
// take an AdminAccess so none of them runs without the admin check
// ------------------------------------------------------------------------
/**
* Return one page of the caller's own rooms with an agent, most recently active
* first, for the agent's Activity tab, rooms where it ran only as another
* agent's subagent included.
*
* @param insight the caller's insight
* @param agentId the agent
* @param search rooms whose name or id contains this text, or null
* @param statuses rooms holding a run in one of these statuses, or empty
* @param limit maximum number of rooms to return
* @param offset number of matching rooms to skip
* @return each room's id, run counts, whether it is closed, and first and last
* activity
* @throws SecurityException when the caller is not signed in
*/
public static List<Map<String, Object>> getRoomsForAgent(Insight insight, String agentId, String search,
Set<AgentRunStatus> statuses, long limit, long offset) {
return queryRooms(callerRoomFilter(insight, agentId, search, statuses), limit, offset);
}
/**
* Count the rooms {@link #getRoomsForAgent} lists.
*
* @param insight the caller's insight
* @param agentId the agent
* @param search rooms whose name or id contains this text, or null
* @param statuses rooms holding a run in one of these statuses, or empty
* @return how many rooms match, across every page
* @throws SecurityException when the caller is not signed in
*/
public static long countRoomsForAgent(Insight insight, String agentId, String search,
Set<AgentRunStatus> statuses) {
return queryRoomCount(callerRoomFilter(insight, agentId, search, statuses));
}
/**
* Return one page of any user's rooms with agent runs, most recently active
* first, for the admin Agent Runs page.
*
* @param access proof that the caller is an admin
* @param filter which rooms to list
* @param limit maximum number of rooms to return
* @param offset number of matching rooms to skip
* @return each room's id, user, agent, run counts, whether it is closed, and
* first and last activity
* @throws SecurityException when {@code access} is missing
*/
public static List<Map<String, Object>> getRoomsForAdmin(AdminAccess access, RoomFilter filter, long limit,
long offset) {
AdminAccess.require(access);
return queryRooms(filter, limit, offset);
}
/**
* Count the rooms {@link #getRoomsForAdmin} lists.
*
* @param access proof that the caller is an admin
* @param filter which rooms to count
* @return how many rooms match, across every page
* @throws SecurityException when {@code access} is missing
*/
public static long countRoomsForAdmin(AdminAccess access, RoomFilter filter) {
AdminAccess.require(access);
return queryRoomCount(filter);
}
/**
* The filter for the caller's own rooms with an agent.
*
* @param insight the caller's insight
* @param agentId the agent
* @param search rooms whose name or id contains this text, or null
* @param statuses rooms holding a run in one of these statuses, or empty
* @return the filter, by the id and login type of the caller's primary login
*/
private static RoomFilter callerRoomFilter(Insight insight, String agentId, String search,
Set<AgentRunStatus> statuses) {
AccessToken login = resolveInsightLogin(insight);
return new RoomFilter(agentId, login.getId(), login.getProvider().getLabel(), search, statuses, true);
}
/**
* Read one page of rooms with agent runs, most recently active first. A room is
* listed once per user, and, unless the filter asks for subagent rooms, only
* when it holds a run that is not a subagent run: a subagent's own room shows
* nested in its parent's room.
*
* @param filter which rooms to list
* @param limit maximum number of rooms to return
* @param offset number of matching rooms to skip
* @return each room's id, user, agent, run counts, whether it is closed, and
* first and last activity
*/
private static List<Map<String, Object>> queryRooms(RoomFilter filter, long limit, long offset) {
IRDBMSEngine db = SystemEngineRegistry.getModelInferenceLogsDb();
PreparedStatement ps = null;
ResultSet rs = null;
try {
List<Object> params = new ArrayList<>();
StringBuilder query = new StringBuilder(roomsQuery(filter, params))
.append(" ORDER BY LAST_ACTIVITY_AT DESC, ar.ROOM_ID, ar.USER_ID");
db.getQueryUtil().addLimitOffsetToQuery(query, limit, offset);
ps = db.getPreparedStatement(query.toString());
for (int i = 0; i < params.size(); i++) {
ps.setObject(i + 1, params.get(i));
}
rs = ps.executeQuery();
List<Map<String, Object>> rooms = new ArrayList<>();
while (rs.next()) {
Map<String, Object> room = new HashMap<>();
room.put("roomId", rs.getString("ROOM_ID"));
room.put("userId", rs.getString("USER_ID"));
room.put("userType", rs.getString("USER_TYPE"));
room.put("agentId", rs.getString("AGENT_ID"));
room.put("roomName", rs.getString("ROOM_NAME"));
room.put("runCount", rs.getLong("RUN_COUNT"));
room.put("activeRunCount", rs.getLong("ACTIVE_RUN_COUNT"));
room.put("failedRunCount", rs.getLong("FAILED_RUN_COUNT"));
room.put("isClosed", rs.getInt("ROOM_CLOSED") > 0);
room.put("firstRunAt", ValueUtils.toStringOrNull(rs.getTimestamp("FIRST_RUN_AT")));
room.put("lastActivityAt", ValueUtils.toStringOrNull(rs.getTimestamp("LAST_ACTIVITY_AT")));
rooms.add(room);
}
return rooms;
} catch (Exception e) {
throw new IllegalStateException("Failed to load the rooms with AGENT_RUN rows", e);
} finally {
ConnectionUtils.closeAllConnectionsIfPooling(db, null, ps, rs);
}
}
/**
* Count the rooms {@link #queryRooms} reads.
*
* @param filter which rooms to count
* @return how many rooms match, across every page
*/
private static long queryRoomCount(RoomFilter filter) {
IRDBMSEngine db = SystemEngineRegistry.getModelInferenceLogsDb();
PreparedStatement ps = null;
ResultSet rs = null;
try {
List<Object> params = new ArrayList<>();
ps = db.getPreparedStatement("SELECT COUNT(*) FROM (" + roomsQuery(filter, params) + ") rooms");
for (int i = 0; i < params.size(); i++) {
ps.setObject(i + 1, params.get(i));
}
rs = ps.executeQuery();
return rs.next() ? rs.getLong(1) : 0L;
} catch (Exception e) {
throw new IllegalStateException("Failed to count the rooms with AGENT_RUN rows", e);
} finally {
ConnectionUtils.closeAllConnectionsIfPooling(db, null, ps, rs);
}
}
/**
* Return every run the caller has in one of their rooms, newest first, subagent
* runs included: the run list the agent's Activity tab opens.
*
* @param insight the caller's insight
* @param roomId the caller's room
* @return the caller's runs in the room
* @throws SecurityException when the caller is not signed in
*/
public static List<Map<String, Object>> getRunsForRoomByLogin(Insight insight, String roomId) {
AccessToken login = resolveInsightLogin(insight);
return getUserRunsForRoom(roomId, login.getId(), login.getProvider().getLabel());
}
/**
* Return every run any user has in a room, newest first, for the admin Agent
* Runs page: the run list the room's owner sees on the agent's Activity tab.
*
* @param access proof that the caller is an admin
* @param roomId room whose runs are returned
* @param userId the user the room belongs to
* @param userType the login type of {@code userId}, or null to match the id
* under any type
* @return the user's runs in the room
* @throws SecurityException when {@code access} is missing
*/
public static List<Map<String, Object>> getRunsForRoomForAdmin(AdminAccess access, String roomId, String userId,
String userType) {
AdminAccess.require(access);
return getUserRunsForRoom(roomId, userId, userType);
}
/**
* Return every run a user has in a room, newest first, for the reads above and
* for closing a room.
*
* @param roomId room whose runs are returned
* @param userId the user the room belongs to
* @param userType the login type of {@code userId}, or null to match the id
* under any type
* @return the user's runs in the room
*/
static List<Map<String, Object>> getUserRunsForRoom(String roomId, String userId, String userType) {
if (roomId == null || roomId.trim().isEmpty()) {
throw new IllegalArgumentException("roomId is required");
}
if (userId == null || userId.trim().isEmpty()) {
throw new IllegalArgumentException("userId is required");
}
String type = ValueUtils.trimToNull(userType);
IRDBMSEngine db = SystemEngineRegistry.getModelInferenceLogsDb();
PreparedStatement ps = null;
ResultSet rs = null;
try {
String query = "SELECT " + ACTIVITY_LOG_COLUMNS + " " + ACTIVITY_LOG_FROM + " WHERE ar.ROOM_ID = ?"
+ ownerCondition(type) + " ORDER BY ar.DATE_CREATED DESC, ar.RUN_ID DESC";
ps = db.getPreparedStatement(query);
ps.setString(1, roomId.trim());
ps.setString(2, userId.trim());
if (type != null) {
ps.setString(3, type);
}
rs = ps.executeQuery();
List<Map<String, Object>> runs = new ArrayList<>();
while (rs.next()) {
runs.add(runMapFromRow(rs));
}
return runs;
} catch (Exception e) {
throw new IllegalStateException("Failed to load AGENT_RUN rows for roomId=" + roomId, e);
} finally {
ConnectionUtils.closeAllConnectionsIfPooling(db, null, ps, rs);
}
}
/**
* Load any user's agent-run details, for the admin Agent Runs page.
*
* @param access proof that the caller is an admin
* @param runId agent run identifier
* @return matching run details with the run's user, or {@code null} when it
* does not exist
* @throws SecurityException when {@code access} is missing
*/
public static Map<String, Object> getRunMapForAdmin(AdminAccess access, String runId) {
AdminAccess.require(access);
IRDBMSEngine db = SystemEngineRegistry.getModelInferenceLogsDb();
PreparedStatement ps = null;
ResultSet rs = null;
try {
String query = "SELECT " + ACTIVITY_LOG_COLUMNS + ", ar.REQUEST_JSON " + ACTIVITY_LOG_FROM
+ " WHERE ar.RUN_ID = ?";
ps = db.getPreparedStatement(query);
ps.setString(1, runId);
rs = ps.executeQuery();
return rs.next() ? runMapFromRow(rs) : null;
} catch (Exception e) {
throw new IllegalStateException("Failed to load AGENT_RUN details for runId=" + runId, e);
} finally {
ConnectionUtils.closeAllConnectionsIfPooling(db, null, ps, rs);
}
}
/**
* Builds the grouped rooms query the room lists read and count, adding its
* parameters in the order its placeholders appear.
*
* @param filter which rooms to match
* @param params receives the query's parameters
* @return the query, without an order or a page
*/
private static String roomsQuery(RoomFilter filter, List<Object> params) {
StringBuilder query = new StringBuilder("SELECT ").append(ROOM_LIST_COLUMNS).append(' ')
.append(ACTIVITY_LOG_FROM).append(" WHERE ar.ROOM_ID IS NOT NULL");
for (AgentRunStatus status : ACTIVE_STATUSES) {
params.add(status.name());
}
params.add(AgentRunStatus.FAILED.name());
params.add(Boolean.FALSE);
if (filter.userId() != null) {
String type = ValueUtils.trimToNull(filter.userType());
query.append(ownerCondition(type));
params.add(filter.userId());
if (type != null) {
params.add(type);
}
}
String search = ValueUtils.trimToNull(filter.search());
if (search != null) {
query.append(" AND (LOWER(r.ROOM_NAME) LIKE ? ESCAPE '!' OR LOWER(ar.ROOM_ID) LIKE ? ESCAPE '!')");
params.add(containsPattern(search));
params.add(containsPattern(search));
}
query.append(" GROUP BY ar.ROOM_ID, ar.USER_ID");
List<String> having = new ArrayList<>();
if (!filter.subagentRooms()) {
having.add("SUM(CASE WHEN ar.PARENT_RUN_ID IS NULL THEN 1 ELSE 0 END) > 0");
}
if (filter.agentId() != null) {
having.add("SUM(CASE WHEN ar.WORKSPACE_ID = ? THEN 1 ELSE 0 END) > 0");
params.add(filter.agentId());
}
if (!filter.statuses().isEmpty()) {
having.add("SUM(CASE WHEN ar.STATUS IN ("
+ String.join(", ", Collections.nCopies(filter.statuses().size(), "?"))
+ ") THEN 1 ELSE 0 END) > 0");
for (AgentRunStatus status : filter.statuses()) {
params.add(status.name());
}
}
if (!having.isEmpty()) {
query.append(" HAVING ").append(String.join(" AND ", having));
}
return query.toString();
}
/**
* The agents of the rooms the admin Agent Runs page lists, most recently active
* first, for its agent filter: an agent is offered once a room holds a run of
* it that is not a subagent run.
*
* @param access proof that the caller is an admin
* @param search agents whose id contains this text, in any case, or null for
* every agent
* @param agentIds more agents to match with the search, such as those whose
* name contains it
* @param limit maximum number of agents to return
* @return each agent's id and when its rooms were last active
* @throws SecurityException when {@code access} is missing
*/
public static List<Map<String, Object>> getRoomAgentsForAdmin(AdminAccess access, String search,
Collection<String> agentIds, long limit) {
AdminAccess.require(access);
List<Object> params = new ArrayList<>();
StringBuilder query = new StringBuilder("SELECT ar.WORKSPACE_ID AS AGENT_ID, ").append(LAST_ACTIVITY_COLUMN)
.append(" FROM AGENT_RUN ar WHERE ").append(ROOM_ROOT_RUN_CONDITION)
.append(" AND ar.WORKSPACE_ID IS NOT NULL");
String text = ValueUtils.trimToNull(search);
if (text != null) {
List<String> matches = new ArrayList<>();
matches.add("LOWER(ar.WORKSPACE_ID) LIKE ? ESCAPE '!'");
params.add(containsPattern(text));
if (!agentIds.isEmpty()) {
matches.add(
"ar.WORKSPACE_ID IN (" + String.join(", ", Collections.nCopies(agentIds.size(), "?")) + ")");
params.addAll(agentIds);
}
query.append(" AND (").append(String.join(" OR ", matches)).append(')');
}
query.append(" GROUP BY ar.WORKSPACE_ID ORDER BY LAST_ACTIVITY_AT DESC, ar.WORKSPACE_ID");
return queryOptions(query, params, limit, rs -> {
Map<String, Object> agent = new HashMap<>();
agent.put("agentId", rs.getString("AGENT_ID"));
agent.put("lastActivityAt", ValueUtils.toStringOrNull(rs.getTimestamp("LAST_ACTIVITY_AT")));
return agent;
});
}
/**
* The users of the rooms the admin Agent Runs page lists, most recently active
* first, for its user filter: a user is offered once a room of theirs holds a
* run that is not a subagent run. A user is an id and the login type their runs
* store, so runs that store none give a row of their own.
*
* @param access proof that the caller is an admin
* @param search users whose id contains this text, in any case, or null for
* every user
* @param users more users to match with the search, by id and login type, such
* as those whose name contains it; runs that store no type match
* the id alone
* @param limit maximum number of users to return
* @return each user's id and login type and when their rooms were last active
* @throws SecurityException when {@code access} is missing
*/
public static List<Map<String, Object>> getRoomUsersForAdmin(AdminAccess access, String search,
Collection<Pair<String, String>> users, long limit) {
AdminAccess.require(access);
List<Object> params = new ArrayList<>();
StringBuilder query = new StringBuilder("SELECT ar.USER_ID, ar.USER_TYPE, ").append(LAST_ACTIVITY_COLUMN)
.append(" FROM AGENT_RUN ar WHERE ").append(ROOM_ROOT_RUN_CONDITION)
.append(" AND ar.USER_ID IS NOT NULL");
String text = ValueUtils.trimToNull(search);
if (text != null) {
List<String> matches = new ArrayList<>();
matches.add("LOWER(ar.USER_ID) LIKE ? ESCAPE '!'");
params.add(containsPattern(text));
for (Pair<String, String> user : users) {
matches.add("(ar.USER_ID = ? AND (ar.USER_TYPE = ? OR ar.USER_TYPE IS NULL))");
params.add(user.getValue0());
params.add(user.getValue1());
}
query.append(" AND (").append(String.join(" OR ", matches)).append(')');
}
query.append(" GROUP BY ar.USER_ID, ar.USER_TYPE ORDER BY LAST_ACTIVITY_AT DESC, ar.USER_ID");
return queryOptions(query, params, limit, rs -> {
Map<String, Object> user = new HashMap<>();
user.put("userId", rs.getString("USER_ID"));
user.put("userType", rs.getString("USER_TYPE"));
user.put("lastActivityAt", ValueUtils.toStringOrNull(rs.getTimestamp("LAST_ACTIVITY_AT")));
return user;
});
}
/**
* Reads one page of filter options.
*
* @param query the options query, without a page
* @param params its parameters, in the order its placeholders appear
* @param limit maximum number of options to return
* @param mapper reads one option from its row
* @return the options
*/
private static List<Map<String, Object>> queryOptions(StringBuilder query, List<Object> params, long limit,
QueryExecutionUtility.RowMapper<Map<String, Object>> mapper) {
IRDBMSEngine db = SystemEngineRegistry.getModelInferenceLogsDb();
PreparedStatement ps = null;
ResultSet rs = null;
try {
db.getQueryUtil().addLimitOffsetToQuery(query, limit, 0);
ps = db.getPreparedStatement(query.toString());
for (int i = 0; i < params.size(); i++) {
ps.setObject(i + 1, params.get(i));
}
rs = ps.executeQuery();
List<Map<String, Object>> options = new ArrayList<>();
while (rs.next()) {
options.add(mapper.map(rs));
}
return options;
} catch (Exception e) {
throw new IllegalStateException("Failed to load the agent run filter options", e);
} finally {
ConnectionUtils.closeAllConnectionsIfPooling(db, null, ps, rs);
}
}
/**
* A LIKE pattern, escaped with {@code !}, that matches text containing the
* given text in any case. Use it with {@code LOWER(column) LIKE ? ESCAPE '!'}.
*
* @param text the text to find
* @return the pattern
*/
private static String containsPattern(String text) {
return "%" + text.trim().toLowerCase(Locale.ROOT).replace("!", "!!").replace("%", "!%").replace("_", "!_")
+ "%";
}
/**
* The condition a run's owner meets: the id, and the login type when one is
* given. A run that stores no type matches the id alone, since its login type
* is not known.