This repository was archived by the owner on Mar 1, 2026. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathmemory-test.test.ts
More file actions
308 lines (262 loc) · 11.4 KB
/
memory-test.test.ts
File metadata and controls
308 lines (262 loc) · 11.4 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
import { createTestClient } from '@zenstackhq/testtools';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
describe.skip('Memory usage test with repeated CRUD operations', () => {
let client: any;
beforeEach(async () => {
client = await createTestClient(
`
model User {
id String @id @default(cuid())
email String @unique
name String
createdAt DateTime @default(now())
posts Post[]
comments Comment[]
}
model Post {
id String @id @default(cuid())
title String
content String
published Boolean @default(false)
createdAt DateTime @default(now())
author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
authorId String
comments Comment[]
}
model Comment {
id String @id @default(cuid())
content String
createdAt DateTime @default(now())
post Post @relation(fields: [postId], references: [id], onDelete: Cascade)
postId String
author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
authorId String
}
`,
);
});
afterEach(async () => {
await client?.$disconnect();
});
it('repeatedly executes CRUD operations with random data and tracks memory', async () => {
// ============ CONFIGURATION ============
// Adjust these values to test different workload scenarios
const iterations = 100; // Number of complete CRUD cycles to execute
const usersCount = 10; // Number of users to create per iteration
const postsPerUser = 5; // Number of posts per user
const commentsPerPost = 3; // Number of comments per post
// Calculated totals
const totalPosts = usersCount * postsPerUser;
const totalComments = totalPosts * commentsPerPost;
const memorySnapshots: Array<{
iteration: number;
rss: number;
heapTotal: number;
heapUsed: number;
external: number;
}> = [];
// Helper function to generate random string
const randomString = (length: number) => {
return Math.random()
.toString(36)
.substring(2, 2 + length);
};
// Helper function to generate random content
const randomContent = () => {
const paragraphs = Math.floor(Math.random() * 5) + 1;
return Array.from({ length: paragraphs }, () => randomString(100)).join('\n\n');
};
console.log(`\nStarting ${iterations} iterations of CRUD operations...\n`);
for (let i = 0; i < iterations; i++) {
// ============ CREATE ============
// Create users
const users = await Promise.all(
Array.from({ length: usersCount }, (_, idx) =>
client.user.create({
data: {
email: `user${i}-${idx + 1}-${randomString(8)}@test.com`,
name: `User ${i}-${idx + 1} ${randomString(10)}`,
},
}),
),
);
// Create posts per user
const posts: any[] = [];
for (const user of users) {
for (let j = 0; j < postsPerUser; j++) {
const post = await client.post.create({
data: {
title: `Post ${i}-${j} - ${randomString(20)}`,
content: randomContent(),
published: Math.random() > 0.5,
authorId: user.id,
},
});
posts.push(post);
}
}
// Create comments per post
const comments: any[] = [];
for (const post of posts) {
for (let k = 0; k < commentsPerPost; k++) {
const randomAuthor = users[Math.floor(Math.random() * users.length)]!;
const comment = await client.comment.create({
data: {
content: randomString(100),
postId: post.id,
authorId: randomAuthor.id,
},
});
comments.push(comment);
}
}
// ============ READ ============
// Read all users with posts and comments
const allUsers = await client.user.findMany({
include: {
posts: {
include: {
comments: true,
},
},
comments: true,
},
});
expect(allUsers).toHaveLength(usersCount);
// Read all posts with filtering
await client.post.findMany({
where: {
published: true,
},
include: {
author: true,
comments: true,
},
});
// Read individual comments
await client.comment.findMany({
include: {
post: true,
author: true,
},
});
// Aggregate operations
const userCount = await client.user.count();
const postCount = await client.post.count();
const commentCount = await client.comment.count();
expect(userCount).toBeGreaterThanOrEqual(usersCount);
expect(postCount).toBeGreaterThanOrEqual(totalPosts);
expect(commentCount).toBeGreaterThanOrEqual(totalComments);
// ============ UPDATE ============
// Update random posts
const postsToUpdate = posts.slice(0, 5);
for (const post of postsToUpdate) {
await client.post.update({
where: { id: post.id },
data: {
title: `Updated - ${randomString(20)}`,
content: randomContent(),
},
});
}
// Update random users
const userToUpdate = users[0]!;
await client.user.update({
where: { id: userToUpdate.id },
data: {
name: `Updated User - ${randomString(10)}`,
},
});
// Update many comments
await client.comment.updateMany({
where: {
postId: posts[0]!.id,
},
data: {
content: `Bulk updated - ${randomString(50)}`,
},
});
// ============ DELETE (Cleanup) ============
// Delete all comments first (due to foreign key constraints)
await client.comment.deleteMany({});
// Delete all posts
await client.post.deleteMany({});
// Delete all users
await client.user.deleteMany({});
// Verify cleanup
const remainingUsers = await client.user.count();
const remainingPosts = await client.post.count();
const remainingComments = await client.comment.count();
expect(remainingUsers).toBe(0);
expect(remainingPosts).toBe(0);
expect(remainingComments).toBe(0);
// ============ MEMORY SNAPSHOT ============
// Force garbage collection if available (run tests with --expose-gc flag)
if (global.gc) {
global.gc();
}
const memUsage = process.memoryUsage();
memorySnapshots.push({
iteration: i + 1,
rss: memUsage.rss,
heapTotal: memUsage.heapTotal,
heapUsed: memUsage.heapUsed,
external: memUsage.external,
});
// Log progress every 10 iterations
if ((i + 1) % 10 === 0) {
console.log(`Completed ${i + 1}/${iterations} iterations`);
console.log(
` Memory: ${(memUsage.heapUsed / 1024 / 1024).toFixed(2)} MB heap used, ${(memUsage.rss / 1024 / 1024).toFixed(2)} MB RSS`,
);
}
}
// ============ MEMORY ANALYSIS ============
console.log('\n=== Memory Usage Summary ===\n');
const firstSnapshot = memorySnapshots[0]!;
const lastSnapshot = memorySnapshots[memorySnapshots.length - 1]!;
const maxHeapUsed = Math.max(...memorySnapshots.map((s) => s.heapUsed));
const minHeapUsed = Math.min(...memorySnapshots.map((s) => s.heapUsed));
const avgHeapUsed = memorySnapshots.reduce((sum, s) => sum + s.heapUsed, 0) / memorySnapshots.length;
const formatMB = (bytes: number) => (bytes / 1024 / 1024).toFixed(2);
console.log('Heap Used:');
console.log(` Initial: ${formatMB(firstSnapshot.heapUsed)} MB`);
console.log(` Final: ${formatMB(lastSnapshot.heapUsed)} MB`);
console.log(` Min: ${formatMB(minHeapUsed)} MB`);
console.log(` Max: ${formatMB(maxHeapUsed)} MB`);
console.log(` Average: ${formatMB(avgHeapUsed)} MB`);
console.log(
` Growth: ${formatMB(lastSnapshot.heapUsed - firstSnapshot.heapUsed)} MB (${(((lastSnapshot.heapUsed - firstSnapshot.heapUsed) / firstSnapshot.heapUsed) * 100).toFixed(2)}%)`,
);
console.log('\nRSS (Resident Set Size):');
console.log(` Initial: ${formatMB(firstSnapshot.rss)} MB`);
console.log(` Final: ${formatMB(lastSnapshot.rss)} MB`);
console.log(
` Growth: ${formatMB(lastSnapshot.rss - firstSnapshot.rss)} MB (${(((lastSnapshot.rss - firstSnapshot.rss) / firstSnapshot.rss) * 100).toFixed(2)}%)`,
);
console.log('\nHeap Total:');
console.log(` Initial: ${formatMB(firstSnapshot.heapTotal)} MB`);
console.log(` Final: ${formatMB(lastSnapshot.heapTotal)} MB`);
console.log('\n=== Test Summary ===');
console.log(`Total iterations: ${iterations}`);
console.log(`Operations per iteration:`);
console.log(` - Created: ${usersCount} users, ${totalPosts} posts, ${totalComments} comments`);
console.log(` - Read: Multiple queries with includes and filters`);
console.log(` - Updated: 5 posts, 1 user, bulk comment updates`);
console.log(` - Deleted: All data (cleanup)`);
const opsPerIteration = usersCount + totalPosts + totalComments + 10; // approximate CRUD ops
console.log(`Total operations: ~${iterations * opsPerIteration}`);
// Check for significant memory leaks (> 50% growth is concerning)
const heapGrowthPercent = ((lastSnapshot.heapUsed - firstSnapshot.heapUsed) / firstSnapshot.heapUsed) * 100;
if (heapGrowthPercent > 50) {
console.log(
`\n⚠️ Warning: Heap usage grew by ${heapGrowthPercent.toFixed(2)}% which may indicate a memory leak`,
);
} else {
console.log(`\n✓ Memory usage appears stable (${heapGrowthPercent.toFixed(2)}% growth)`);
}
console.log('\n');
// Store snapshots for potential further analysis
expect(memorySnapshots).toHaveLength(iterations);
}, 120000); // 2 minute timeout for the test
});