Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .Rbuildignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,6 @@
^\.jules(/.*)?$
^\.trivyignore\.yaml$
^trivy\.yaml$
^test_dummy\.R$
^test_validation\.R$
^\.semgrepignore$
51 changes: 39 additions & 12 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
@@ -1,18 +1,45 @@
# Bolt Journal

## 2024-07-04 - R 언어에서 루프 내 데이터 프레임 탐색 병목 최적화
**Learning:** R에서 루프를 돌면서 매번 데이터 프레임을 서브셋팅(subsetting)하는 작업은 복사 오버헤드로 인해 매우 느려질 수 있습니다. 특히 공통 문항 수가 많아질 경우 O(N^2)의 비효율을 초래합니다.
**Action:** 루프 내에서 수행하던 데이터 프레임 조회를 루프 외부에서 한 번에 `as.character(unlist(...))`로 처리하는 벡터 연산으로 변경하여 타입 변환 없이 O(1) 수준으로 성능을 크게 향상시킬 수 있습니다.

**Performance Issue:** `which(df$column == val)`을 루프 내부에서 사용할 경우
매 반복마다 O(N)의 선형 검색이 발생합니다.
**Learning:** `split(seq_len(nrow(df)), df$column)`을 루프 외부에서 미리 계산하여
사용하면 O(1) 리스트 조회를 통해 획기적으로 탐색 시간을 줄일 수 있습니다.

## 2024-07-07 - R 언어에서 데이터 프레임의 특정 항목 탐색을 캐싱하여 O(N) 검색 병목 최적화
**Learning:** R에서 반복문 내부에서 특정 조건을 만족하는 데이터의 위치를 찾기 위해 `which()`를 여러 번 반복 호출하는 것은 O(N) 시간 복잡도를 가져 매번 불필요한 배열 스캔을 유발합니다. 이는 루프의 반복 횟수가 많고, 탐색해야할 데이터가 클 수록 성능 저하의 주 원인이 됩니다.
**Action:** 조건에 맞는 인덱스를 최초 탐색 시 변수에 캐싱(`newIdx`, `oldIdx` 등)하여 저장하고 이후 동일한 데이터 접근 시 캐싱된 인덱스를 사용함으로써 O(1) 수준으로 성능을 향상시킬 수 있습니다. 추가로 스칼라 값에 대한 불필요한 `paste0()` 함수 호출을 제거하여 오버헤드를 줄입니다.

**Performance Issue:** 데이터 프레임 행 필터링이나 열 검색 시 동일한 항목에 대해
반복적으로 인덱싱 연산(`df$col`)을 수행하면 불필요한 연산 오버헤드가 발생합니다.
**Learning:** 반복문 시작 전 관심 있는 열 데이터(`lookup_col <- df$col`)를 변수에
캐싱하고 루프 내부에서는 해당 변수를 조회하여 반복적인 인덱싱 비용을 방지해야 합니다.

## 2024-07-08 - R 언어에서 루프 내 인덱스 검색(which) O(N) 병목 최적화
**Learning:** R에서 반복문 내부에서 특정 조건을 만족하는 데이터의 위치를 찾기 위해 `which()`를 여러 번 호출하면 매번 O(N)의 선형 탐색(linear scan)이 발생하여 데이터 크기가 클수록 성능이 크게 저하됩니다. 또한 `paste0()`를 이용한 불필요한 배열 단위 문자열 생성은 반복문 오버헤드를 가중시킵니다.
**Action:** 조건에 맞는 인덱스를 최초 한 번 `split(seq_len(nrow(df)), df$column)`를 통해 리스트 형태로 캐싱(dictionary lookup)하여 루프 외부에서 O(1) 검색 체계로 만들고, 스칼라 값에 대한 불필요한 `paste0()` 함수 호출을 최적화(`paste(..., collapse=' ')`)하여 오버헤드를 줄입니다.

**Performance Issue:** 다수의 요소에 대해 `which(vector == value)`를 반복 호출하면
O(N * M) 복잡도가 발생하여 벡터 크기가 커질수록 급격한 속도 저하를 일으킵니다.
**Learning:** `which` 호출 대상을 하나씩 검색하는 대신 `%in%`이나 `match()`를 사용하여
검색 자체를 벡터화(vectorize)하고 검색을 루프 외부로 옮겨 O(N + M)으로 최적화해야 합니다.

## 2026-07-11 - R 언어에서 루프 내 벡터 동적 확장 및 조건부 탐색 최적화
**Learning:** R에서 for 루프 내에 동적으로 벡터 크기를 늘리면서 (`vector[i] <- value`) 조건을 검사하는 것은 O(N^2)의 복사 오버헤드(copy-on-modify)를 발생시키며 매 반복마다 `match()` 스캔을 수행하면 성능 저하를 초래합니다.
**Action:** 루프 외부에 벡터화된 `match()`를 한 번만 수행하여 유효한 인덱스를 찾고, 벡터 인덱싱(`vector[idx]`)으로 한 번에 데이터를 추출하여 불필요한 루프 오버헤드 및 동적 메모리 재할당을 방지하여 O(1) 수준으로 성능을 개선해야 합니다.

**Performance Issue:** 반복문 안에서 벡터를 `c(vec, val)`로 동적으로 확장하고,
음수 인덱싱(`-c(which(...))`) 시 매칭되는 항목이 없으면 `integer(0)`로 평가되어
전체 요소를 날려버리는 치명적 성능/논리 오류가 발생할 수 있습니다.
**Learning:** 음수 인덱싱과 결합된 부정적 `which()`나 `grep()` 연쇄 호출 대신
`!grepl()`과 같은 단일 논리형 벡터 마스크를 사용하는 것이 훨씬 빠르고 안전합니다.

## 2024-07-12 - R 언어에서 데이터프레임 서브셋팅 시 불필요한 which() 및 반복 평가 제거
**Learning:** 데이터 프레임의 특정 로우(row)를 변경할 때 `df[which(df$col == "val"), ]`와 같이 `which()`를 사용하면 내부적으로 추가 함수 호출 및 논리 벡터 평가 오버헤드가 발생합니다. 또한, 여러 값을 업데이트하기 위해 동일한 조건식을 연속으로 사용하면 매번 동일한 O(N) 논리 벡터 평가가 중복해서 일어납니다. 불필요한 `paste0("GROUP")` 호출도 오버헤드를 더합니다.
**Action:** `which()`를 생략하고 직접 논리 인덱싱(`df$col == "val"`)을 사용하며, 동일한 조건식을 두 번 이상 연속으로 사용할 경우 해당 논리 벡터를 변수에 캐싱(`idx <- df$col == "val"`)하여 여러 번 재사용함으로써 중복된 O(N) 선형 스캔을 피하고 성능을 최적화해야 합니다. 또한 불필요한 문자열 연산을 제거합니다.

**Performance Issue:** 데이터 프레임 내 동일한 조건(`df$col == val`)으로 값을 할당하거나
추출할 때 매번 `which()`를 감싸거나 조건을 반복 평가하면 O(N) 함수 호출 오버헤드가 지속 발생합니다.
**Learning:** 조건에 대한 논리 인덱스 자체를 변수로 캐싱(`idx <- df$col == val`)하고,
`which()` 없이 직접 논리 인덱싱(`df[idx, ]`)을 수행하여 중복 평가를 O(1)의 읽기로 전환해야 합니다.

## 2025-02-12 - R 언어에서 반복적인 mirt 모델 생성 시 불필요한 데이터프레임 부분집합 추출 최적화
**Learning:** R에서 데이터프레임의 특정 열을 추출하는 작업(`df[cols]`)은 O(N)의 메모리 복사를 수반합니다. `autoFIPC`에서 `mirt` 모델의 파라미터를 설정하거나 호출하는 과정 중에 `newformXDataK[colnames(newFormModel@Data$data)]` 코드가 반복해서 사용되었고, 심지어 `ncol()`을 위해 단순히 개수를 구할 때도 사용되어 불필요한 메모리 할당과 오버헤드를 초래했습니다.
**Action:** 조건문이나 반복문 내부에서 불필요하게 데이터프레임 부분집합 연산이 반복되지 않도록 외부에서 한 번만 `linkedFormData <- newformXDataK[colnames(newFormModel@Data$data)]`로 캐싱(caching)한 뒤, `ncol(linkedFormData)`와 `data = linkedFormData` 형태로 재사용하여 메모리 복사와 O(N) 오버헤드를 방지해야 합니다.

**Performance Issue:** 동일한 전체 데이터프레임과 문항 모수 프레임에 대해 내부 구조를
조작하기 위해 반복적으로 부분 데이터프레임을 생성(예: `df[, cols, drop=FALSE]`)하면 심각한
O(N) 메모리 복사 오버헤드가 발생합니다.
**Learning:** 부분집합 생성이나 데이터 강제 변환 없이 전체 데이터프레임을 참조하며 `intersect`나
문자열 매칭(`cols %in% colnames(df)`)을 통해 필터링 인덱스만 조작하도록 최적화해야 합니다.
16 changes: 12 additions & 4 deletions .jules/palette.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
# Palette Journal

## 2024-06-24 - Pure R Backend Package
**Learning:** The aFIPC repository is a pure R backend package without any frontend web components or UI. Therefore, standard micro-UX enhancements such as ARIA labels, loading states, and CSS styling cannot be applied.
**Action:** Stop and do not create a PR, as no suitable web UX enhancements can be identified.

**Observation:** This repository is an R package for backend analysis (`aFIPC`)
and does not contain any user-facing frontend components or UI/UX surface area.
**Learning:** Do not attempt to add UI enhancements or frontend libraries
(like React, CSS, or shiny components) unless a clear UI layer is established.

## 2026-06-30 - No Frontend Surface
**Learning:** The package contains R calibration code and package metadata, not HTML, React, CSS, or other UI surfaces.
**Action:** Palette tasks should stop after recording that no UX enhancement applies unless a future frontend artifact is introduced.

**Observation:** As a pure computational R backend, attempting to create UI
features is outside the repository scope.
**Learning:** Stop execution immediately and do not generate PRs for UI
enhancements in this codebase to avoid polluting the repository history.
28 changes: 25 additions & 3 deletions .jules/sentinel.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,26 @@
# Sentinel Journal

## 2024-07-12 - Fix missing parameter validations
**Vulnerability:** Unvalidated inputs passed to `if()` statements can cause process crashes (`condition has length > 1`) or unexpected coercion vulnerabilities.
**Learning:** In R, optional boolean parameters that default to `NULL` should be validated using explicit runtime type validation (e.g., `if (!is.null(flag) && (!is.logical(flag) || length(flag) != 1 || is.na(flag)))`).
**Prevention:** Always implement explicit runtime type validation for optional boolean parameters.

**Vulnerability:** Unvalidated inputs passed to `if()` statements can cause
process crashes (`condition has length > 1`) or unexpected coercion
vulnerabilities.
**Learning:** In R, optional boolean parameters that default to `NULL` should
be validated using explicit runtime type validation (e.g.,
`if (!is.null(flag) && (!is.logical(flag) || length(flag) != 1 || is.na(flag)))`).
**Prevention:** Always implement explicit runtime type validation for
optional boolean parameters.

## 2024-08-10 - [사용자 입력 검증 강화 및 정수 오버플로우 방지]

**Vulnerability:** 대화형 프롬프트(`readline()`)에서 사용자의 입력을 검증할
때 `grepl("^[0-9]+$", n)`과 같이 무제한의 숫자를 허용하여 큰 숫자가 입력될
경우 `as.integer()`에서 `NA`를 반환하는 등의 정수 오버플로우 및 강제 변환
취약점이 발생할 위험이 있었습니다.
**Learning:** 기대하는 입력값(예: 1 또는 2)의 범위가 명확함에도
정규표현식 매칭을 너무 광범위하게 허용하는 것은 에러 처리가 되지 않은 상태에서
예상치 못한 형변환 결과를 초래하여 프로세스가 강제 종료될 수 있는 보안
리스크임을 배웠습니다.
**Prevention:** 대화형 프롬프트나 텍스트 기반 입력에서 정수형 변환을 수행하기
전에, 허용 가능한 정확한 값(예: `^[12]$`)에 대해서만 엄격하게 정규식 매칭을
수행하도록 해야 합니다.
6 changes: 3 additions & 3 deletions R/aFIPC.R
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ autoFIPC <-
}
for (attempt in seq_len(3)) {
n <- readline(prompt = "Is it correct? (1: Yes 2: No) : ")
if (grepl("^[0-9]+$", n)) {
if (grepl("^[12]$", n)) {
return(as.integer(n))
}
}
Expand Down Expand Up @@ -171,7 +171,7 @@ autoFIPC <-
readline(
prompt = "Do you want to use default BILOG-MG priors for oldform Data? (1: Yes 2: No) : "
)
if (grepl("^[0-9]+$", n)) {
if (grepl("^[12]$", n)) {
return(as.integer(n))
}
}
Expand Down Expand Up @@ -390,7 +390,7 @@ autoFIPC <-
readline(
prompt = "Do you want to use default BILOG-MG priors for newform Data? (1: Yes 2: No) : "
)
if (grepl("^[0-9]+$", n)) {
if (grepl("^[12]$", n)) {
return(as.integer(n))
}
}
Expand Down
Loading