Commit 90cab30 for stable-diffusion.cpp

commit 90cab303d7a4c0ba9073393a9920f2976c4ad764
Author: leejet <leejet714@gmail.com>
Date:   Fri Dec 4 00:50:07 2026 +0800

    feat(server): support named inputs for DGL jobs (#2508)

diff --git a/docs/dgl.md b/docs/dgl.md
index db89869..8573da1 100644
--- a/docs/dgl.md
+++ b/docs/dgl.md
@@ -1750,7 +1750,9 @@ systems, string bindings can carry native path bytes, including paths that
 cannot be written as UTF-8 source literals. Byte bindings copy the buffers
 into DGL-owned storage, including embedded zero bytes.
 A null byte pointer is valid for an empty buffer. Use `sd_dgl_check` for
-standalone scripts or scripts with tensor parameters.
+standalone scripts or scripts with tensor parameters. Use `sd_dgl_check_inputs`
+to validate source against the names and kinds in an input array before running
+the script. This check needs no context and does not copy input values.

 ```c
 /* bytes and length describe an encoded image read by the host. */
diff --git a/examples/common/common.cpp b/examples/common/common.cpp
index b10e8dc..9d0bbdd 100644
--- a/examples/common/common.cpp
+++ b/examples/common/common.cpp
@@ -1649,16 +1649,15 @@ static bool is_base64(unsigned char c) {
     return std::isalnum(c) || c == '+' || c == '/';
 }

-static std::vector<uint8_t> decode_base64_bytes(const std::string& encoded_string) {
-    int in_len = static_cast<int>(encoded_string.size());
+static std::vector<uint8_t> decode_base64_bytes(std::string_view encoded_string) {
     int i      = 0;
     int j      = 0;
-    int in_    = 0;
+    size_t in_ = 0;
     uint8_t char_array_4[4];
     uint8_t char_array_3[3];
     std::vector<uint8_t> ret;

-    while (in_len-- && encoded_string[in_] != '=' && is_base64(encoded_string[in_])) {
+    while (in_ < encoded_string.size() && encoded_string[in_] != '=' && is_base64(encoded_string[in_])) {
         char_array_4[i++] = encoded_string[in_];
         in_++;
         if (i == 4) {
@@ -1698,6 +1697,24 @@ static std::vector<uint8_t> decode_base64_bytes(const std::string& encoded_strin
     return ret;
 }

+bool decode_base64_bytes_strict(std::string_view encoded, std::vector<uint8_t>& bytes) {
+    if (encoded.size() % 4 != 0)
+        return false;
+    const auto data = encoded.substr(0, encoded.find('='));
+    if (data.find_first_not_of(k_base64_chars) != std::string_view::npos)
+        return false;
+    if (data.size() != encoded.size()) {
+        const auto padding = encoded.substr(data.size());
+        if (padding != "=" && padding != "==")
+            return false;
+        const auto last_digit = k_base64_chars.find(data.back());
+        if (last_digit % (padding.size() == 1 ? 4 : 16) != 0)
+            return false;
+    }
+    bytes = decode_base64_bytes(data);
+    return true;
+}
+
 bool decode_base64_image(const std::string& encoded_input,
                          int target_channels,
                          int expected_width,
diff --git a/examples/common/common.h b/examples/common/common.h
index f505318..2935955 100644
--- a/examples/common/common.h
+++ b/examples/common/common.h
@@ -8,6 +8,7 @@
 #include <functional>
 #include <map>
 #include <string>
+#include <string_view>
 #include <vector>

 #include "log.h"
@@ -115,6 +116,7 @@ struct ArgOptions {

 void add_log_options(ArgOptions& options, sd_log_level_t& level);
 bool parse_options(int argc, const char** argv, const std::vector<ArgOptions>& options_list);
+bool decode_base64_bytes_strict(std::string_view encoded, std::vector<uint8_t>& bytes);
 bool decode_base64_image(const std::string& encoded_input,
                          int target_channels,
                          int expected_width,
diff --git a/examples/server/api.md b/examples/server/api.md
index e6f73d1..b231dfd 100644
--- a/examples/server/api.md
+++ b/examples/server/api.md
@@ -1838,10 +1838,42 @@ uses `./dgl` in the working directory unless `--dgl-dir` is set.
 | GET /sdcpp/v1/dgl/scripts | Returns directory and a list of scripts |
 | GET /sdcpp/v1/dgl/script?name=example.dgl | Returns the script as source |
 | POST /sdcpp/v1/dgl/script | Saves UTF-8 source with the given name. Pass previous_source to update an existing script. A conflict returns HTTP 409. |
-| POST /sdcpp/v1/dgl/jobs | Queues the source string and returns a job ID and `poll_url` with HTTP 202 |
+| POST /sdcpp/v1/dgl/jobs | Queues the source and optional named inputs. Returns a job ID and `poll_url` with HTTP 202. |
 | GET /sdcpp/v1/jobs/{id} | Returns job status and progress, plus any error or result with tensor descriptions and inline encoded media |
 | POST /sdcpp/v1/jobs/{id}/cancel | Cancels a queued job or requests cancellation of a running job |

+Send an `application/json` body with the `source` string and an optional
+`inputs` object. Supply one entry for each parameter in `fn main(...)` and use
+the parameter name as the key. Each entry is an object with `type` and `value`.
+For a script without parameters, omit `inputs` or pass an empty object.
+
+- For `"type": "string"`, `value` is a JSON string. It can be empty and
+  must not contain NUL.
+- For `"type": "bytes"`, `value` is a standard Base64 string with padding
+  where required. The script can decode uploaded media with `image::decode`,
+  `audio::decode`, or `video::decode`.
+
+This request decodes an uploaded PNG and uses a string input to select the
+output format.
+
+```json
+{
+  "source": "fn main(ref, format) { return image::encode(image::decode(ref), format = format) }",
+  "inputs": {
+    "ref": {
+      "type": "bytes",
+      "value": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC"
+    },
+    "format": {"type": "string", "value": "png"}
+  }
+}
+```
+
+Invalid source, missing or unknown input names, invalid input objects,
+incompatible input types, and malformed Base64 return HTTP 400 before the job
+is queued. Errors while running the script, such as invalid image data inside
+a valid Base64 input, appear in the job status.
+
 Failed jobs report `error.code` and `error.message`. When execution reports
 `out_of_memory`, the message includes the memory failure details available
 from the runtime.
diff --git a/examples/server/async_jobs.cpp b/examples/server/async_jobs.cpp
index 5f7c8f7..2b05a9f 100644
--- a/examples/server/async_jobs.cpp
+++ b/examples/server/async_jobs.cpp
@@ -262,6 +262,7 @@ bool cancel_queued_job(AsyncJobManager& manager, AsyncGenerationJob& job) {
     job.model.reset();
     job.request_body = nullptr;
     job.dgl_source.clear();
+    job.dgl_inputs.clear();
     job.cancel_requested.store(true);
     job.status       = AsyncJobStatus::Cancelled;
     job.completed_at = unix_timestamp_now_ms();
@@ -747,21 +748,36 @@ void configure_server_file_access(ServerModels& models, const SDSvrParams& param
         throw std::runtime_error(sd_get_last_error());
 }

+std::vector<sd_dgl_input_t> dgl_input_bindings(const std::vector<DglJobInput>& inputs) {
+    std::vector<sd_dgl_input_t> bindings;
+    bindings.reserve(inputs.size());
+    for (const auto& input : inputs) {
+        sd_dgl_input_t binding{};
+        binding.name = input.name.c_str();
+        if (const auto* text = std::get_if<std::string>(&input.value)) {
+            binding.kind         = SD_DGL_INPUT_STRING;
+            binding.value.string = text->c_str();
+        } else {
+            const auto& bytes   = std::get<std::vector<uint8_t>>(input.value);
+            binding.kind        = SD_DGL_INPUT_BYTES;
+            binding.value.bytes = {bytes.data(), bytes.size()};
+        }
+        bindings.push_back(binding);
+    }
+    return bindings;
+}
+
 static sd_status_t execute_dgl_job(ServerRuntime& runtime,
                                    AsyncGenerationJob& job,
                                    json& result_info,
                                    std::string& error_message) {
     try {
         auto source                 = std::move(job.dgl_source);
+        auto inputs                 = std::move(job.dgl_inputs);
         sd_dgl_result_t* raw_result = nullptr;
         if (job.cancel_requested.load())
             return SD_STATUS_CANCELLED;
         if (job.dgl_allow_download && runtime.models->dgl_model_sources) {
-            const auto status = sd_dgl_check(source.c_str(), false);
-            if (status != SD_STATUS_OK) {
-                error_message = sd_dgl_error();
-                return status;
-            }
             sd::download::Events events;
             events.cancelled = [&job] { return job.cancel_requested.load(); };
             events.log       = [](const std::string& message) { LOG_INFO("%s", message.c_str()); };
@@ -771,6 +787,7 @@ static sd_status_t execute_dgl_job(ServerRuntime& runtime,
             if (!runtime.models->dgl_model_sources->prepare(source, events))
                 return SD_STATUS_CANCELLED;
         }
+        const auto bindings = dgl_input_bindings(inputs);
         {
             std::lock_guard<std::mutex> lock(*runtime.sd_ctx_mutex);
             if (job.cancel_requested.load())
@@ -781,13 +798,14 @@ static sd_status_t execute_dgl_job(ServerRuntime& runtime,
                 sd_dgl_ctx_cancel(ctx);
             });
             update_job_progress(job, "executing", "dgl");
-            const auto status = sd_dgl_run(ctx, source.c_str(), nullptr, 0, &raw_result);
+            const auto status = sd_dgl_run(ctx, source.c_str(), bindings.data(), bindings.size(), &raw_result);
             if (status != SD_STATUS_OK) {
                 error_message = sd_dgl_error();
                 return status;
             }
         }
         std::unique_ptr<sd_dgl_result_t, decltype(&sd_dgl_result_free)> result(raw_result, sd_dgl_result_free);
+        inputs.clear();
         result_info = describe_dgl_result(result.get());
         return SD_STATUS_OK;
     } catch (const std::exception& error) {
diff --git a/examples/server/async_jobs.h b/examples/server/async_jobs.h
index d116875..11a07e3 100644
--- a/examples/server/async_jobs.h
+++ b/examples/server/async_jobs.h
@@ -9,6 +9,7 @@
 #include <mutex>
 #include <string>
 #include <unordered_map>
+#include <variant>
 #include <vector>


@@ -42,6 +43,13 @@ struct AsyncJobProgress {
     std::chrono::steady_clock::time_point finished{};
 };

+struct DglJobInput {
+    std::string name;
+    std::variant<std::string, std::vector<uint8_t>> value;
+};
+
+std::vector<sd_dgl_input_t> dgl_input_bindings(const std::vector<DglJobInput>& inputs);
+
 struct AsyncGenerationJob {
     std::string id;
     AsyncJobKind kind     = AsyncJobKind::ImgGen;
@@ -56,6 +64,7 @@ struct AsyncGenerationJob {
     ImgGenJobRequest img_gen;
     VidGenJobRequest vid_gen;
     std::string dgl_source;
+    std::vector<DglJobInput> dgl_inputs;
     bool dgl_allow_download = false;
     json dgl_result_info;
     std::vector<std::string> result_images_b64;
diff --git a/examples/server/routes_dgl.cpp b/examples/server/routes_dgl.cpp
index c66597d..9e648fe 100644
--- a/examples/server/routes_dgl.cpp
+++ b/examples/server/routes_dgl.cpp
@@ -6,6 +6,7 @@
 #include <string_view>

 #include "async_jobs.h"
+#include "common/common.h"

 namespace {
     namespace fs   = std::filesystem;
@@ -102,6 +103,38 @@ namespace {
     }
 }

+static std::vector<DglJobInput> parse_dgl_inputs(const json& inputs) {
+    if (!inputs.is_object())
+        throw std::invalid_argument("Expected inputs to be an object");
+    std::vector<DglJobInput> parsed;
+    parsed.reserve(inputs.size());
+    for (const auto& [name, input] : inputs.items()) {
+        if (name.empty() || name.find('\0') != std::string::npos)
+            throw std::invalid_argument("Expected a non-empty DGL input name without NUL bytes");
+        if (!input.is_object() || input.size() != 2 ||
+            !input.contains("type") || !input.at("type").is_string() || !input.contains("value"))
+            throw std::invalid_argument("DGL input '" + name + "' must be an object with a string type and a value");
+        const auto& type = input.at("type").get_ref<const std::string&>();
+        if (type != "string" && type != "bytes")
+            throw std::invalid_argument("DGL input '" + name + "' has an unsupported type");
+        const auto& value = input.at("value");
+        if (!value.is_string())
+            throw std::invalid_argument("DGL input '" + name + "' value must be a string");
+        const auto& text = value.get_ref<const std::string&>();
+        if (type == "string") {
+            if (text.find('\0') != std::string::npos)
+                throw std::invalid_argument("DGL string input '" + name + "' contains a NUL byte");
+            parsed.push_back({name, text});
+        } else {
+            std::vector<uint8_t> bytes;
+            if (!decode_base64_bytes_strict(text, bytes))
+                throw std::invalid_argument("DGL input '" + name + "' has invalid base64");
+            parsed.push_back({name, std::move(bytes)});
+        }
+    }
+    return parsed;
+}
+
 void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) {
     auto workspace = std::make_shared<DglWorkspace>(runtime.svr_params->dgl_dir);
     svr.Get("/sdcpp/v1/dgl/scripts", with_dgl_errors([workspace](const Request&, Response& res) {
@@ -160,14 +193,31 @@ void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) {
              }));

     svr.Post("/sdcpp/v1/dgl/jobs", with_dgl_errors([&runtime](const Request& req, Response& res) {
-                 auto source = json::parse(req.body).at("source").get<std::string>();
-                 if (source.empty() || !valid_source(source)) {
-                     send_error(res, 400, "Expected non-empty UTF-8 source");
+                 std::string source;
+                 std::vector<DglJobInput> inputs;
+                 try {
+                     auto body = json::parse(req.body);
+                     source    = std::move(body.at("source").get_ref<std::string&>());
+                     if (source.empty() || !valid_source(source)) {
+                         send_error(res, 400, "Expected non-empty UTF-8 source");
+                         return;
+                     }
+                     if (body.contains("inputs"))
+                         inputs = parse_dgl_inputs(body.at("inputs"));
+                 } catch (const std::invalid_argument& error) {
+                     send_error(res, 400, error.what());
+                     return;
+                 }
+                 const auto bindings = dgl_input_bindings(inputs);
+                 const auto status   = sd_dgl_check_inputs(source.c_str(), bindings.data(), bindings.size());
+                 if (status != SD_STATUS_OK) {
+                     send_error(res, status == SD_STATUS_OUT_OF_MEMORY ? 500 : 400, sd_dgl_error());
                      return;
                  }
                  auto job                     = std::make_shared<AsyncGenerationJob>();
                  job->kind                    = AsyncJobKind::Dgl;
                  job->dgl_source              = std::move(source);
+                 job->dgl_inputs              = std::move(inputs);
                  const auto origin            = req.get_header_value("Origin");
                  const bool loopback          = req.remote_addr == "127.0.0.1" || req.remote_addr == "::1" ||
                                                 req.remote_addr == "::ffff:127.0.0.1";
diff --git a/include/stable-diffusion.h b/include/stable-diffusion.h
index 9b0208b..68e22ce 100644
--- a/include/stable-diffusion.h
+++ b/include/stable-diffusion.h
@@ -415,6 +415,10 @@ typedef struct {
 // Set allow_tensor_inputs to accept named tensor parameters in fn main(name, ...).
 SD_API sd_status_t sd_dgl_check(const char* source, bool allow_tensor_inputs);

+// Checks source with the same named bindings as sd_dgl_run, without a context,
+// copying input values, or loading models.
+SD_API sd_status_t sd_dgl_check_inputs(const char* source, const sd_dgl_input_t* inputs, size_t input_count);
+
 // Compiles source once per call, binds inputs and executes in the required context.
 // Supply every main parameter exactly once, or NULL, 0 for no inputs.
 // The run retains tensors and copies strings and byte inputs. Strings are
diff --git a/src/dgl/dgl.cpp b/src/dgl/dgl.cpp
index 697a556..7ac9ccc 100644
--- a/src/dgl/dgl.cpp
+++ b/src/dgl/dgl.cpp
@@ -237,6 +237,15 @@ sd_status_t sd_dgl_check(const char* source, bool allow_tensor_inputs) {
     });
 }

+sd_status_t sd_dgl_check_inputs(const char* source, const sd_dgl_input_t* inputs, size_t input_count) {
+    return api_call([&] {
+        if (!source)
+            throw Error(SD_STATUS_INVALID_ARGUMENT, "source is required");
+        const auto kinds = input_kinds(inputs, input_count);
+        compile(source, operations(), true, &kinds);
+    });
+}
+
 sd_status_t sd_dgl_run(sd_dgl_ctx_t* ctx, const char* source, const sd_dgl_input_t* inputs, size_t input_count, sd_dgl_result_t** result_out) {
     if (result_out)
         *result_out = nullptr;