Skip to content

Commit cf115ba

Browse files
mstrathmanclaude
andcommitted
fix: cap classifier vocab at STUDENT_MAX_CLASS during interning
The student deserializer rejects nclass > 2048, but the trainers did not, so fit()/distill_predict could grow the label (and soft-label) arrays, or even hit SQLITE_NOMEM, before erroring, or register a classifier blob that then failed to load. Add STUDENT_MAX_CLASS (predict-student.h) as the single source for the cap, use it for the three nclass deserializer checks, and reject an oversized vocabulary DURING interning (immediately after each predict0_intern_label) in predict0_train_student and both distill_predict classify loops, plus check nproba before allocating the soft-label arrays. The post-convergence checks are kept as defensive invariants. PREDICT_ERR_SCHEMA throughout. Regression tests over 2049 distinct classes for both fit() and distill_predict. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
1 parent 5f43962 commit cf115ba

6 files changed

Lines changed: 82 additions & 3 deletions

File tree

‎predict-distill.c‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,14 @@ static int distill_train(sqlite3 *db, const char *tq, DistOpts *o,
222222
PREDICT_ERR_OPTIONS);
223223
goto done;
224224
}
225+
/* Cap before allocating proba_col/soft_P so an oversized class set can't
226+
* drive the allocation (STUDENT_MAX_CLASS, predict-student.h). */
227+
if (nproba > STUDENT_MAX_CLASS) {
228+
rc = SQLITE_ERROR;
229+
*errmsg = sqlite3_mprintf("%s: too many classes (%d); the maximum is %d",
230+
PREDICT_ERR_SCHEMA, nproba, STUDENT_MAX_CLASS);
231+
goto done;
232+
}
225233
proba_col = sqlite3_malloc(sizeof(int) * nproba);
226234
if (!proba_col) {
227235
rc = SQLITE_NOMEM;
@@ -403,6 +411,12 @@ static int distill_train(sqlite3 *db, const char *tq, DistOpts *o,
403411
int cl = predict0_intern_label(&labels, &nclass, &nlab_cap, y_true_c[i], &rc);
404412
if (cl < 0)
405413
goto done;
414+
if (nclass > STUDENT_MAX_CLASS) {
415+
rc = SQLITE_ERROR;
416+
*errmsg = sqlite3_mprintf("%s: too many classes (%d); the maximum is %d",
417+
PREDICT_ERR_SCHEMA, nclass, STUDENT_MAX_CLASS);
418+
goto done;
419+
}
406420
y_teach[i] = cl;
407421
} else {
408422
y_teach_r[i] = (f32)y_true_r[i];
@@ -437,6 +451,12 @@ static int distill_train(sqlite3 *db, const char *tq, DistOpts *o,
437451
predict0_intern_label(&labels, &nclass, &nlab_cap, pred ? pred : "", &rc);
438452
if (cl < 0)
439453
goto done;
454+
if (nclass > STUDENT_MAX_CLASS) {
455+
rc = SQLITE_ERROR;
456+
*errmsg = sqlite3_mprintf("%s: too many classes (%d); the maximum is %d",
457+
PREDICT_ERR_SCHEMA, nclass, STUDENT_MAX_CLASS);
458+
goto done;
459+
}
440460
y_teach[ti] = cl;
441461
} else {
442462
y_teach_r[ti] = (f32)sqlite3_column_double(tqs, 0);
@@ -464,6 +484,15 @@ static int distill_train(sqlite3 *db, const char *tq, DistOpts *o,
464484
teacher ? "teacher" : "target column");
465485
goto done;
466486
}
487+
/* Defensive invariant: the interning loops and the soft-label nproba check
488+
* already cap this before any allocation; kept so the bound holds even if
489+
* those paths change. */
490+
if (classify && nclass > STUDENT_MAX_CLASS) {
491+
rc = SQLITE_ERROR;
492+
*errmsg = sqlite3_mprintf("%s: too many classes (%d); the maximum is %d",
493+
PREDICT_ERR_SCHEMA, nclass, STUDENT_MAX_CLASS);
494+
goto done;
495+
}
467496

468497
/* ---- 4. fit the student on the fit split (teacher targets) ---- */
469498
int n_hold = n / 5;

‎predict-student.c‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ static int tree_deserialize(const void *blob, int len, Tree *t, char **errmsg) {
155155
t->nclass = (int)rd_u32(&r);
156156
t->n_nodes = (int)rd_u32(&r);
157157
if (r.err || t->task < 0 || t->task > 1 || t->nfeat <= 0 ||
158-
t->nfeat > TREE_MAX_FEAT || t->nclass < 0 || t->nclass > 2048 ||
158+
t->nfeat > TREE_MAX_FEAT || t->nclass < 0 || t->nclass > STUDENT_MAX_CLASS ||
159159
t->n_nodes <= 0 || t->n_nodes > (1 << 24))
160160
goto bad;
161161

@@ -366,7 +366,7 @@ static int forest_deserialize(const void *blob, int len, Forest *f,
366366
f->lr = rd_f32(&r);
367367
int want_score = f->task == 0 ? f->nclass : 1;
368368
if (r.err || f->task < 0 || f->task > 1 || f->nfeat <= 0 ||
369-
f->nfeat > TREE_MAX_FEAT || f->nclass < 0 || f->nclass > 2048 ||
369+
f->nfeat > TREE_MAX_FEAT || f->nclass < 0 || f->nclass > STUDENT_MAX_CLASS ||
370370
f->n_rounds <= 0 || f->n_rounds > (1 << 20) || f->n_score != want_score ||
371371
f->n_score <= 0)
372372
goto bad;
@@ -570,7 +570,8 @@ static int mlp_deserialize(const void *blob, int len, MLP *m, char **errmsg) {
570570
m->nclass = (int)rd_u32(&r);
571571
if (r.err || m->task < 0 || m->task > 1 || m->nfeat <= 0 ||
572572
m->nfeat > TREE_MAX_FEAT || m->nhid <= 0 || m->nhid > 2048 ||
573-
m->nout <= 0 || m->nout > 2048 || m->nclass < 0 || m->nclass > 2048 ||
573+
m->nout <= 0 || m->nout > 2048 || m->nclass < 0 ||
574+
m->nclass > STUDENT_MAX_CLASS ||
574575
(m->task == 0 && m->nout != m->nclass) || (m->task == 1 && m->nout != 1))
575576
goto bad;
576577
m->mean = sqlite3_malloc(sizeof(f32) * m->nfeat);

‎predict-student.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
#define TREE_MAX_FEAT PREDICT_MAX_FEAT /* alias; see predict-internal.h */
1919
#define FCST_MAX_CONTEXT 4096 /* forecast student: max context length (nfeat) */
2020
#define FCST_MAX_QUANT 64 /* forecast student: max quantile levels */
21+
#define STUDENT_MAX_CLASS 2048 /* tree/gbt/mlp classifier: max distinct classes */
2122
/* Forecast student with a linear skip: the hidden path is a small correction on
2223
* the dominant linear map, so its output is scaled by this. Shared by the
2324
* trainer (train_mlp) and the serving forward (predict0_mlp_forward). */

‎predict-train.c‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -721,6 +721,14 @@ int predict0_train_student(sqlite3 *db, const f32 *X, int n, int nfeat,
721721
int k = predict0_intern_label(&labels, &nclass, &lcap, ylab[i] ? ylab[i] : "", &rc);
722722
if (k < 0)
723723
goto done;
724+
/* Enforce the cap during interning so an oversized vocabulary errors here
725+
* instead of growing the label array (STUDENT_MAX_CLASS, predict-student.h). */
726+
if (nclass > STUDENT_MAX_CLASS) {
727+
rc = SQLITE_ERROR;
728+
*errmsg = sqlite3_mprintf("%s: too many classes (%d); the maximum is %d",
729+
PREDICT_ERR_SCHEMA, nclass, STUDENT_MAX_CLASS);
730+
goto done;
731+
}
724732
y_teach[i] = k;
725733
}
726734
if (nclass < 2) {
@@ -731,6 +739,14 @@ int predict0_train_student(sqlite3 *db, const f32 *X, int n, int nfeat,
731739
PREDICT_ERR_TARGET, nclass);
732740
goto done;
733741
}
742+
/* Defensive invariant: the intern loop already caps this; kept so the bound
743+
* holds even if that path changes. */
744+
if (nclass > STUDENT_MAX_CLASS) {
745+
rc = SQLITE_ERROR;
746+
*errmsg = sqlite3_mprintf("%s: too many classes (%d); the maximum is %d",
747+
PREDICT_ERR_SCHEMA, nclass, STUDENT_MAX_CLASS);
748+
goto done;
749+
}
734750
} else {
735751
y_teach_r = sqlite3_malloc(sizeof(f32) * n);
736752
if (!y_teach_r) {

‎tests/test_distill.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,23 @@ def test_missing_student_id_errors(db):
119119
assert "PREDICT_ERR_OPTIONS" in str(e.value)
120120

121121

122+
def test_distill_rejects_too_many_classes(db):
123+
"""distill_predict must cap the class vocabulary at STUDENT_MAX_CLASS (2048)
124+
before fitting, the same limit the deserializer enforces on load, so it
125+
never registers a student that cannot be reloaded."""
126+
db.execute("CREATE TABLE many(f1 real, f2 real, c integer)")
127+
db.execute(
128+
"INSERT INTO many(f1, f2, c)"
129+
" WITH RECURSIVE s(i) AS (SELECT 0 UNION ALL SELECT i+1 FROM s WHERE i < 2048)"
130+
" SELECT i * 1.0, i * 2.0, i FROM s") # 2049 distinct classes
131+
with pytest.raises(sqlite3.OperationalError) as e:
132+
db.execute(
133+
"SELECT model_id FROM distill_predict('SELECT f1, f2, c FROM many',"
134+
" json_object('target','c','task','classify','student_id','big'))"
135+
).fetchall()
136+
assert "PREDICT_ERR_SCHEMA" in str(e.value)
137+
138+
122139
def test_bad_task_errors(db):
123140
_train_table(db)
124141
with pytest.raises(sqlite3.OperationalError) as e:

‎tests/test_fit.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,3 +145,18 @@ def test_predict_rejects_nonfinite_float_in_blob(db):
145145
with pytest.raises(sqlite3.OperationalError) as e:
146146
db.execute("SELECT predict(?, 2, 20)", (bytes(buf),)).fetchall()
147147
assert "PREDICT_ERR_SCHEMA" in str(e.value)
148+
149+
150+
def test_fit_rejects_too_many_classes(db):
151+
"""The deserializer caps classes at STUDENT_MAX_CLASS (2048); fit() must
152+
reject a larger vocabulary up front rather than register a blob that
153+
predict() can never load."""
154+
db.execute("CREATE TABLE many(f1 real, f2 real, c integer)")
155+
db.execute(
156+
"INSERT INTO many(f1, f2, c)"
157+
" WITH RECURSIVE s(i) AS (SELECT 0 UNION ALL SELECT i+1 FROM s WHERE i < 2048)"
158+
" SELECT i * 1.0, i * 2.0, i FROM s") # 2049 distinct classes
159+
with pytest.raises(sqlite3.OperationalError) as e:
160+
db.execute(
161+
"SELECT fit(f1, f2, c, '{\"task\":\"classify\"}') FROM many").fetchall()
162+
assert "PREDICT_ERR_SCHEMA" in str(e.value)

0 commit comments

Comments
 (0)