Compare commits
8
Commits
0779e8ed97
..
test
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0164a76299 | ||
|
|
156693b76f | ||
|
|
3fd10c3d48 | ||
|
|
2b6b9c1445 | ||
|
|
d9755bf995 | ||
|
|
cfd815cd7c | ||
|
|
05cc5a1427 | ||
|
|
8d96f6e3e7 |
+2
-2
@@ -110,7 +110,7 @@ tasks.withType<KotlinCompile> {
|
||||
tasks.withType<Test>().configureEach {
|
||||
useJUnitPlatform()
|
||||
maxParallelForks = 1
|
||||
forkEvery = 50
|
||||
forkEvery = 300
|
||||
systemProperty("spring.test.context.cache.maxSize", 4)
|
||||
jvmArgs("-Dfile.encoding=UTF-8")
|
||||
|
||||
@@ -121,7 +121,7 @@ tasks.withType<Test>().configureEach {
|
||||
val heapMiB = TestHeapPolicy.calculateHeapMiB(availableBytes, maxParallelForks, maxWorkers)
|
||||
maxHeapSize = "${heapMiB}m"
|
||||
logger.lifecycle(
|
||||
"Test heap: available estimate={} MiB, workers={}, maxHeap={} MiB (50% budget, 1 GiB native reserve per worker)",
|
||||
"Test heap: available estimate={} MiB, workers={}, maxHeap={} MiB (50% worker budget, 25% native reserve)",
|
||||
availableBytes / (1024 * 1024),
|
||||
minOf(maxParallelForks, maxWorkers),
|
||||
heapMiB
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
plugins {
|
||||
java
|
||||
`kotlin-dsl`
|
||||
id("org.jlleitschuh.gradle.ktlint") version "11.5.0"
|
||||
}
|
||||
|
||||
repositories {
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
package buildlogic;
|
||||
|
||||
import com.sun.management.OperatingSystemMXBean;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public final class TestHeapPolicy {
|
||||
private static final long MIB = 1L << 20;
|
||||
private static final long WORKER_RESERVE_BYTES = 1L << 30;
|
||||
private static final long MINIMUM_HEAP_MIB = 4096;
|
||||
private static final Pattern PAGE_SIZE = Pattern.compile(
|
||||
"Mach Virtual Memory Statistics:\\s*\\(page size of ([0-9]+) bytes\\)"
|
||||
);
|
||||
private static final Pattern PAGE_COUNTER = Pattern.compile("Pages (free|inactive)\\s*:\\s*([0-9]+)\\.?");
|
||||
|
||||
private TestHeapPolicy() {
|
||||
}
|
||||
|
||||
public static long calculateHeapMiB(long availableBytes, int maxParallelForks, int maxWorkers) {
|
||||
if (availableBytes <= 0 || maxParallelForks <= 0 || maxWorkers <= 0) {
|
||||
throw new IllegalArgumentException("Available bytes, maxParallelForks and maxWorkers must be positive");
|
||||
}
|
||||
|
||||
int effectiveWorkers = Math.min(maxParallelForks, maxWorkers);
|
||||
long perWorkerBytes = availableBytes / 2 / effectiveWorkers;
|
||||
long heapMiB = (perWorkerBytes - WORKER_RESERVE_BYTES) / MIB;
|
||||
if (heapMiB < MINIMUM_HEAP_MIB) {
|
||||
throw new IllegalStateException(
|
||||
"Insufficient test memory: availableBytes=" + availableBytes + ", effectiveWorkers=" + effectiveWorkers
|
||||
+ ", minimumHeapMiB=" + MINIMUM_HEAP_MIB + ". Close other applications or reduce workers."
|
||||
);
|
||||
}
|
||||
return heapMiB;
|
||||
}
|
||||
|
||||
public static long readAvailableBytes() {
|
||||
long availableBytes;
|
||||
if (System.getProperty("os.name").startsWith("Mac")) {
|
||||
ProcessBuilder builder = new ProcessBuilder("/usr/bin/vm_stat").redirectErrorStream(true);
|
||||
builder.environment().put("LC_ALL", "C");
|
||||
try {
|
||||
Process process = builder.start();
|
||||
try (
|
||||
InputStream output = process.getInputStream();
|
||||
InputStream error = process.getErrorStream();
|
||||
OutputStream input = process.getOutputStream()
|
||||
) {
|
||||
if (!process.waitFor(5, TimeUnit.SECONDS)) {
|
||||
throw new IllegalStateException("vm_stat did not finish within 5 seconds");
|
||||
}
|
||||
if (process.exitValue() != 0) {
|
||||
throw new IllegalStateException("vm_stat failed with exit code " + process.exitValue());
|
||||
}
|
||||
availableBytes = parseMacVmStat(new String(output.readAllBytes(), StandardCharsets.US_ASCII));
|
||||
} finally {
|
||||
process.destroyForcibly();
|
||||
}
|
||||
} catch (InterruptedException failure) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("Interrupted while reading available memory with vm_stat", failure);
|
||||
} catch (IOException failure) {
|
||||
throw new IllegalStateException("Unable to read available memory with vm_stat", failure);
|
||||
}
|
||||
} else {
|
||||
OperatingSystemMXBean operatingSystem = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
|
||||
if (operatingSystem == null) {
|
||||
throw new IllegalStateException("OperatingSystemMXBean free-memory observation is unavailable");
|
||||
}
|
||||
availableBytes = operatingSystem.getFreeMemorySize();
|
||||
}
|
||||
if (availableBytes <= 0) {
|
||||
throw new IllegalStateException("Available-memory observation must be positive: availableBytes=" + availableBytes);
|
||||
}
|
||||
return availableBytes;
|
||||
}
|
||||
|
||||
static long parseMacVmStat(String output) {
|
||||
long pageSize = -1;
|
||||
long freePages = -1;
|
||||
long inactivePages = -1;
|
||||
try {
|
||||
for (String rawLine : output.lines().toList()) {
|
||||
String line = rawLine.strip();
|
||||
if (line.startsWith("Mach Virtual Memory Statistics")) {
|
||||
Matcher header = PAGE_SIZE.matcher(line);
|
||||
if (pageSize >= 0 || !header.matches()) {
|
||||
throw new IllegalArgumentException("Duplicate or malformed vm_stat page-size header: " + line);
|
||||
}
|
||||
pageSize = Long.parseLong(header.group(1));
|
||||
} else if (line.startsWith("Pages free") || line.startsWith("Pages inactive")) {
|
||||
Matcher counter = PAGE_COUNTER.matcher(line);
|
||||
if (!counter.matches()) {
|
||||
throw new IllegalArgumentException("Malformed vm_stat page counter: " + line);
|
||||
}
|
||||
long pages = Long.parseLong(counter.group(2));
|
||||
if (counter.group(1).equals("free")) {
|
||||
if (freePages >= 0) {
|
||||
throw new IllegalArgumentException("Duplicate vm_stat Pages free counter");
|
||||
}
|
||||
freePages = pages;
|
||||
} else {
|
||||
if (inactivePages >= 0) {
|
||||
throw new IllegalArgumentException("Duplicate vm_stat Pages inactive counter");
|
||||
}
|
||||
inactivePages = pages;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pageSize <= 0 || freePages < 0 || inactivePages < 0) {
|
||||
throw new IllegalArgumentException("vm_stat requires a positive page size and both free and inactive counters");
|
||||
}
|
||||
// Raw free already includes speculative pages; do not subtract or add them separately.
|
||||
return Math.multiplyExact(Math.addExact(freePages, inactivePages), pageSize);
|
||||
} catch (NumberFormatException | ArithmeticException failure) {
|
||||
throw new IllegalArgumentException("vm_stat page size or counters exceed the supported long range", failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package buildlogic
|
||||
|
||||
import com.sun.management.OperatingSystemMXBean
|
||||
import org.gradle.api.logging.Logging
|
||||
import java.io.IOException
|
||||
import java.lang.management.ManagementFactory
|
||||
import java.nio.charset.StandardCharsets
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.regex.Pattern
|
||||
|
||||
object TestHeapPolicy {
|
||||
private const val MIB = 1L shl 20
|
||||
private const val JVM_MINIMUM_HEAP_MIB = 2L
|
||||
private val PAGE_SIZE = Pattern.compile(
|
||||
"Mach Virtual Memory Statistics:\\s*\\(page size of ([0-9]+) bytes\\)"
|
||||
)
|
||||
private val PAGE_COUNTER = Pattern.compile("Pages (free|inactive)\\s*:\\s*([0-9]+)\\.?")
|
||||
private val LINUX_MEMORY_COUNTER = Pattern.compile("(MemTotal|MemAvailable):\\s+([0-9]+)\\s+kB")
|
||||
|
||||
@JvmStatic
|
||||
fun calculateHeapMiB(availableBytes: Long, maxParallelForks: Int, maxWorkers: Int): Long {
|
||||
require(availableBytes > 0 && maxParallelForks > 0 && maxWorkers > 0) {
|
||||
"Available bytes, maxParallelForks and maxWorkers must be positive"
|
||||
}
|
||||
|
||||
val effectiveWorkers = minOf(maxParallelForks, maxWorkers)
|
||||
val perWorkerBytes = availableBytes / 2 / effectiveWorkers
|
||||
val nativeReserveBytes = (perWorkerBytes + 3) / 4
|
||||
val heapMiB = (perWorkerBytes - nativeReserveBytes) / MIB
|
||||
check(heapMiB >= JVM_MINIMUM_HEAP_MIB) {
|
||||
"Insufficient test memory: availableBytes=$availableBytes, effectiveWorkers=$effectiveWorkers" +
|
||||
", heapMiB=$heapMiB. JVM requires at least 2 MiB. Close other applications or reduce workers."
|
||||
}
|
||||
return heapMiB
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun readAvailableBytes(): Long {
|
||||
val osName = System.getProperty("os.name")
|
||||
val availableBytes = if (osName.startsWith("Mac")) {
|
||||
val builder = ProcessBuilder("/usr/bin/vm_stat").redirectErrorStream(true)
|
||||
builder.environment()["LC_ALL"] = "C"
|
||||
try {
|
||||
val process = builder.start()
|
||||
try {
|
||||
process.inputStream.use { output ->
|
||||
process.errorStream.use {
|
||||
process.outputStream.use {
|
||||
check(process.waitFor(5, TimeUnit.SECONDS)) {
|
||||
"vm_stat did not finish within 5 seconds"
|
||||
}
|
||||
check(process.exitValue() == 0) {
|
||||
"vm_stat failed with exit code ${process.exitValue()}"
|
||||
}
|
||||
parseMacVmStat(String(output.readAllBytes(), StandardCharsets.US_ASCII))
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
process.destroyForcibly()
|
||||
}
|
||||
} catch (failure: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
throw IllegalStateException("Interrupted while reading available memory with vm_stat", failure)
|
||||
} catch (failure: IOException) {
|
||||
throw IllegalStateException("Unable to read available memory with vm_stat", failure)
|
||||
}
|
||||
} else {
|
||||
val operatingSystem = checkNotNull(ManagementFactory.getPlatformMXBean(OperatingSystemMXBean::class.java)) {
|
||||
"OperatingSystemMXBean free-memory observation is unavailable"
|
||||
}
|
||||
if (osName == "Linux") {
|
||||
val memInfo = try {
|
||||
Files.readString(Path.of("/proc/meminfo"), StandardCharsets.US_ASCII)
|
||||
} catch (failure: IOException) {
|
||||
throw IllegalStateException("Unable to read Linux available memory from /proc/meminfo", failure)
|
||||
}
|
||||
val jvmTotalBytes = operatingSystem.totalMemorySize
|
||||
val jvmFreeBytes = operatingSystem.freeMemorySize
|
||||
val available = resolveLinuxAvailableBytes(memInfo, jvmTotalBytes, jvmFreeBytes)
|
||||
Logging.getLogger(TestHeapPolicy::class.java).lifecycle(
|
||||
"Test memory (Linux): JVM total={} MiB, JVM free={} MiB, effective available={} MiB",
|
||||
jvmTotalBytes / MIB,
|
||||
jvmFreeBytes / MIB,
|
||||
available / MIB
|
||||
)
|
||||
available
|
||||
} else {
|
||||
operatingSystem.freeMemorySize
|
||||
}
|
||||
}
|
||||
check(availableBytes > 0) {
|
||||
"Available-memory observation must be positive: availableBytes=$availableBytes"
|
||||
}
|
||||
return availableBytes
|
||||
}
|
||||
|
||||
internal fun resolveLinuxAvailableBytes(memInfo: String, jvmTotalBytes: Long, jvmFreeBytes: Long): Long {
|
||||
var hostTotalBytes = -1L
|
||||
var hostAvailableBytes = -1L
|
||||
try {
|
||||
for (rawLine in memInfo.lineSequence()) {
|
||||
val line = rawLine.trim()
|
||||
if (line.startsWith("MemTotal:") || line.startsWith("MemAvailable:")) {
|
||||
val counter = LINUX_MEMORY_COUNTER.matcher(line)
|
||||
require(counter.matches()) { "Malformed Linux memory counter: $line" }
|
||||
val bytes = Math.multiplyExact(counter.group(2).toLong(), 1024L)
|
||||
if (counter.group(1) == "MemTotal") {
|
||||
require(hostTotalBytes < 0) { "Duplicate Linux MemTotal counter" }
|
||||
hostTotalBytes = bytes
|
||||
} else {
|
||||
require(hostAvailableBytes < 0) { "Duplicate Linux MemAvailable counter" }
|
||||
hostAvailableBytes = bytes
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (failure: NumberFormatException) {
|
||||
throw IllegalArgumentException("Linux memory counters exceed the supported long range", failure)
|
||||
} catch (failure: ArithmeticException) {
|
||||
throw IllegalArgumentException("Linux memory counters exceed the supported long range", failure)
|
||||
}
|
||||
require(hostTotalBytes > 0 && hostAvailableBytes >= 0 && hostAvailableBytes <= hostTotalBytes) {
|
||||
"Linux /proc/meminfo requires positive MemTotal and MemAvailable within that total"
|
||||
}
|
||||
check(jvmTotalBytes > 0) { "JVM total-memory observation must be positive" }
|
||||
if (jvmTotalBytes < hostTotalBytes) {
|
||||
check(jvmFreeBytes >= 0) { "Container free-memory observation must not be negative" }
|
||||
return minOf(hostAvailableBytes, jvmFreeBytes, jvmTotalBytes)
|
||||
}
|
||||
return hostAvailableBytes
|
||||
}
|
||||
|
||||
internal fun parseMacVmStat(output: String): Long {
|
||||
var pageSize = -1L
|
||||
var freePages = -1L
|
||||
var inactivePages = -1L
|
||||
try {
|
||||
for (rawLine in output.lineSequence()) {
|
||||
val line = rawLine.trim { Character.isWhitespace(it) }
|
||||
if (line.startsWith("Mach Virtual Memory Statistics")) {
|
||||
val header = PAGE_SIZE.matcher(line)
|
||||
require(pageSize < 0 && header.matches()) {
|
||||
"Duplicate or malformed vm_stat page-size header: $line"
|
||||
}
|
||||
pageSize = header.group(1).toLong()
|
||||
} else if (line.startsWith("Pages free") || line.startsWith("Pages inactive")) {
|
||||
val counter = PAGE_COUNTER.matcher(line)
|
||||
require(counter.matches()) { "Malformed vm_stat page counter: $line" }
|
||||
val pages = counter.group(2).toLong()
|
||||
if (counter.group(1) == "free") {
|
||||
require(freePages < 0) { "Duplicate vm_stat Pages free counter" }
|
||||
freePages = pages
|
||||
} else {
|
||||
require(inactivePages < 0) { "Duplicate vm_stat Pages inactive counter" }
|
||||
inactivePages = pages
|
||||
}
|
||||
}
|
||||
}
|
||||
require(pageSize > 0 && freePages >= 0 && inactivePages >= 0) {
|
||||
"vm_stat requires a positive page size and both free and inactive counters"
|
||||
}
|
||||
// Raw free already includes speculative pages; do not subtract or add them separately.
|
||||
return Math.multiplyExact(Math.addExact(freePages, inactivePages), pageSize)
|
||||
} catch (failure: NumberFormatException) {
|
||||
throw IllegalArgumentException("vm_stat page size or counters exceed the supported long range", failure)
|
||||
} catch (failure: ArithmeticException) {
|
||||
throw IllegalArgumentException("vm_stat page size or counters exceed the supported long range", failure)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
package buildlogic;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.DynamicTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestFactory;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
|
||||
|
||||
class TestHeapPolicyTest {
|
||||
private static final long MIB = 1L << 20;
|
||||
private static final long GIB = 1L << 30;
|
||||
|
||||
@TestFactory
|
||||
Stream<DynamicTest> shouldCalculateHeapWithinTheAvailableWorkerBudget() {
|
||||
return Stream.of(
|
||||
dynamicTest("10 GiB reaches the 4096 MiB floor", () ->
|
||||
assertEquals(4096, TestHeapPolicy.calculateHeapMiB(10 * GIB, 1, 1))),
|
||||
dynamicTest("20 GiB supports two workers at the floor", () ->
|
||||
assertEquals(4096, TestHeapPolicy.calculateHeapMiB(20 * GIB, 2, 2))),
|
||||
dynamicTest("13 GiB leaves half and the per-worker reserve", () ->
|
||||
assertEquals(5632, TestHeapPolicy.calculateHeapMiB(13 * GIB, 1, 1))),
|
||||
dynamicTest("max workers caps four requested forks", () ->
|
||||
assertEquals(7168, TestHeapPolicy.calculateHeapMiB(32 * GIB, 4, 2))),
|
||||
dynamicTest("max forks caps four available workers", () ->
|
||||
assertEquals(7168, TestHeapPolicy.calculateHeapMiB(32 * GIB, 2, 4))),
|
||||
dynamicTest("fractional MiB rounds down", () ->
|
||||
assertEquals(5632, TestHeapPolicy.calculateHeapMiB(13 * GIB + 2 * MIB - 1, 1, 1))),
|
||||
dynamicTest("an exact additional MiB is retained", () ->
|
||||
assertEquals(5633, TestHeapPolicy.calculateHeapMiB(13 * GIB + 2 * MIB, 1, 1))),
|
||||
dynamicTest("the largest positive long does not overflow", () ->
|
||||
assertEquals(4_398_046_510_079L, TestHeapPolicy.calculateHeapMiB(Long.MAX_VALUE, 1, 1)))
|
||||
);
|
||||
}
|
||||
|
||||
@TestFactory
|
||||
Stream<DynamicTest> shouldRejectInsufficientBudgetsWithActionableDiagnostics() {
|
||||
return Stream.of(
|
||||
new long[] {10 * GIB - 1, 1, 1},
|
||||
new long[] {20 * GIB - 1, 4, 2},
|
||||
new long[] {1, 1, 1},
|
||||
new long[] {GIB, 1, 1},
|
||||
new long[] {2 * GIB, 1, 1},
|
||||
new long[] {8 * GIB, 1, 1}
|
||||
).map(input -> dynamicTest(Arrays.toString(input), () -> {
|
||||
IllegalStateException failure = assertThrows(IllegalStateException.class, () ->
|
||||
TestHeapPolicy.calculateHeapMiB(input[0], (int) input[1], (int) input[2]));
|
||||
|
||||
String message = failure.getMessage();
|
||||
assertAll(
|
||||
() -> assertTrue(message.contains("availableBytes=" + input[0]), message),
|
||||
() -> assertTrue(message.contains("effectiveWorkers=" + Math.min(input[1], input[2])), message),
|
||||
() -> assertTrue(message.contains("minimumHeapMiB=4096"), message),
|
||||
() -> assertTrue(message.contains("Close other applications"), message),
|
||||
() -> assertTrue(message.contains("reduce workers"), message)
|
||||
);
|
||||
}));
|
||||
}
|
||||
|
||||
@TestFactory
|
||||
Stream<DynamicTest> shouldRejectNonpositiveAvailabilityOrWorkerLimits() {
|
||||
return Stream.of(
|
||||
new long[] {0, 1, 1},
|
||||
new long[] {-1, 1, 1},
|
||||
new long[] {Long.MIN_VALUE, 1, 1},
|
||||
new long[] {10 * GIB, 0, 1},
|
||||
new long[] {10 * GIB, -1, 1},
|
||||
new long[] {10 * GIB, Integer.MIN_VALUE, 1},
|
||||
new long[] {10 * GIB, 1, 0},
|
||||
new long[] {10 * GIB, 1, -1},
|
||||
new long[] {10 * GIB, 1, Integer.MIN_VALUE}
|
||||
).map(input -> dynamicTest(Arrays.toString(input), () ->
|
||||
assertThrows(IllegalArgumentException.class, () ->
|
||||
TestHeapPolicy.calculateHeapMiB(input[0], (int) input[1], (int) input[2]))));
|
||||
}
|
||||
|
||||
@TestFactory
|
||||
Stream<DynamicTest> shouldParseOnlyRawFreeAndInactivePages() {
|
||||
return Stream.of(
|
||||
dynamicTest("4K pages ignore speculative and file-backed counts", () ->
|
||||
assertEquals(2_371_584, TestHeapPolicy.parseMacVmStat("""
|
||||
Mach Virtual Memory Statistics: (page size of 4096 bytes)
|
||||
Pages free: 123.
|
||||
Pages speculative: 100.
|
||||
Pages inactive: 456.
|
||||
File-backed pages: 999.
|
||||
"""))),
|
||||
dynamicTest("16K pages accept reordered counters and whitespace", () ->
|
||||
assertEquals(81_920, TestHeapPolicy.parseMacVmStat("""
|
||||
Mach Virtual Memory Statistics: (page size of 16384 bytes)
|
||||
Pages inactive : 3.
|
||||
Pages active: 999.
|
||||
Pages free:\t2.
|
||||
"""))),
|
||||
dynamicTest("both raw counters may be zero", () ->
|
||||
assertEquals(0, TestHeapPolicy.parseMacVmStat(vmStat("4096", "0", "0")))),
|
||||
dynamicTest("counters need not have trailing periods", () ->
|
||||
assertEquals(20_480, TestHeapPolicy.parseMacVmStat(
|
||||
vmStat("4096", "2", "3").replace(".\n", "\n")))),
|
||||
dynamicTest("the largest representable byte count remains valid", () ->
|
||||
assertEquals(Long.MAX_VALUE, TestHeapPolicy.parseMacVmStat(vmStat("1", "9223372036854775806", "1"))))
|
||||
);
|
||||
}
|
||||
|
||||
@TestFactory
|
||||
Stream<DynamicTest> shouldRejectMissingDuplicateMalformedNegativeOrOverflowingVmStatFields() {
|
||||
String valid = vmStat("4096", "2", "3");
|
||||
return Stream.of(
|
||||
"",
|
||||
"Pages free: 2.\nPages inactive: 3.\n",
|
||||
"page size of 4096 bytes\nPages free: 2.\nPages inactive: 3.\n",
|
||||
valid.replace("Pages free: 2.\n", ""),
|
||||
valid.replace("Pages inactive: 3.\n", ""),
|
||||
valid + "Pages free: 2.\n",
|
||||
valid + "Pages inactive: 3.\n",
|
||||
valid + "Mach Virtual Memory Statistics: (page size of 4096 bytes)\n",
|
||||
valid + "Pages free: broken.\n",
|
||||
vmStat("4096", "-1", "3"),
|
||||
vmStat("4096", "2", "-1"),
|
||||
vmStat("-4096", "2", "3"),
|
||||
vmStat("0", "2", "3"),
|
||||
vmStat("invalid", "2", "3"),
|
||||
vmStat("4096", "2x", "3"),
|
||||
vmStat("4096", "2", "3.5"),
|
||||
valid.replace("Pages free:", "Pages free"),
|
||||
valid.replace("bytes)", "bytes) trailing"),
|
||||
vmStat("9223372036854775808", "2", "3"),
|
||||
vmStat("4096", "9223372036854775808", "3"),
|
||||
vmStat("1", "9223372036854775807", "1"),
|
||||
vmStat("4096", "2251799813685248", "0")
|
||||
).map(output -> dynamicTest("rejects " + output.replace('\n', ' '), () ->
|
||||
assertThrows(IllegalArgumentException.class, () -> TestHeapPolicy.parseMacVmStat(output))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReadPositiveAvailabilityFromTheCurrentOperatingSystem() {
|
||||
assertTrue(TestHeapPolicy.readAvailableBytes() > 0);
|
||||
}
|
||||
|
||||
private static String vmStat(String pageSize, String free, String inactive) {
|
||||
return "Mach Virtual Memory Statistics: (page size of " + pageSize + " bytes)\n"
|
||||
+ "Pages free: " + free + ".\nPages inactive: " + inactive + ".\n";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package buildlogic
|
||||
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertThrows
|
||||
import org.junit.jupiter.api.DynamicTest
|
||||
import org.junit.jupiter.api.DynamicTest.dynamicTest
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.api.TestFactory
|
||||
|
||||
class LinuxAvailableMemoryTest {
|
||||
@Test
|
||||
fun shouldUseReclaimableHostMemoryInsteadOfTheReportedJenkinsFreeMemory() {
|
||||
val available = TestHeapPolicy.resolveLinuxAvailableBytes(memInfo(), 16 * GIB, 1315 * MIB)
|
||||
|
||||
assertEquals(10 * GIB, available)
|
||||
assertEquals(3840L, TestHeapPolicy.calculateHeapMiB(available, 1, 1))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldAllowHostMemoryWhenJvmTotalIsLargerThanProcTotal() {
|
||||
assertEquals(10 * GIB, TestHeapPolicy.resolveLinuxAvailableBytes(memInfo(), 16 * GIB + 4096, 1315 * MIB))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldNotTreatZeroHostFreePagesAsZeroAvailableMemory() {
|
||||
assertEquals(10 * GIB, TestHeapPolicy.resolveLinuxAvailableBytes(memInfo(), 16 * GIB, 0))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldCapAvailableMemoryByRecognizedContainerHeadroom() {
|
||||
assertEquals(3 * GIB, TestHeapPolicy.resolveLinuxAvailableBytes(memInfo(), 4 * GIB, 3 * GIB))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldRespectHostPressureEvenWhenTheContainerHasMoreHeadroom() {
|
||||
assertEquals(GIB, TestHeapPolicy.resolveLinuxAvailableBytes(memInfo(availableKiB = GIB / 1024), 4 * GIB, 3 * GIB))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldNeverExceedTheRecognizedContainerTotal() {
|
||||
assertEquals(4 * GIB, TestHeapPolicy.resolveLinuxAvailableBytes(memInfo(), 4 * GIB, 8 * GIB))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldPreserveZeroAvailableMemoryWithoutFallingBackToHostFree() {
|
||||
assertEquals(0L, TestHeapPolicy.resolveLinuxAvailableBytes(memInfo(availableKiB = 0), 16 * GIB, 1315 * MIB))
|
||||
assertEquals(0L, TestHeapPolicy.resolveLinuxAvailableBytes(memInfo(), 4 * GIB, 0))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldRejectUnknownRemainingMemoryForARecognizedContainerLimit() {
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
TestHeapPolicy.resolveLinuxAvailableBytes(memInfo(), 4 * GIB, -1)
|
||||
}
|
||||
}
|
||||
|
||||
@TestFactory
|
||||
fun shouldRejectUnknownJvmTotalMemory(): List<DynamicTest> = listOf(0L, -1L).map { total ->
|
||||
dynamicTest("JVM total $total") {
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
TestHeapPolicy.resolveLinuxAvailableBytes(memInfo(), total, GIB)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldParseReorderedKiBCountersWithoutAddingCachedOrSwapPages() {
|
||||
val input = "MemAvailable:\t3072 kB\nCached: 999999 kB\nSwapFree: 999999 kB\n MemTotal: 4096 kB\n"
|
||||
assertEquals(3 * MIB, TestHeapPolicy.resolveLinuxAvailableBytes(input, 4 * MIB, MIB))
|
||||
}
|
||||
|
||||
@TestFactory
|
||||
fun shouldRejectMissingDuplicateMalformedOrOverflowingProcCounters(): List<DynamicTest> {
|
||||
val valid = memInfo()
|
||||
return listOf(
|
||||
"",
|
||||
"MemTotal: 16777216 kB\n",
|
||||
"MemAvailable: 10485760 kB\n",
|
||||
valid + "MemTotal: 16777216 kB\n",
|
||||
valid + "MemAvailable: 10485760 kB\n",
|
||||
valid.replace("16777216 kB", "0 kB"),
|
||||
valid.replace("10485760 kB", "16777217 kB"),
|
||||
valid.replace("10485760 kB", "-1 kB"),
|
||||
valid.replace("10485760 kB", "1.5 kB"),
|
||||
valid.replace("10485760 kB", "invalid kB"),
|
||||
valid.replace("10485760 kB", "10485760 MB"),
|
||||
valid.replace("10485760 kB", "10485760"),
|
||||
valid.replace("10485760 kB", "10485760 kB trailing"),
|
||||
valid.replace("16777216 kB", "9223372036854775808 kB"),
|
||||
valid.replace("10485760 kB", "9223372036854775808 kB"),
|
||||
valid.replace("16777216 kB", "9007199254740992 kB"),
|
||||
valid.replace("10485760 kB", "9007199254740992 kB")
|
||||
).map { input ->
|
||||
dynamicTest("rejects ${input.replace('\n', ' ')}") {
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
TestHeapPolicy.resolveLinuxAvailableBytes(input, 16 * GIB, GIB)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun memInfo(availableKiB: Long = 10 * GIB / 1024): String =
|
||||
"MemTotal: 16777216 kB\nMemFree: 1346560 kB\nMemAvailable: $availableKiB kB\n"
|
||||
|
||||
companion object {
|
||||
private const val MIB = 1_048_576L
|
||||
private const val GIB = 1_073_741_824L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package buildlogic
|
||||
|
||||
import org.junit.jupiter.api.Assertions.assertAll
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertThrows
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
import org.junit.jupiter.api.DynamicTest
|
||||
import org.junit.jupiter.api.DynamicTest.dynamicTest
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.api.TestFactory
|
||||
|
||||
class TestHeapPolicyTest {
|
||||
@TestFactory
|
||||
fun shouldCalculateHeapWithinTheAvailableWorkerBudget(): List<DynamicTest> = listOf(
|
||||
dynamicTest("the reported Jenkins availability runs below the former fixed floor") {
|
||||
assertEquals(879L, TestHeapPolicy.calculateHeapMiB(2_460_004_352L, 1, 1))
|
||||
},
|
||||
dynamicTest("1 GiB reserves native memory proportionally") {
|
||||
assertEquals(384L, TestHeapPolicy.calculateHeapMiB(GIB, 1, 1))
|
||||
},
|
||||
dynamicTest("2 GiB does not lose the whole worker budget to a fixed reserve") {
|
||||
assertEquals(768L, TestHeapPolicy.calculateHeapMiB(2 * GIB, 1, 1))
|
||||
},
|
||||
dynamicTest("8 GiB permits a heap below 4 GiB") {
|
||||
assertEquals(3072L, TestHeapPolicy.calculateHeapMiB(8 * GIB, 1, 1))
|
||||
},
|
||||
dynamicTest("10 GiB scales without a policy floor") {
|
||||
assertEquals(3840L, TestHeapPolicy.calculateHeapMiB(10 * GIB, 1, 1))
|
||||
},
|
||||
dynamicTest("20 GiB is shared between two workers") {
|
||||
assertEquals(3840L, TestHeapPolicy.calculateHeapMiB(20 * GIB, 2, 2))
|
||||
},
|
||||
dynamicTest("13 GiB leaves half and a proportional native reserve") {
|
||||
assertEquals(4992L, TestHeapPolicy.calculateHeapMiB(13 * GIB, 1, 1))
|
||||
},
|
||||
dynamicTest("max workers caps four requested forks") {
|
||||
assertEquals(6144L, TestHeapPolicy.calculateHeapMiB(32 * GIB, 4, 2))
|
||||
},
|
||||
dynamicTest("max forks caps four available workers") {
|
||||
assertEquals(6144L, TestHeapPolicy.calculateHeapMiB(32 * GIB, 2, 4))
|
||||
},
|
||||
dynamicTest("fractional MiB rounds down") {
|
||||
assertEquals(4992L, TestHeapPolicy.calculateHeapMiB(13 * GIB + 2 * MIB, 1, 1))
|
||||
},
|
||||
dynamicTest("an exact proportional increase is retained") {
|
||||
assertEquals(4995L, TestHeapPolicy.calculateHeapMiB(13 * GIB + 8 * MIB, 1, 1))
|
||||
},
|
||||
dynamicTest("one byte below the proportional increase rounds down") {
|
||||
assertEquals(4994L, TestHeapPolicy.calculateHeapMiB(13 * GIB + 8 * MIB - 1, 1, 1))
|
||||
},
|
||||
dynamicTest("the JVM technical minimum is not replaced with an application floor") {
|
||||
assertEquals(2L, TestHeapPolicy.calculateHeapMiB(5_592_406, 1, 1))
|
||||
},
|
||||
dynamicTest("the JVM technical minimum accounts for two workers") {
|
||||
assertEquals(2L, TestHeapPolicy.calculateHeapMiB(11_184_812, 2, 2))
|
||||
},
|
||||
dynamicTest("the largest positive long does not overflow") {
|
||||
assertEquals(3_298_534_883_327L, TestHeapPolicy.calculateHeapMiB(Long.MAX_VALUE, 1, 1))
|
||||
}
|
||||
)
|
||||
|
||||
@TestFactory
|
||||
fun shouldRejectOnlyBudgetsTooSmallToStartTheJvm(): List<DynamicTest> = listOf(
|
||||
Triple(5_592_405L, 1, 1),
|
||||
Triple(11_184_811L, 4, 2),
|
||||
Triple(1L, 1, 1),
|
||||
Triple(MIB, 1, 1),
|
||||
Triple(2 * MIB, 1, 1),
|
||||
Triple(4 * MIB, 1, 1)
|
||||
).map { (available, forks, workers) ->
|
||||
dynamicTest("[$available, $forks, $workers]") {
|
||||
val failure = assertThrows(IllegalStateException::class.java) {
|
||||
TestHeapPolicy.calculateHeapMiB(available, forks, workers)
|
||||
}
|
||||
val message = requireNotNull(failure.message)
|
||||
assertAll(
|
||||
{ assertTrue(message.contains("availableBytes=$available"), message) },
|
||||
{ assertTrue(message.contains("effectiveWorkers=${minOf(forks, workers)}"), message) },
|
||||
{ assertTrue(message.contains("JVM requires at least 2 MiB"), message) },
|
||||
{ assertTrue(message.contains("Close other applications"), message) },
|
||||
{ assertTrue(message.contains("reduce workers"), message) }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@TestFactory
|
||||
fun shouldRejectNonpositiveAvailabilityOrWorkerLimits(): List<DynamicTest> = listOf(
|
||||
Triple(0L, 1, 1),
|
||||
Triple(-1L, 1, 1),
|
||||
Triple(Long.MIN_VALUE, 1, 1),
|
||||
Triple(10 * GIB, 0, 1),
|
||||
Triple(10 * GIB, -1, 1),
|
||||
Triple(10 * GIB, Int.MIN_VALUE, 1),
|
||||
Triple(10 * GIB, 1, 0),
|
||||
Triple(10 * GIB, 1, -1),
|
||||
Triple(10 * GIB, 1, Int.MIN_VALUE)
|
||||
).map { (available, forks, workers) ->
|
||||
dynamicTest("[$available, $forks, $workers]") {
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
TestHeapPolicy.calculateHeapMiB(available, forks, workers)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@TestFactory
|
||||
fun shouldParseOnlyRawFreeAndInactivePages(): List<DynamicTest> = listOf(
|
||||
dynamicTest("4K pages ignore speculative and file-backed counts") {
|
||||
assertEquals(
|
||||
2_371_584L,
|
||||
TestHeapPolicy.parseMacVmStat(
|
||||
"""
|
||||
Mach Virtual Memory Statistics: (page size of 4096 bytes)
|
||||
Pages free: 123.
|
||||
Pages speculative: 100.
|
||||
Pages inactive: 456.
|
||||
File-backed pages: 999.
|
||||
""".trimIndent()
|
||||
)
|
||||
)
|
||||
},
|
||||
dynamicTest("16K pages accept reordered counters and whitespace") {
|
||||
assertEquals(
|
||||
81_920L,
|
||||
TestHeapPolicy.parseMacVmStat(
|
||||
" Mach Virtual Memory Statistics: (page size of 16384 bytes)\n" +
|
||||
" Pages inactive : 3.\nPages active: 999.\nPages free:\t2.\n"
|
||||
)
|
||||
)
|
||||
},
|
||||
dynamicTest("both raw counters may be zero") {
|
||||
assertEquals(0L, TestHeapPolicy.parseMacVmStat(vmStat("4096", "0", "0")))
|
||||
},
|
||||
dynamicTest("counters need not have trailing periods") {
|
||||
assertEquals(20_480L, TestHeapPolicy.parseMacVmStat(vmStat("4096", "2", "3").replace(".\n", "\n")))
|
||||
},
|
||||
dynamicTest("the largest representable byte count remains valid") {
|
||||
assertEquals(Long.MAX_VALUE, TestHeapPolicy.parseMacVmStat(vmStat("1", "9223372036854775806", "1")))
|
||||
}
|
||||
)
|
||||
|
||||
@TestFactory
|
||||
fun shouldRejectMissingDuplicateMalformedNegativeOrOverflowingVmStatFields(): List<DynamicTest> {
|
||||
val valid = vmStat("4096", "2", "3")
|
||||
return listOf(
|
||||
"",
|
||||
"Pages free: 2.\nPages inactive: 3.\n",
|
||||
"page size of 4096 bytes\nPages free: 2.\nPages inactive: 3.\n",
|
||||
valid.replace("Pages free: 2.\n", ""),
|
||||
valid.replace("Pages inactive: 3.\n", ""),
|
||||
valid + "Pages free: 2.\n",
|
||||
valid + "Pages inactive: 3.\n",
|
||||
valid + "Mach Virtual Memory Statistics: (page size of 4096 bytes)\n",
|
||||
valid + "Pages free: broken.\n",
|
||||
vmStat("4096", "-1", "3"),
|
||||
vmStat("4096", "2", "-1"),
|
||||
vmStat("-4096", "2", "3"),
|
||||
vmStat("0", "2", "3"),
|
||||
vmStat("invalid", "2", "3"),
|
||||
vmStat("4096", "2x", "3"),
|
||||
vmStat("4096", "2", "3.5"),
|
||||
valid.replace("Pages free:", "Pages free"),
|
||||
valid.replace("bytes)", "bytes) trailing"),
|
||||
vmStat("9223372036854775808", "2", "3"),
|
||||
vmStat("4096", "9223372036854775808", "3"),
|
||||
vmStat("1", "9223372036854775807", "1"),
|
||||
vmStat("4096", "2251799813685248", "0")
|
||||
).map { output ->
|
||||
dynamicTest("rejects ${output.replace('\n', ' ')}") {
|
||||
assertThrows(IllegalArgumentException::class.java) { TestHeapPolicy.parseMacVmStat(output) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldReadPositiveAvailabilityFromTheCurrentOperatingSystem() {
|
||||
assertTrue(TestHeapPolicy.readAvailableBytes() > 0)
|
||||
}
|
||||
|
||||
private fun vmStat(pageSize: String, free: String, inactive: String): String =
|
||||
"Mach Virtual Memory Statistics: (page size of $pageSize bytes)\n" +
|
||||
"Pages free: $free.\nPages inactive: $inactive.\n"
|
||||
|
||||
companion object {
|
||||
private const val MIB = 1_048_576L
|
||||
private const val GIB = 1_073_741_824L
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
- 작성일: 2026-11-18
|
||||
- 기준: [prd.md](prd.md)
|
||||
- 상태: P4 구현·경계/실제 worker/부족 예산/lint 검증·리뷰 승인·정리 완료. 전체 테스트 재실행은 미수행.
|
||||
- 상태: P8 fork300 동일 힙 focused 비교·lint·리뷰 승인·정리 완료. 실제 Jenkins와 전체 suite 재실행은 미수행.
|
||||
- 활성 Goal: 없음
|
||||
|
||||
## P1-T1: 실패 원인 재현과 최소 테스트 수정
|
||||
@@ -197,3 +197,112 @@
|
||||
- 임시 JVM 관측 probe, 부족 예산 init script와 실행 노트를 삭제하고 owned root를 정리한다. 계산식/검증 결과는 이 문서에 남긴다. 앱 코드 및 기존 테스트 파일은 P4에서 수정하지 않았다.
|
||||
- 최종 독립 리뷰 APPROVE: raw free+inactive 계산, 예산/worker cap/내림/4GiB 하한, parser 오류와 프로세스 정리, doFirst 연결 및 별도 buildSrc 테스트 범위를 확인했다. 비macOS와 강제 timeout/interruption은 미검증으로 유지한다.
|
||||
- 소유 임시 root 삭제와 부재 확인 완료. 추가 재검증 없이 종료하며 commit/push는 수행하지 않았다.
|
||||
|
||||
## P5: 고정 힙 하한·예약량 제거
|
||||
- 시작 조건: 사용자 승인과 Jenkins 오류 `availableBytes=2460004352, effectiveWorkers=1, minimumHeapMiB=4096`.
|
||||
- 대상 파일: `buildSrc/src/main/java/buildlogic/TestHeapPolicy.java`, `buildSrc/src/test/java/buildlogic/TestHeapPolicyTest.java`, 루트 `build.gradle.kts` 로그, 실행 가이드와 기존 문서.
|
||||
- 정책 변경: F=`min(maxParallelForks,maxWorkers)`, P=`floor(floor(A/2)/F)`, native reserve=`ceil(P/4)`, heapMiB=`floor((P-native reserve)/1MiB)`. 고정 1GiB 차감과 4GiB 정책 하한을 제거한다. 양수 입력·overflow 안전성은 유지한다.
|
||||
- 기술 한계 관측: 로컬 Java17에서 `java -Xmx2m -version`은 성공하고 `java -Xmx1m -version`은 `Too small maximum heap`로 실패했다. 따라서 2MiB 미만만 JVM 실행 불가로 거부하며 상향 보정하지 않는다.
|
||||
- [x] Jenkins 실제 값, sub-GiB/4GiB 미만 예산, worker 분배, rounding과 JVM 극소 경계의 새 계약을 테스트에서 먼저 RED 확인.
|
||||
- [x] 비율 계산 구현 후 전체 buildSrc 정책 테스트 GREEN.
|
||||
- [x] 실제 root worker에 동적 Xmx 전달, script lint·단일 리뷰 확인.
|
||||
- [x] 현재 정책/미검증 범위 문서와 소유 임시 자원 정리.
|
||||
- 실제 Jenkins/AWS 실행, 전체 앱 suite, OS 메모리 조회 변경은 범위 밖이다. 이번 회귀는 4GiB 사전 거부를 해결하며 작은 힙에서 모든 테스트가 통과한다고 보장하지 않는다.
|
||||
- RED: `./gradlew --no-daemon --offline -p buildSrc test --tests 'buildlogic.TestHeapPolicyTest' --console=plain`, exit 1/8초. 58개 중 21개 실패. 실제 Jenkins 값과 1/2/8GiB 입력은 기존 fixed floor 예외를 재현했고, 다른 예산/반올림은 새 비율 계약과 불일치했다. 기존 parser/invalid-input 검사들은 그대로 유지했다.
|
||||
- 최소 구현: 1GiB 상수를 없애고 `ceil(perWorkerBytes/4)`를 native reserve로 사용한다. 4GiB 정책 하한 대신 JVM 실행 가능 여부만 검사한다. root 로그와 실행 가이드도 비율 정책으로 갱신했다.
|
||||
- GREEN: 같은 buildSrc focused 명령 exit 0/8초, 58 tests/0 failures/0 errors/0 skipped. Jenkins 제공값 2,460,004,352 bytes가 879MiB를 반환함을 검증했다.
|
||||
- 실제 root 검증: `./gradlew --no-daemon --offline --max-workers=1 ktlintKotlinScriptCheck test --tests '*CodePointTextSplitterTest' --info --console=plain`, exit 0/9분 11초. buildSrc 변경에 따른 기존 Kotlin/KAPT 재컴파일을 포함했다. CodePointTextSplitterTest 33개 통과와 script lint 성공 확인. 기존 애플리케이션/테스트 컴파일 경고는 숨기거나 변경하지 않았다.
|
||||
- task 시작 시 관측 13,160MiB, worker 1개, 선택 4,935MiB였고 실제 worker 명령 `-Xmx4935m`과 일치했다. 이 로컬 실행을 Jenkins 노드의 실행 결과로 해석하지 않는다.
|
||||
- 독립 P5 리뷰 APPROVE. 고정 4GiB·1GiB 값 제거, 비율 예약의 overflow 안전성, 실제 Jenkins 입력과 sub-GiB/rounding 경계, OS reader/기존 보호 설정 유지 및 작은 힙의 한계를 확인했다.
|
||||
- `git diff --check` 통과, 소유 테스트 worker 없음 확인. 실행 노트·owned temp root 삭제 및 부재 확인 후 종료한다. commit/push는 수행하지 않았다.
|
||||
|
||||
## P6: buildSrc Kotlin 통일
|
||||
- 사용자 승인에 따른 언어 전환이며 정책 변경이 아니다. P5의 Java 58개 GREEN을 baseline으로 사용한다.
|
||||
- 의존 경계: root build.gradle.kts → TestHeapPolicy public static calculateHeapMiB/readAvailableBytes. parser는 buildSrc 테스트에서만 호출한다. 앱 코드 의존은 없다.
|
||||
- 변경 파일: `buildSrc/build.gradle.kts`, Java helper/test를 각각 `buildSrc/src/main/kotlin/buildlogic/TestHeapPolicy.kt`, `buildSrc/src/test/kotlin/buildlogic/TestHeapPolicyTest.kt`로 이동, 기존 작업 문서와 사용법 필요 부분.
|
||||
- 플러그인: Gradle 버전에 맞는 `kotlin-dsl`, Java toolchain 17, 기존 JUnit 5.8.2 유지. 앱 Kotlin 1.6.21은 변경하지 않는다. 로컬에 kotlin-dsl 플러그인이 캐시돼 있지 않아 최초 의존성 해석은 네트워크가 필요할 수 있다.
|
||||
- [x] Kotlin 전환과 Java 중복 제거. 모든 동작·케이스 보존.
|
||||
- [x] buildSrc clean focused test에서 58/58 통과, Kotlin 소스 lint와 public JVM signature 확인.
|
||||
- [x] root Gradle에서 helper를 호출하고 선택된 Xmx가 실제 worker에 전달되는지 확인.
|
||||
- [x] 독립 리뷰, 문서 기록, 소유 임시 자원 정리.
|
||||
- `javap` baseline: `public static long calculateHeapMiB(long,int,int)`, `public static long readAvailableBytes()`. 기존 parser는 Java package-private이다. Kotlin에서는 module 내부로 한정한다.
|
||||
- Java baseline XML: 58 tests/0 failures, 정렬한 testcase 이름 JSON의 SHA-256 `6ba55b03a872659fedbca5419274eeaf42b38c2e219cd01fa34725f7b2447642`. 언어 이동 후 case 보존 확인에만 사용하며 구현 의미는 실제 assertion과 리뷰로 대조한다.
|
||||
- `./gradlew --no-daemon -p buildSrc help --console=plain` exit 0/52초. 새 kotlin-dsl 플러그인 해석과 Java17/JUnit 설정 로딩을 확인했다. 앱 Kotlin 플러그인 버전은 유지했다.
|
||||
- buildSrc의 새 Kotlin 소스도 검증하도록 루트와 동일한 ktlint 11.5.0 플러그인을 해당 build에 적용한다. 테스트와 정책의 포맷 검사 범위를 빠뜨리지 않으며 앱 의존성은 바꾸지 않는다.
|
||||
- `./gradlew --no-daemon -p buildSrc clean test --tests 'buildlogic.TestHeapPolicyTest' ktlintCheck --console=plain` exit 0/52초. Kotlin 컴파일 후 58 tests/0 failures/0 errors/0 skipped와 buildSrc의 script/main/test lint 통과. compileJava/compileTestJava NO-SOURCE로 이전 Java 산출물에 의존하지 않음을 확인했다.
|
||||
- 변환 후 testcase 이름 digest는 baseline과 동일하다. `javap -classpath buildSrc/build/classes/kotlin/main buildlogic.TestHeapPolicy`는 `.kt`에서 생성된 두 public static 메서드를 확인했다. parser는 internal 메서드로 컴파일된다.
|
||||
- root 연결: `./gradlew --no-daemon --offline --max-workers=1 ktlintKotlinScriptCheck test --tests '*CodePointTextSplitterTest' --info --console=plain`, exit 0/11분 32초. buildSrc classpath 변경에 따른 기존 Kotlin/KAPT 재컴파일을 포함한다. 기존 컴파일 경고는 변경하거나 숨기지 않았다. CodePointTextSplitterTest 33개, root script lint 통과.
|
||||
- 실제 root task 로그는 가용 추정 12,099MiB/worker1/선택4,537MiB이고 worker 명령에 `-Xmx4537m`이 전달됐다. Java→Kotlin 이동 후에도 기존 public 호출과 실행 시 산정 연결이 작동했다.
|
||||
- 독립 P6 리뷰 APPROVE: 계산식/OS reader/parser·예외·프로세스 종료와 58개 case 보존, static API 및 buildSrc Kotlin 설정을 확인했다. `git diff --check` 통과, 소유 테스트 worker 없음 확인. 노트와 owned temp root를 제거했다.
|
||||
- P6에서 전체 앱 테스트나 실제 Jenkins/AWS 실행은 수행하지 않았다. commit/push도 수행하지 않았다. 기존 P5의 비율 정책과 앱 Kotlin 1.6.21은 유지했다.
|
||||
|
||||
## P7: Linux MemAvailable와 JDK 인식 cgroup 상한
|
||||
- 승인된 수정 범위: `buildSrc/src/main/kotlin/buildlogic/TestHeapPolicy.kt`, Linux parser/resolver 회귀 테스트, 실행 가이드와 기존 작업 문서. 앱 테스트/운영 로직/힙 비율/cache/fork/parallel/commit/push는 변경하지 않는다.
|
||||
- 관측: 실제 Jenkins는 가용 1315MiB → 힙 493MiB를 선택했고 AdminMemberServiceTest 실행 중 OOM이 발생했다. 최초 OOM 세부 메시지와 실제 MemAvailable/cgroup 원본은 아직 제공되지 않아 원격 자원 여유량·전체 성공을 추정하지 않는다.
|
||||
- Java17 OpenJDK 소스에서 컨테이너 인식 시 total은 유효 제한, free는 제한-사용량이며 미인식 시 host 지표로 돌아감을 확인했다. 따라서 host MemAvailable와 JVM free의 min을 무조건 취하지 않고, JVM total < host MemTotal인 경우에만 제한을 적용한다.
|
||||
- [x] MemFree는 작고 MemAvailable는 큰 host fixture 및 quota가 더 작은 fixture를 기존 free-only 동작에서 RED로 확인.
|
||||
- [x] MemTotal/MemAvailable kB 파싱과 quota resolver 구현. 누락·중복·잘못된 단위/숫자/overflow·관측 실패 경계를 검증.
|
||||
- [x] 기존 58개 정책/OS 테스트와 새 Linux 테스트 GREEN, Kotlin lint 및 root 연결 검증.
|
||||
- [x] 단일 gate 리뷰, 사용자 진단 로그/제약 문서, 소유 temp 정리.
|
||||
- fixture 기반 Linux 검증과 실제 macOS Gradle 연결 결과를 실제 Jenkins/AWS 실행과 구분한다. JVM이 인식하지 못한 cgroup을 완전히 탐지한다고 주장하지 않는다.
|
||||
- RED: Linux 분기를 분리하되 기존 JVM free-only 반환을 유지한 상태에서 `./gradlew --no-daemon --offline -p buildSrc test --tests 'buildlogic.*' --console=plain` 실행. exit 1/16초, 86개 중 새 Linux 회귀 24개 실패. 기존 58개는 유지됐다. Host MemAvailable 사용·컨테이너/host pressure cap·잘못된 proc 카운터 거부의 누락을 확인했다.
|
||||
- 구현은 Linux의 MemTotal/MemAvailable만 엄격하게 kB 단위로 파싱하고, JVM total이 host total보다 작을 때만 JVM free/total로 상한한다. quota 여유 0을 host 값으로 덮지 않는다. 실제 Linux 실행 시 JVM total/free/effective available 진단 로그를 남긴다.
|
||||
- GREEN: `./gradlew --no-daemon --offline -p buildSrc test --tests 'buildlogic.*' ktlintCheck --console=plain`, exit 0/33초. 기존 58개와 Linux 28개를 합친 86개 통과, buildSrc script/main/test lint 통과. Host MemFree=1315MiB지만 MemAvailable=10GiB인 테스트 fixture는 10GiB를 선택해 힙 3840MiB를 계산한다. 이는 실제 Jenkins의 MemAvailable 측정값이 아니다.
|
||||
- root 연결 확인: `./gradlew --no-daemon --offline help ktlintKotlinScriptCheck --console=plain`, exit 0/35초. 공개 API를 참조하는 root Kotlin DSL과 buildSrc classpath 구성이 정상 로딩되고 root script lint가 통과했다. root 앱 테스트/worker를 실행한 검증과 구분한다.
|
||||
- 사용자 요청에 따라 실행 가이드에 Jenkins `clean build` 명령을 기록했다. 기존 Gradle JVM 2GB/Metaspace768MB와 worker1은 유지하고 `--no-parallel`, `--console=plain`만 명시적으로 추가한다. 테스트 heap은 코드가 산정하며 별도 미구현 CLI 옵션을 제시하지 않는다.
|
||||
- XML로 기존 정책 58개와 Linux 회귀 28개 모두 failures/errors/skipped 0을 확인했다. `git diff --check` 통과, 소유 테스트 worker 없음 확인. 임시 노트·owned root는 제거하며 기존 Gradle/IDE 프로세스는 건드리지 않는다.
|
||||
- 독립 P7 리뷰 APPROVE: Linux kB 파싱, recognized quota/host pressure 제한, zero 보존, 기존 비율 정책 유지와 원격 미검증 한계를 확인했다. 노트·owned root 삭제와 부재 확인 완료. commit/push는 수행하지 않았다.
|
||||
|
||||
## P8: worker 재시작 비용 조정
|
||||
- 사용자 관측: Jenkins `available estimate=5152 MiB, workers=1, maxHeap=1932 MiB`, OOM 없음, 약 두 배 느림. 로컬에서도 비슷한 지연을 보고했다.
|
||||
- Oracle 권고에 따라 먼저 `forkEvery=50→100`만 비교한다. cache4/parallel1/힙 비율은 그대로다. 무제한 재사용은 이전 4GiB 포화 증거 때문에 사용하지 않는다.
|
||||
- Gradle8.1.1은 JUnit Platform의 실제 실행 테스트 수와 별도로 전달된 class candidate를 fork 카운터에 반영하므로 필터 실행에도 빈 worker가 생길 수 있다. 테스트 파일명 include로 후보를 임의 제외하지 않는다.
|
||||
- [x] 현재 설정의 동일 focused 기준 실행/메모리/worker 비용 확보.
|
||||
- [x] 교체 간격100만 적용하고 같은 1932MiB 조건으로 비교. 테스트 누락·실패·OOM 없어야 한다.
|
||||
- [x] 이번 실험 채택 기준: worker 구간 10% 이상 단축, 최대 GC 후 힙 Xmx80% 이하, GC pause 비율5% 이하. 이 수치는 실험 판정 기준이지 보편적 보장은 아니다.
|
||||
- [x] 필요 시에만 힙 비율을 별도 단계로 검토. 압박 근거가 없으면 확대하지 않는다.
|
||||
- [x] 단일 리뷰, 측정 한계/실행 명령 기록, owned 자원 정리.
|
||||
- 비교 범위: MainContentAllEndToEndTest, ContentOverviewEndToEndTest, ContentSeriesBannerServiceIntegrationTest, AdminTranslationSelectionContentsHttpIntegrationTest, AdminMemberServiceTest. 기존 25개에 문제 보고된 관리자 회원 테스트7개를 포함한다.
|
||||
- 임시 init script는 root의 기존 doFirst 예산 산정 뒤 QA용 힙1932m을 지정한다. 실제 worker 실행 인자/GC MaxCapacity로 적용을 확인한다. 배포할 기본 힙 설정은 바꾸지 않으며 script는 종료 시 제거한다.
|
||||
- 컴파일 비용은 전체 shell 시간과 별도로 기록하고, 성능 비교는 worker 첫 시작~마지막 종료 구간을 사용한다. 전체 suite 자동 실행 대신 직접 영향 범위 focused 검증을 수행한다. Jenkins 실제 전체 비교는 사용자 실행으로 남긴다.
|
||||
|
||||
### P8 측정 기록
|
||||
- baseline 명령: `./gradlew --no-daemon --offline --max-workers=1 -I /var/folders/yh/8xsbvpsj5wg2qnxzxdp11_gm0000gn/T/opencode/fork-speed.Uj34CC/jenkins-heap.gradle test --tests '*MainContentAllEndToEndTest' --tests '*ContentOverviewEndToEndTest' --tests '*ContentSeriesBannerServiceIntegrationTest' --tests '*AdminTranslationSelectionContentsHttpIntegrationTest' --tests '*AdminMemberServiceTest' --console=plain`.
|
||||
- `*AdminMemberServiceTest`는 CreatorAdminMemberServiceTest도 포함하여 실제 비교 범위는 6클래스/33개다. 동일 패턴을 그대로 유지해 전후 테스트 집합을 바꾸지 않는다.
|
||||
- fork50 baseline: exit 0, shell 652초(기존 Kotlin/KAPT 재컴파일 포함). QA override가 실제 GC MaxCapacity 1932MiB로 적용됨을 확인했다. 33 tests/0 failures, Spring 시작6회.
|
||||
- baseline worker PID 91319,91435,91443,91587,91596,91605,91613,91750,91759,91866,91874,91882,91891. worker 구간232.828초, GC pause2.695초(1.157%), Full GC0, 최대 GC 후 힙339MiB(17.547% Xmx). 모든 worker heap exit 기록이 있다.
|
||||
- root `forkEvery`만 100으로 변경하여 다음 측정을 수행한다. 기본 힙 산정·캐시4·parallel1은 변경하지 않는다. 기존 H2 `SKIP LOCKED` 스케줄러 오류와 종료 중 Redis 재연결 경고가 baseline에서도 관측됐으며, 이번 설정 비교를 위해 숨기거나 별도 운영 로직을 수정하지 않는다.
|
||||
- fork100 결과: 같은 1932MiB/동일6클래스33개 모두 통과. shell296초(컴파일 UP-TO-DATE)와 별도로 worker구간255.806초. worker7개지만 실제 Spring context를 띄운 worker는 여전히4개, 시작6회였다. GC pause2.859초(1.118%), FullGC0, 최대 GC 후 힙329MiB(17.029%). baseline보다 빠르지 않아 100은 채택하지 않는다. shell652→296초 차이는 재컴파일 포함 여부가 달라 최적화 효과로 사용하지 않는다.
|
||||
- 다음 실험은 fork200이다. 100은 빈 worker만 줄이고 실제 Spring 기동 그룹을 합치지 못했으므로, bounded 간격을 한 단계 늘려 실제 기동 재사용 효과를 확인한다. baseline50과 동일 테스트·힙·cache·parallel 및 기존 채택 기준을 유지한다. GC 압박이 없어 힙 비율이나 cache 크기는 올리지 않는다. 이것을 전체 Jenkins의 안전성 보장으로 확대하지 않는다.
|
||||
- fork200 결과: 33/33 통과, shell242초, worker4개(실제 Spring기동3개), worker구간213.198초. GC pause2.475초(1.161%), FullGC0, 최대 GC 후434MiB(22.464%). baseline 대비 약8.43% 단축으로10% 채택 기준에는 못 미친다. 테스트 집합과1932MiB cap은 동일하다.
|
||||
- 마지막 교체 간격 후보로 fork300을 비교한다. 앞선 그룹 재사용 효과가 실제 기동 worker수에서 확인됐고 메모리 압박은 없어, 힙/cache 확대 없이 기동 그룹을 추가로 합치는 실험이다. 여전히 bounded이며 같은 기준을 적용한다. 300도 기준에 못 미치면 이번 간격 변경은 되돌리고 측정된 한계를 보고한다.
|
||||
- fork300 결과: exit 0, shell204초, 동일33개 통과. worker3개(실제 Spring기동2개), worker구간181.903초. GC pause2.095초(1.152%), FullGC0, 최대 GC 후472MiB(24.431%). 모든 worker MaxCapacity1932MiB와 heap exit를 확인했다. baseline 대비 worker구간21.87% 단축으로 이번 focused 채택 기준을 충족했다.
|
||||
- fork300을 채택하고 힙 산정·cache4·parallel1은 그대로 유지한다. 메모리 압박이 관측되지 않았으므로 힙60% 확대 실험은 하지 않는다. 기존 모든33개 case와 Spring 시작6회를 유지했고 파일 include/exclude나 테스트 삭제를 추가하지 않았다.
|
||||
- 비교는 동일 Mac/JDK/CLI/heap에 대한 순차 단일 실행이다. 전체 shell652→204초에는 최초 컴파일 여부 차이가 있으므로 이 차이를 성능 향상으로 제시하지 않는다. worker구간의 관측 개선도 실제 Jenkins 전체 suite 또는 통계적 반복 성능을 보장하지 않는다.
|
||||
|
||||
| forkEvery | 테스트 | worker 수 | worker 구간 | GC pause 비중 | 최대 GC 후 힙 | Full GC |
|
||||
|---:|---:|---:|---:|---:|---:|---:|
|
||||
| 50 | 33 PASS | 13 | 232.828초 | 1.157% | 339MiB | 0 |
|
||||
| 100 | 33 PASS | 7 | 255.806초 | 1.118% | 329MiB | 0 |
|
||||
| 200 | 33 PASS | 4 | 213.198초 | 1.161% | 434MiB | 0 |
|
||||
| 300 | 33 PASS | 3 | 181.903초 | 1.152% | 472MiB | 0 |
|
||||
|
||||
- 최종 설정의 `./gradlew --no-daemon --offline ktlintKotlinScriptCheck --console=plain` exit 0/11초. 전후 측정에 사용한 임시1932m override는 배포 코드에 포함하지 않는다.
|
||||
- 독립 P8 gate APPROVE. 기능 diff 한 줄, 네 실행 GC 로그의 heap/worker/시간/정상 종료와 최종 XML 6클래스33개 통과를 대조했다. 21.87%는 이 로컬 focused 단일 비교의 관측값이며, 실제 Jenkins 전체 suite의 속도/OOM 또는 보편적 향상률로 주장하지 않는다.
|
||||
- `git diff --check` 통과, 소유 테스트 worker 없음 확인. 임시1932m init script와 노트·owned root를 삭제한다. 기본 힙 산정은 기존 정책 그대로이며 commit/push는 수행하지 않았다.
|
||||
|
||||
## 커밋 전 검증 (2026-11-19)
|
||||
- 사용자 `/commit-with-validation` 요청으로 P5/P6 변경을 커밋한다.
|
||||
- `./gradlew --no-daemon --offline -p buildSrc test --tests 'buildlogic.TestHeapPolicyTest' --rerun ktlintCheck --console=plain` exit 0/9초. 정책 테스트를 재실행해 XML의 58 tests/0 failures/0 errors/0 skipped를 확인했다. buildSrc lint는 UP-TO-DATE였다.
|
||||
- 이번 커밋 검증에서 root focused test와 실제 Jenkins/AWS 실행은 반복하지 않았다. 전체 앱 테스트도 미실행이며 사용자 실행 명령은 `./gradlew test`다.
|
||||
|
||||
## P7 커밋 전 검증 (2026-11-19)
|
||||
- 사용자 `/commit-with-validation` 요청으로 Linux 메모리 관측 변경과 관련 문서를 커밋한다.
|
||||
- `./gradlew --no-daemon --offline -p buildSrc test --tests 'buildlogic.*' --rerun ktlintCheck --console=plain` exit 0/8초. XML에서 기존 정책 58개와 Linux 회귀 28개, 총 86개 tests/0 failures/0 errors/0 skipped를 확인했다. buildSrc lint는 UP-TO-DATE였다.
|
||||
- `git diff --check` 통과. 실제 Jenkins/Linux 환경 실행과 전체 앱 테스트는 미실행이며 사용자 전체 테스트 명령은 `./gradlew test`다.
|
||||
|
||||
## P8 커밋 전 검증 (2026-11-19)
|
||||
- 사용자 `/commit-with-validation` 요청으로 worker 교체 간격 변경과 관련 문서를 커밋한다.
|
||||
- `./gradlew --no-daemon --offline ktlintKotlinScriptCheck --console=plain` exit 0/9초, 모든 task는 UP-TO-DATE였다. `git diff --check` 통과.
|
||||
- 기존 root 테스트 XML 6개에서 총 33 tests/0 failures/0 errors/0 skipped를 확인했다. 이번 커밋 검증에서는 focused 성능 비교를 반복하지 않았다.
|
||||
- 실제 Jenkins 실행과 전체 앱 테스트는 미실행이며 사용자 전체 테스트 명령은 `./gradlew test`다.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# 번역 및 관리자 오디오 테스트 수정
|
||||
|
||||
- 작성일: 2026-11-18
|
||||
- 상태: P4 자동 힙 구현·51개 경계 테스트·실제 worker/부족 예산 검증·리뷰 승인·정리 완료. P4 후 전체 재실행은 미수행.
|
||||
- 상태: P8 worker 간격 조정·동일 힙 focused 비교·lint·리뷰 승인·정리 완료. 실제 Jenkins와 전체 suite는 P8 후 미실행.
|
||||
- 구현 계획: [plan-task.md](plan-task.md)
|
||||
|
||||
## 목표와 범위
|
||||
@@ -37,3 +37,26 @@
|
||||
- OS의 현재 메모리 관측값에 안전 여유와 JVM 힙 외 메모리 예산을 남기고 동시 worker 수로 나눈다. 기존에 검증한 4GiB를 보수적 실행 하한으로 유지하며, 하한 미달 또는 유효한 관측 불가 시 worker 시작 전에 이유를 알리고 중단한다. 하한은 수학적으로 입증된 최소 필요량이라는 뜻이 아니다.
|
||||
- macOS JDK의 free-only 값은 전체 가용량이 아니므로 회수 가능한 메모리 추정 규칙을 출처와 함께 명시한다. 실행 도중 가용량 변화에 따른 실시간 heap 재조정이나 무제한 할당은 제외한다.
|
||||
- 기존 cache 4개, 50클래스 worker 교체, 동시 worker 1개는 유지한다. 운영 코드 변경, commit/push는 제외한다.
|
||||
|
||||
## 추가 승인: 고정 하한과 고정 예약량 제거
|
||||
- Jenkins가 보고한 `availableBytes=2460004352`를 4GiB 하한 때문에 거부한 뒤, 사용자가 하한도 고정하지 말고 현재 관측값으로 결정하도록 승인했다.
|
||||
- 4GiB 정책 하한과 worker당 고정 1GiB 예약을 제거한다. 전체 관측값의 50%를 worker에 배분하고 그 예산의 25%를 힙 외 용도로 남겨, 나머지 75%를 힙 상한으로 사용한다. worker 수와 MiB 내림을 유지한다.
|
||||
- 정책상의 최소 힙을 임의로 올려 할당하지 않는다. 현재 JDK가 실행 자체를 거부하는 1MiB 이하만 명시적으로 거부한다. 이는 앱 테스트의 필요 힙을 보장하는 하한이 아니다.
|
||||
- OS 관측 구현·기존 cache/fork/parallel 설정은 유지한다. Linux MemAvailable/cgroup 관측 변경, 운영 코드·commit·push는 이번 범위에 포함하지 않는다.
|
||||
|
||||
## 추가 승인: buildSrc Kotlin 통일
|
||||
- 사용자가 힙 정책과 테스트를 프로젝트 관례에 맞게 Kotlin으로 통일하도록 승인했다.
|
||||
- Java helper/test를 Kotlin 소스로 이동하고 중복 Java 파일을 제거한다. 현재 P5 계산식·OS 관측·오류·자원 정리와 58개 테스트 케이스를 보존한다.
|
||||
- buildSrc에는 Gradle 8.1.1에 맞는 `kotlin-dsl`을 적용하고 Java 17/JUnit 5.8.2를 유지한다. 앱의 Kotlin 1.6.21 버전과 운영 코드, root Test 정책은 변경하지 않는다.
|
||||
- public static 호출 호환성과 실제 루트 Gradle 연결을 검증한다. commit/push와 전체 앱 suite 자동 실행은 제외한다.
|
||||
|
||||
## 추가 승인: Linux 가용 메모리 관측 보정
|
||||
- Jenkins에서 `available estimate=1315 MiB, maxHeap=493 MiB` 선택 뒤 실제 OOM이 보고됐다. 사용자가 Linux MemAvailable와 cgroup 제한을 반영하는 수정에 동의했다.
|
||||
- Linux는 `/proc/meminfo`의 MemAvailable를 사용한다. JDK가 보고한 total memory가 proc MemTotal보다 작으면 JDK가 인식한 제한으로 판단하고, 그 free memory와 total memory를 넘지 않도록 가용량을 제한한다.
|
||||
- cgroup v1/v2 파싱을 새로 만들지 않고 Java 17의 컨테이너 인식 API를 재사용한다. `UseContainerSupport` 비활성화·미지원/발견 실패·일부 상위 계층 제한은 JDK 인식 범위를 벗어날 수 있음을 명시한다.
|
||||
- 고정 4GiB 하한을 복원하거나 힙 비율·캐시·worker 정책을 변경하지 않는다. 작은 실제 예산에서도 모든 테스트가 성공한다는 보장은 하지 않는다. 실제 Jenkins 성공 여부는 원격 재실행 전까지 미검증이다.
|
||||
|
||||
## 추가 승인: 안정성을 유지한 실행 속도 설정 조정
|
||||
- 사용자가 Jenkins와 로컬에서 약 두 배 느려졌다고 보고하고 속도 설정 수정을 승인했다. Jenkins는 가용 5152MiB/worker1/힙1932MiB를 보고하며 OOM은 없다고 확인했다.
|
||||
- 첫 실험은 worker 교체 간격 50→100만 변경한다. 캐시4·동시worker1·힙 산정은 유지해 효과를 분리한다. 단일 focused 비교로 실제 Jenkins 전체 속도를 보장하지 않는다.
|
||||
- 기존 테스트 누락 없이 동일 범위와 실제 Jenkins 힙 1932MiB를 맞춘 로컬 비교를 수행한다. 메모리 압박이 확인될 때만 별도 힙 비율 실험을 검토한다. 무제한 JVM 재사용이나 근거 없는 병렬 확대는 제외한다.
|
||||
|
||||
@@ -46,14 +46,36 @@
|
||||
|
||||
## 테스트 메모리와 진행 진단
|
||||
- IntelliJ의 `Build, Execution, Deployment > Build Tools > Gradle > Run tests using`을 `Gradle`로 맞추면 CLI와 같은 테스트 JVM 설정을 사용한다. IDE 자체 JUnit runner는 Gradle의 heap/worker 설정을 적용하지 않는다.
|
||||
- 테스트 JVM heap은 Test task 실행 직전에 가용 메모리로 계산한다. 가용 추정의 50%를 유효 동시 worker 수(`min(maxParallelForks, maxWorkers)`)로 나누고 worker마다 힙 외 1GiB를 남긴 뒤 MiB 단위로 내린 값을 명시적 `maxHeapSize`로 전달한다. 계산값이 4GiB 미만이면 올려 할당하지 않고 worker 시작 전에 실패한다. 4GiB는 기존 검증을 유지하는 보수적 실행 하한이며, 실제 최소 필요량을 증명한 수치는 아니다.
|
||||
- macOS 가용 추정은 `vm_stat`의 `(Pages free + Pages inactive) × page size`이며 speculative/file-backed를 별도로 더하지 않는다. 다른 OS는 JDK의 free-memory 관측값을 보수적으로 사용하므로 회수 가능한 캐시를 충분히 반영하지 못할 수 있다. 가용 추정은 OS의 할당 보장이 아니며 다른 앱의 이후 사용량도 예측하지 못한다.
|
||||
- 테스트 JVM heap은 Test task 실행 직전에 가용 메모리로 계산한다. 가용 추정의 50%를 유효 동시 worker 수(`min(maxParallelForks, maxWorkers)`)로 나누고, 그 worker 예산의 25%를 힙 외 용도로 남긴다. 나머지 75%를 MiB 단위로 내려 명시적 `maxHeapSize`로 전달한다. 고정 4GiB 정책 하한이나 고정 1GiB 예약은 사용하지 않는다. 단, JVM 실행 자체가 불가능한 2MiB 미만 결과는 상향 보정하지 않고 명시적으로 거부한다.
|
||||
- macOS 가용 추정은 `vm_stat`의 `(Pages free + Pages inactive) × page size`이며 speculative/file-backed를 별도로 더하지 않는다. Linux는 `/proc/meminfo`의 `MemAvailable`을 사용해 회수 가능한 메모리를 반영한다. `MemTotal`과 `MemAvailable`은 kB(1024 bytes)로 읽고 잘못되거나 누락된 값은 추정으로 대체하지 않는다.
|
||||
- Linux에서 JDK의 total memory가 host `MemTotal`보다 작으면 JDK가 인식한 더 작은 제한으로 판단한다. 이 경우에만 host `MemAvailable`, JDK free memory, JDK total memory 중 가장 작은 값을 사용한다. cgroup v1/v2는 Java 17의 컨테이너 인식에 의존하며, `UseContainerSupport` 비활성화·발견 실패·미지원 구성이나 JDK가 인식하지 못한 상위 제한까지 탐지한다고 보장하지 않는다.
|
||||
- macOS/Linux 외에는 JDK의 free-memory 값을 보수적으로 사용한다. 모든 관측은 시작 시점의 추정이며 이후 사용량 변화나 앱 테스트에 충분한 메모리를 보장하지 않는다.
|
||||
- 콘솔의 `Test heap:`에서 관측값·유효 worker 수·선택한 상한을 확인한다. task 시작 때 한 번 계산하며 교체된 worker도 동일한 상한을 사용한다. 메모리 부족 오류가 나면 다른 프로그램/중복 테스트를 정리한 뒤 다시 실행한다. 기존 `maxHeapSize`만 지워 Gradle 기본 512MB로 돌아가거나, 비율 옵션만 추가하는 방식은 사용하지 않는다.
|
||||
- 동시 worker 1개, Spring context 캐시 최대 4개, 50개 테스트 클래스마다 worker 교체는 유지한다. 클래스 수 기준이므로 단일 클래스의 과도한 사용까지 방지하지는 않는다. Gradle daemon heap과 테스트 worker heap은 별개다. 같은 저장소의 전체 테스트를 IDE와 CLI/에이전트에서 동시에 시작하지 않는다.
|
||||
- Linux는 `Test memory (Linux):`에 JVM total/free와 최종 가용량도 기록한다. Jenkins 메모리 문제를 조사할 때 이 줄과 `Test heap:`, 최초 OOM 전체 메시지를 함께 확인한다. 전체 빌드 명령의 `org.gradle.jvmargs`는 Gradle JVM 설정이며 테스트 worker heap과 별개다.
|
||||
- 예를 들어 관측값 2,460,004,352 bytes와 worker 1개는 879MiB 힙을 선택한다. 4GiB 미만이라는 이유만으로 중단하지 않지만, 선택된 예산이 앱 테스트의 실제 메모리 요구량보다 작으면 JVM에서 OOM이 발생할 수 있다. 계산 성공을 전체 테스트 통과 보장으로 해석하지 않는다.
|
||||
- 동시 worker 1개, Spring context 캐시 최대 4개, `forkEvery=300`을 사용한다. Gradle이 처리하는 class candidate 수 기준이므로 실제 테스트 개수와 같지 않으며, JUnit Platform 필터 실행에서도 빈 worker가 생길 수 있다. 단일 클래스의 과도한 메모리 사용까지 방지하지는 않는다. Gradle daemon heap과 테스트 worker heap은 별개다. 같은 저장소의 전체 테스트를 IDE와 CLI/에이전트에서 동시에 시작하지 않는다.
|
||||
- 실행 콘솔의 `Test class:`는 클래스 시작 위치이며 완료 또는 성공 표시가 아니다. 최종 종료 코드와 `build/test-results/test/`의 해당 실행 XML을 함께 확인한다.
|
||||
- GC 로그는 `build/test-gc/<task 이름>/gc-<PID>.log`에 기록한다. PID별 10MB 파일과 회전 로그 최대 3개를 사용한다. 오래된 실행 로그는 조사 후 정리한다.
|
||||
- 후반에 진행이 멈추면 해당 worker PID의 `jstat -gcutil <PID>`와 GC 로그를 확인한다. Old 사용률이 높고 Full GC 시간만 증가하는 상태에서는 실행 제한만 늘리지 않는다. 타인이 시작한 worker는 승인 없이 종료하지 않는다.
|
||||
- 힙 예산 build logic를 변경하면 `./gradlew --no-daemon -p buildSrc test --tests 'buildlogic.TestHeapPolicyTest'`로 산정·파싱 경계를 검증한다. 이 테스트는 애플리케이션의 root `test`와 별도이며, 일반 root 실행에서 buildSrc 컴파일만 됐다고 테스트까지 통과한 것으로 보지 않는다.
|
||||
- 힙 예산 build logic를 변경하면 `./gradlew --no-daemon -p buildSrc test --tests 'buildlogic.*'`로 산정·OS 파싱·Linux/container 경계를 검증한다. 이 테스트는 애플리케이션의 root `test`와 별도이며, 일반 root 실행에서 buildSrc 컴파일만 됐다고 테스트까지 통과한 것으로 보지 않는다.
|
||||
- 힙 정책과 테스트는 `buildSrc/src/main/kotlin/buildlogic/TestHeapPolicy.kt`, `buildSrc/src/test/kotlin/buildlogic/TestHeapPolicyTest.kt`에 둔다. buildSrc는 Gradle 버전에 맞는 `kotlin-dsl`과 Java 17 toolchain을 사용하며 앱의 Kotlin 버전과 별도로 관리한다. 해당 Kotlin 소스의 포맷 검사는 `./gradlew --no-daemon -p buildSrc ktlintCheck`로 실행한다.
|
||||
|
||||
## Jenkins 전체 빌드 명령
|
||||
수정된 build logic가 Jenkins workspace에 반영된 뒤 아래 명령을 사용한다. 테스트를 생략하지 않으며, Gradle JVM의 2GB 한도와 테스트 worker의 자동 힙 산정은 별개다.
|
||||
|
||||
```bash
|
||||
./gradlew clean build \
|
||||
--no-daemon \
|
||||
--no-parallel \
|
||||
--max-workers=1 \
|
||||
--console=plain \
|
||||
--stacktrace \
|
||||
'-Dorg.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=768m -Dfile.encoding=UTF-8'
|
||||
```
|
||||
|
||||
별도의 테스트 heap 옵션은 필요하지 않다. Linux에서는 `Test memory (Linux):`와 `Test heap:` 두 로그를 함께 확인한다. 이 명령은 Jenkins/사용자의 전체 검증용이며 에이전트가 자동 실행하는 명령이 아니다.
|
||||
|
||||
빌드 시간이 길면 같은 명령에 `--profile`을 추가해 `build/reports/profile/`에서 컴파일과 테스트 시간을 구분한다. `forkEvery=300`은 1932MiB 힙에서 관련 33개 테스트의 로컬 비교를 거쳐 적용했으며, 실제 Jenkins 전체 suite의 시간·OOM 여부까지 보장한 값은 아니다. 재시작 간격을 추가로 늘리거나 힙/캐시/병렬 수를 함께 바꾸기 전에 해당 환경의 GC와 실행시간을 비교한다.
|
||||
|
||||
## AWS 의존성 확인
|
||||
|
||||
|
||||
Reference in New Issue
Block a user