{"record":{"id":"f30e845374e4427e","repo":"stanfordnlp/CoreNLP","slug":"could-not-save-model-to-stream","errorCode":null,"errorMessage":"Could not save model to stream!","messagePattern":"Could not save model to stream!","errorType":"console","errorClass":null,"httpStatus":null,"severity":"error","filePath":"src/edu/stanford/nlp/sentiment/SimpleSentiment.java","lineNumber":270,"sourceCode":"        if (useL1) {\n          minimizer.useOWLQN(true, 1 / (sigma * sigma));\n        } else {\n          factory.setSigma(sigma);\n        }\n        return minimizer;\n      });\n    } catch (Exception ignored) {}\n    factory.setSigma(sigma);\n    LinearClassifier<SentimentClass, String> classifier = factory.trainClassifier(dataset);\n\n    // Optionally save the model\n    modelLocation.ifPresent(stream -> {\n      try {\n        ObjectOutputStream oos = new ObjectOutputStream(stream);\n        oos.writeObject(classifier);\n        oos.close();\n      } catch (IOException e) {\n        log.err(\"Could not save model to stream!\");\n      }\n    });\n    endTrack(\"Training\");\n\n    // Evaluate the model\n    forceTrack(\"Evaluating\");\n    factory.setVerbose(false);\n    double sumAccuracy = 0.0;\n    Counter<SentimentClass> sumP = new ClassicCounter<>();\n    Counter<SentimentClass> sumR = new ClassicCounter<>();\n    int numFolds = 4;\n    for (int fold = 0; fold < numFolds; ++fold) {\n      Pair<GeneralDataset<SentimentClass, String>, GeneralDataset<SentimentClass, String>> trainTest = dataset.splitOutFold(fold, numFolds);\n      LinearClassifier<SentimentClass, String> foldClassifier = factory.trainClassifierWithInitialWeights(trainTest.first, classifier);  // convex objective, so this should be OK\n      sumAccuracy += foldClassifier.evaluateAccuracy(trainTest.second);\n      for (SentimentClass label : SentimentClass.values()) {\n        Pair<Double, Double> pr = foldClassifier.evaluatePrecisionAndRecall(trainTest.second, label);\n        sumP.incrementCount(label, pr.first);","sourceCodeStart":252,"sourceCodeEnd":288,"githubUrl":"https://github.com/stanfordnlp/CoreNLP/blob/1b7edd19c4d0d7b1f13a2591425b9b60a0b1af7a/src/edu/stanford/nlp/sentiment/SimpleSentiment.java#L252-L288","documentation":"SimpleSentiment.train serializes the trained classifier to an ObjectOutputStream wrapped around the modelLocation stream when -serializeTo/-serialize model output is provided. If writing or closing the object stream throws IOException, it logs this terse message. The model is not persisted even though training succeeded, so later load attempts will fail with no file.","triggerScenarios":"Within train(), constructing ObjectOutputStream or calling writeObject/close on the stream from modelLocation throws IOException — e.g. unwritable destination path, full disk, stream closed early, or the underlying OutputStream supplier failing.","commonSituations":"Serialize target in a read-only directory; typo'd path in a non-existent directory; disk quota exceeded in CI; running in a container with a read-only filesystem mounting the output path.","solutions":["Check the serialization path: directory exists, file writable, sufficient disk space.","Fix any IOException detail available (enable fuller logging) to distinguish open vs write vs close failures.","Write to a temp file then atomically move it into place to avoid partial model files.","If the stream is provided by a lambda/supplier, ensure it is open and not already consumed/closed before writeObject."],"exampleFix":"// before: directory doesn't exist\njava -cp ... SimpleSentiment -trainPath train.txt -serialize /nonexistent/dir/model.ser\n// after\nmkdir -p models\njava -cp ... SimpleSentiment -trainPath train.txt -serialize models/model.ser","handlingStrategy":"try-catch","validationCode":"Path out = Paths.get(serializeTo);\nif (out.getParent() != null) Files.createDirectories(out.getParent());\nif (!Files.isWritable(out.getParent())) throw new IOException(\"Not writable: \" + out.getParent());","typeGuard":null,"tryCatchPattern":"try (ObjectOutputStream oos = new ObjectOutputStream(Files.newOutputStream(out))) {\n    oos.writeObject(classifier);\n} catch (IOException e) {\n    throw new UncheckedIOException(\"Failed to serialize model to \" + out, e);\n}","preventionTips":["Pre-create the output directory and check writability before training.","Serialize to a temp path and atomically move on success.","Monitor disk space/quota in CI environments.","Always confirm the model file exists and is non-empty after a training run."],"tags":["java","io","serialization","model-persistence"],"backgroundTag":"file-write-failed","analyzedSha":"1b7edd19c4d0d7b1f13a2591425b9b60a0b1af7a","analyzedAt":"2026-09-10T02:24:07.274Z","contentChangedAt":"2026-09-10T02:24:07.274Z","schemaVersion":2},"datasetVersion":"2026-09-17T15:17:12.973Z"}