11import { createLogger } from '@sim/logger'
2- import type { QueryResult , Session } from 'neo4j-driver'
2+ import type { Record as Neo4jRecord , Result , ResultSummary , Session } from 'neo4j-driver'
33import type {
44 Neo4jCreateRequest ,
55 Neo4jDeleteRequest ,
@@ -12,7 +12,7 @@ import type {
1212import { createNeo4jDriver } from '@/lib/internal/neo4j/client'
1313import { convertNeo4jValue } from '@/lib/internal/neo4j/values'
1414import {
15- capResultRows ,
15+ createResultRowsBudget ,
1616 resultTruncationReason ,
1717} from '@/lib/internal/tool-operations/response-limits'
1818import type { Neo4jNodeSchema , Neo4jRelationshipSchema } from '@/tools/neo4j/types'
@@ -47,21 +47,42 @@ function bindSessionAbort(session: Session, signal?: AbortSignal): () => void {
4747 return ( ) => signal . removeEventListener ( 'abort' , abort )
4848}
4949
50- function projectRecords ( result : QueryResult ) : Array < Record < string , unknown > > {
51- return result . records . map ( ( record ) => {
52- const projected : Record < string , unknown > = { }
53- for ( const key of record . keys ) {
54- if ( typeof key === 'string' ) projected [ key ] = convertNeo4jValue ( record . get ( key ) )
50+ function projectRecord ( record : Neo4jRecord ) : Record < string , unknown > {
51+ const projected : Record < string , unknown > = { }
52+ for ( const key of record . keys ) {
53+ if ( typeof key === 'string' ) projected [ key ] = convertNeo4jValue ( record . get ( key ) )
54+ }
55+ return projected
56+ }
57+
58+ /**
59+ * Streams records until the response budget is spent. Returning the iterator early discards the
60+ * rest on the server (the statement still completes, so the summary counters stay accurate)
61+ * instead of buffering every record in memory.
62+ */
63+ async function readCappedRecords ( result : Result ) {
64+ const budget = createResultRowsBudget ( )
65+ const records : Array < Record < string , unknown > > = [ ]
66+ const iterator = result [ Symbol . asyncIterator ] ( )
67+ let next = await iterator . next ( )
68+ while ( ! next . done ) {
69+ const projected = projectRecord ( next . value )
70+ if ( ! budget . admit ( projected ) ) {
71+ const rest = await iterator . return ?.( )
72+ if ( ! rest ?. done ) throw new Error ( 'Neo4j result ended without a summary' )
73+ return { records, summary : rest . value , truncated : true }
5574 }
56- return projected
57- } )
75+ records . push ( projected )
76+ next = await iterator . next ( )
77+ }
78+ return { records, summary : next . value , truncated : false }
5879}
5980
60- function projectSummary ( result : QueryResult ) {
61- const updates = result . summary . counters . updates ( )
81+ function projectSummary ( summary : ResultSummary ) {
82+ const updates = summary . counters . updates ( )
6283 return {
63- resultAvailableAfter : result . summary . resultAvailableAfter . toNumber ( ) ,
64- resultConsumedAfter : result . summary . resultConsumedAfter . toNumber ( ) ,
84+ resultAvailableAfter : summary . resultAvailableAfter . toNumber ( ) ,
85+ resultConsumedAfter : summary . resultConsumedAfter . toNumber ( ) ,
6586 counters : {
6687 nodesCreated : updates . nodesCreated ,
6788 nodesDeleted : updates . nodesDeleted ,
@@ -78,58 +99,42 @@ function projectSummary(result: QueryResult) {
7899 }
79100}
80101
81- function statementResponse ( kind : StatementKind , result : QueryResult ) {
82- const { rows : records , truncated } = capResultRows ( projectRecords ( result ) )
83- const summary = projectSummary ( result )
84- const truncation = truncated
85- ? {
86- truncated : true ,
87- truncationReason : resultTruncationReason (
88- records . length ,
89- 'Page with SKIP and LIMIT to read the rest.'
90- ) ,
91- }
102+ function statementResponse (
103+ kind : StatementKind ,
104+ read : Awaited < ReturnType < typeof readCappedRecords > >
105+ ) {
106+ const { records } = read
107+ const summary = projectSummary ( read . summary )
108+ const truncationReason = read . truncated
109+ ? resultTruncationReason (
110+ records . length ,
111+ kind === 'query'
112+ ? 'Page with SKIP and LIMIT to read the rest.'
113+ : 'A write statement still ran in full; page a read with SKIP and LIMIT to read the rest.'
114+ )
92115 : undefined
93- const withTruncation = ( message : string ) =>
94- truncation ? `${ message } ${ truncation . truncationReason } ` : message
116+ const withRecords = ( message : string ) => ( {
117+ message : truncationReason ? `${ message } ${ truncationReason } ` : message ,
118+ records,
119+ recordCount : records . length ,
120+ summary,
121+ ...( truncationReason && { truncated : true , truncationReason } ) ,
122+ } )
95123 switch ( kind ) {
96124 case 'query' :
97- return {
98- message : withTruncation ( `Found ${ records . length } records` ) ,
99- records,
100- recordCount : records . length ,
101- summary,
102- ...truncation ,
103- }
125+ return withRecords ( `Found ${ records . length } records` )
104126 case 'execute' :
105- return {
106- message : withTruncation ( `Query executed successfully, returned ${ records . length } records` ) ,
107- records,
108- recordCount : records . length ,
109- summary,
110- ...truncation ,
111- }
127+ return withRecords ( `Query executed successfully, returned ${ records . length } records` )
112128 case 'create' :
113- return {
114- message : `Created ${ summary . counters . nodesCreated } nodes and ${ summary . counters . relationshipsCreated } relationships` ,
115- records,
116- recordCount : records . length ,
117- summary,
118- }
129+ return withRecords (
130+ `Created ${ summary . counters . nodesCreated } nodes and ${ summary . counters . relationshipsCreated } relationships`
131+ )
119132 case 'update' :
120- return {
121- message : `Updated ${ summary . counters . propertiesSet } properties` ,
122- records,
123- recordCount : records . length ,
124- summary,
125- }
133+ return withRecords ( `Updated ${ summary . counters . propertiesSet } properties` )
126134 case 'merge' :
127- return {
128- message : `Merge completed: ${ summary . counters . nodesCreated } nodes created, ${ summary . counters . relationshipsCreated } relationships created` ,
129- records,
130- recordCount : records . length ,
131- summary,
132- }
135+ return withRecords (
136+ `Merge completed: ${ summary . counters . nodesCreated } nodes created, ${ summary . counters . relationshipsCreated } relationships created`
137+ )
133138 case 'delete' :
134139 return {
135140 message : `Deleted ${ summary . counters . nodesDeleted } nodes and ${ summary . counters . relationshipsDeleted } relationships` ,
@@ -145,9 +150,9 @@ async function executeStatement(input: StatementInput, kind: StatementKind, sign
145150 const session = driver . session ( { database : input . database } )
146151 const unbindAbort = bindSessionAbort ( session , signal )
147152 try {
148- const result = await session . run ( input . cypherQuery , input . parameters ?? { } )
153+ const read = await readCappedRecords ( session . run ( input . cypherQuery , input . parameters ?? { } ) )
149154 signal ?. throwIfAborted ( )
150- return statementResponse ( kind , result )
155+ return statementResponse ( kind , read )
151156 } finally {
152157 unbindAbort ( )
153158 await session . close ( ) . catch ( ( ) => undefined )
0 commit comments