RSS 2.0
Sign In
# Monday, October 26, 2026

AI agents are good at connecting steps. But some steps need more than a local shell: a particular runtime, more CPU or memory, or a place to keep working files between runs. We wanted flexible compute environments that can be selected to fit each task, while still being callable through the same MCP workflow.

Azure, AWS, and Google Cloud all have ways to run this kind of workload. As IBMers, though, IBM Cloud was our first choice; we also like its comparatively close-to-the-metal feel. Within IBM Cloud, Code Engine fits the execution model: each request can run in an isolated container, with its own image and CPU/memory profile. Its jobrun lifecycle gives us the operations we need: submit work, check its state, read logs, and request deletion.

MCP v2 protocol version 2025-07-28 that transitions the core architecture to be completely stateless made it possible to host implementation in Code Engine Application. A client submits a script and may choose an image and resource profile; a job can also use persistent data from a mapped COS store. The Application starts the job and returns its terminal ID to the client. That ID identifies the job in later requests to check its status, retrieve logs, or request deletion. Code Engine runs the work independently of the Application.

Tools and options

  • shell starts a job from inline Bash or a script path, with an optional image (shell, java, node, python, dotnet, all, or a full image reference) and supported CPU/memory profile.
  • status checks the job state using its terminal ID.
  • output retrieves logs by terminal ID, optionally selecting range or tail lines.
  • stop requests job deletion; use it only when you need to abort a long-running job.

The bundled images include common tools and dependencies so many tasks can run without additional setup. Resource profiles must be supported by Code Engine and fit the project's quotas.

For larger scripts or data that should persist across jobruns, configure a Code Engine persistent data store backed by Cloud Object Storage (COS). It is mounted read/write at /mnt/data, so jobs can share persistent files and callers can pass a script path there instead of sending a large script inline.

Security

The terminal service must run behind an API Gateway that authenticates callers. The service can start jobs that execute arbitrary shell scripts, so exposing it without authentication would let unauthenticated users consume compute, run untrusted commands, and access any persistent storage available to those jobs.

The gateway must forward the authenticated user's name and email as trusted identity headers, and must remove client-supplied versions of those headers before setting its own. The service uses these values to populate job identity and resolve storage paths; accepting caller-supplied identity would allow one user to impersonate another.

If persistent storage is configured, its bucket prefix must include $USER, for example terminal-store:users/$USER. The service expands that placeholder from the gateway-verified username, keeping each user's files in a separate path. Without a user-specific prefix, concurrent callers can share or overwrite files, and one user's job may read data written by another user's job.

Forwarding the email also gives jobs a verified contact identity for auditing and user-aware workflows. Only gateway-verified identity should be used for these purposes; other request headers are not a substitute for authentication.

Secrets needed by a job can be supplied as MCP HTTP headers instead of script text or tool arguments. For example, with the default x-terminal- header prefix, x-terminal-api-key becomes the job's API_KEY environment variable. In VS Code, define the header using a password-protected input:

{
  "servers": {
    "code-engine-terminal": {
      "url": "https://api.<project-id>.<region>.codeengine.appdomain.cloud/terminal/mcp",
      "type": "http",
      "headers": {
        "Authorization": "Bearer ${input:terminal-token}",
        "x-terminal-api-key": "${input:job-api-key}"
      }
    }
  },
  "inputs": [
    {
      "id": "terminal-token",
      "type": "promptString",
      "description": "Authentication token for the terminal MCP gateway",
      "password": true
    },
    {
      "id": "job-api-key",
      "type": "promptString",
      "description": "API key to expose to the job as API_KEY",
      "password": true
    }
  ]
}

The MCP client adds these values to the HTTP request; they are not part of the agent's shell-tool arguments or prompt. The gateway must still authenticate the caller, remove untrusted copies of privileged headers, and forward only explicitly approved secret headers. Secrets become available to the job process as environment variables, so scripts should not print them and logs or child processes must be handled accordingly. Prefer short-lived, least-privilege credentials.

Example: Analyze a dataset

This conversation shows an agent analyzing /mnt/data/sales.csv with the Python image: it starts a job, checks its status, and retrieves the result using the returned terminal ID.

User: I uploaded /sales.csv to the mounted COS store. Can you report the row count, total revenue, and revenue by region?

AI: I’ll run a short Python analysis against the mounted file, then check the job output.

{
  "tool": "shell",
  "arguments": {
    "script": "python - <<'PY'\nimport pandas as pd\ndf = pd.read_csv('/mnt/data/sales.csv')\nprint(f'Rows: {len(df)}')\nprint(f'Total revenue: {df[\"revenue\"].sum():.2f}')\nprint('Revenue by region:')\nprint(df.groupby('region')['revenue'].sum().to_string())\nPY",
    "image": "python",
    "resourceProfile": "cpu-1-mem-4g"
  }
}

AI: The job is running. Its terminal ID is k4m2...

{
  "tool": "status",
  "arguments": { "terminalId": "k4m2..." }
}

AI: The job completed. I’ll fetch the report.

{
  "tool": "output",
  "arguments": { "terminalId": "k4m2..." }
}

AI: The file contains 1,248 rows with total revenue of 84,392.50. The largest regional total is West at 29,410.00.

Run it in your account

Deploy the MCP service as a Code Engine Application with its own container image, and register the job images (shell, java, node, python, dotnet, and all) in a container registry the project can access.

The service does not authenticate or authorize callers, so place it behind an API Gateway that does.

For example, the Application might be reachable inside the project at http://terminal.<project-id>.svc.cluster.local/mcp. Clients would connect through a public gateway URL such as https://api.<project-id>.<region>.codeengine.appdomain.cloud/terminal/mcp.

In VS Code, add the gateway endpoint to the project's .vscode/mcp.json and prompt for the gateway token:

{
  "servers": {
    "code-engine-terminal": {
      "url": "https://api.<project-id>.<region>.codeengine.appdomain.cloud/terminal/mcp",
      "type": "http",
      "headers": {
        "Authorization": "Bearer ${input:terminal-token}"
      }
    }
  },
  "inputs": [
    {
      "id": "terminal-token",
      "type": "promptString",
      "description": "Authentication token for the terminal MCP gateway",
      "password": true
    }
  ]
}

A terminal shaped around the task

Different jobs need different tools, compute, and working data. By combining selectable execution images and resource profiles with a simple MCP interface, the terminal lets an agent run each task in an environment suited to the work.

See implementation at GitHub

Monday, October 26, 2026 7:01:03 AM UTC  #    Comments [0] -
AI | Announce | Thinking aloud

Continuing the tradition, we reported the bug in Saxon 13.1

See Compilation error in Saxon 13.1

Monday, October 26, 2026 6:58:39 AM UTC  #    Comments [0] -
xslt
# Monday, June 1, 2026

It's almost established tradition - Saxonica issues new version of Saxon XSLT processor, we update our code base to newest version, and it crashes.

Next step is a long discussion in their forum and attempt to figure our who is guilty, and what to do about it.

In most cases the problem is eventually found, we rollback to stable Saxon version, and wait for the update.

Same is true for newest major Saxon 13 update.

See ClassCastException in Saxon 13

Monday, June 1, 2026 6:40:29 AM UTC  #    Comments [0] -
Thinking aloud | xslt
# Sunday, May 24, 2026

It's not the first time we need massive use of AI in our code.

Summary

This post documents our exploration of agentic AI frameworks as an alternative to our proven OpenAI Batch API approach. While pressure existed to adopt trendy agentic solutions, we remained pragmatic: our existing Batch API solution is scalable, well-understood, and well-maintained.

We evaluated LangChain and LangGraph for implementing complex AI workflows with state management and resumability. Our conclusion is nuanced:

  • LangChain excels at simplifying AI integration through declarative service interfaces.
  • LangGraph introduces unnecessary complexity for our use cases; pure Java with explicit state management is cleaner and easier to debug.

By combining pure Java with LangChain for AI calls, we achieved cleaner, more efficient code than our original Batch API implementation, while maintaining the readability and maintainability Arthur and I both value.

Use Case

Let's formulate a use case in simple form:

  • There is a folder of input data that you need to process somehow.
  • One or multiple steps in such processing involve AI prompts.
  • The result is a folder of output data.

Journey So Far

For a couple of years, we've used OpenAI Batch API to do such processing. Originally we used Azure OpenAI, but when we became part of IBM, we switched to watsonx.ai, and even re-implemented a lacking Batch API drop-in replacement service using IBM Code Engine.

Solution works, but... here the journey only begins.

The Conversation

IBM presses - you need to build agentic solutions.

Arthur tells - what we have can be called agentic use of AI. It just works without buzz words.

I tell - yes, that's correct, but it's not easy to implement non-trivial AI flow, including tool calls, while sticking to the Batch API.

Arthur - not trivial but possible. Our solution is scalable, we understand it, and we easily support it. So, per the first rule of programming - don't fix something that is working!

I - I want to explore what other solutions can give us.

Arthur, skeptically - go on, and I'll be looking at your efforts!

Exploring the Landscape

So, I went on discovering today's landscape of agentic AI libraries.

As you know, there are many of them - from Microsoft, from the community, and for other providers. We have our constraints. Being part of IBM means Langchain is the default choice. You would need to have good arguments to use something different.

Okay, we agreed with Arthur that Langchain is what I'll continue to explore.

Then I went forward looking at how I could implement our sample task with massive processing of folders of data.

What came naturally is LangGraph - the framework to implement different workflows, including cycles, parallel processing, AI calls, and checkpointing of execution.

Checkpointing looked promising - I could run the flow, save intermediate results, stop, restart, and do different things with state. This was encouraging for a long-running flow.

I've found that with some effort, you could even integrate the Batch API into it. I was positive about the right direction. Arthur wisely listened and agreed that this sounds promising.

Language Selection

Next step was to select the language.

Several years ago I would say it's weird to select a framework and then language, but these days the world has changed.

We found that LangGraph has:

  • Original implementation in Python, which is most advanced
  • TypeScript port
  • LangGraph4j - Java version inspired by Python

For us it was not immediately obvious what to use, as we don't start a new project but continue ongoing development. Our preferences go with LangGraph4j - there will be fewer moving parts, and it will integrate naturally.

POC Sample

Now we needed hands-on experience with the technology to study it deeper and implement a simplest flow.

What I learned is that LangGraph is a library to define a logic flow in a semi-declarative way as a graph of edges and vertices, where:

  • Edge - defines a unit of logic
  • Vertices - define transitions between edges

In general, LangGraph has nothing to do with LangChain, which is an AI wrapper. You can do whatever you want with LangGraph, including calling AI through LangChain. LangGraph allows you to stop execution, save state somewhere (e.g., in files or in a database), and later resume.

Arthur was satisfied and told me that the flow graph resembled his old favorite BizTalk, which allowed you to define a high-level algorithm visually, and the final block could be implemented by calling real code.

All this looked promising and allowed us to implement some simple tasks:

  1. An agent to perform simple math: Sum(a, b)
  2. An agent to perform a simple cycle of sub-agents
  3. An agent to perform a parallel cycle of sub-agents

I started with Task 1 - the Sum agent - and implemented it using a LangGraph sample. It included a map-based immutable state, graph definitions, and node handlers.

Arthur looked at it for a long time and told me that he barely understood what he saw and barely understood where the business logic (a + b) was.

Verdict - this is an obscure, unmanageable pile of code. We need something less clever if we want to understand it in half a year.

I went back and introduced some helpers to simplify agent coding in LangGraph4j. This allowed me to produce much smaller and concise code, which I want to quote here:

package com.bphx.coolgen.agents;

import org.bsc.langgraph4j.CompileConfig;
import org.bsc.langgraph4j.CompiledGraph;
import org.bsc.langgraph4j.RunnableConfig;
import org.bsc.langgraph4j.StateGraph;

import static com.bphx.coolgen.agents.Agent.*;

import java.io.Serializable;

/// Sample agent demonstrating basic LangGraph4j usage. Receives two numbers and
/// computes their sum.
///
/// Uses state class [Data].
///
/// ## Usage
///
/// var graph = Sum.build();
/// var data = Sum.of(10.0, 32.0);
/// var result = Agent.invoke(graph, data);
/// System.out.println("Sum: " + result.result); // prints: Sum: 42.0
public final class Sum
{
  /// State class for the Sum agent. Contains input operands and the
  /// computed result.
  public static class Data implements Serializable
  {
    public Data(double a, double b)
    {
      this.a = a;
      this.b = b;
    }

    public final double a;
    public final double b;
    public double result;
  }

  public static Data of(double a, double b)
  {
    return new Data(a, b);
  }

  /// Builds and returns a compiled graph for the sum agent.
  /// 
  /// @return compiled graph ready to invoke
  /// @throws Exception if graph compilation fails
  public static CompiledGraph<State<Data>> build() throws Exception
  {
    return Agent.<Data>graph()
        .addNode("sum", node(Sum::sum))
        .addEdge(StateGraph.START, "sum")
        .addEdge("sum", StateGraph.END)
        .compile(CompileConfig.builder().build());
  }

  private static Data sum(Data data, RunnableConfig config)
  {
    data.result = data.a + data.b;

    return data;
  }
}

Arthur confirmed that he was able to understand that sum() defines the business logic, the Data class defines the graph state, and build() defines the graph itself, like this: start -> sum -> end.

However, neither Arthur nor I were fully satisfied.

At the next step, I implemented Task 2 - a cycle of Sum calls. This worked, but it looked as if you were building assembly with a graph, as if you need to implement:

start:
  index = 0;
  count = 1000;

cycle:
  if (index >= count)
    goto end;

iteration:
  result[index] = a[index] + b[index];
  index = index + 1;
  goto cycle;

end:

This works but doesn't look nice. Besides, debugging LangGraph code is an adventure.

Finally, the 3rd task was the least trivial part to implement. It turned out there is no built-in parallel cycles, and we needed to go to the basic fork-join building block in LangGraph to generate a dynamic graph for parallel processing.

This worked as well, but it became even more complex, involving merging states after parallel branches and uncontrolled serialization and deserialization of all accumulated states.

It did not look like a good trade. We lost clean, readable Java code in exchange for a resumable graph that is hard to understand and debug.

Next Steps

We implemented the original task of processing a folder in parallel, where we called LangChain and were pleased with its AI services. You could define an interface and get its implementation from ChatModel (which even supports tool calls), like this:

  /// AI service interface for generating HTML documentation summaries.
  ///
  /// LangChain4j creates an implementation that calls the chat model with
  /// a system prompt.
  interface Summarizer
  {
    @SystemMessage("""
        You are a world class expert in programming... 

        Create documentation for the provided code to ... 
        Use basic HTML markup, like
        <h1>, <p>, <b>, <ol>, <ul>, <li>. Don't use <html> and <body>.

        - Documentation must be terse.
        - No greetings and farewells must be used.
        - Provide a summary of the code's purpose and functionality.
        ...
        """)
    String summarize(@UserMessage String code);
  }

  ...
  var summarizer = AiServices.create(Summarizer.class, chatModel);
  ...
  var summary = summarizer.summarize(code);

Notice the elegance: the entire AI integration is reduced to a single interface definition and one line of instantiation. The business logic (summarize()) is immediately visible. Compare this to the earlier LangGraph Sum agent with its graph definitions, node handlers, and state management—this is why we prefer it.

Sharing Our Approach

We're planning to share this pattern with our team as the recommended path forward for AI integration. Rather than pursuing the latest agentic frameworks, teams should:

  1. Start with explicit state management in their language of choice
  2. Use focused AI libraries like LangChain4j for clean abstraction
  3. Avoid graph frameworks unless truly needed for distributed resumability
  4. Prioritize code clarity over framework comprehensiveness

Future Roadmap

The Java + LangChain pattern scales well for:

  • Batch processing of large folders with parallel LangChain calls
  • Multi-step AI workflows (chain multiple AI services together)
  • Tool-augmented AI (extending ChatModel with custom tools)
  • Integration with existing systems where Java is already the lingua franca

We're confident this approach will serve our organization better than chasing trending frameworks.

Key Learnings

  1. Buzzwords ≠ Solutions: The pressure to "build agentic solutions" made us evaluate tools strictly on merit, not hype. Sometimes "agentic" is just marketing.

  2. Abstraction Layers Matter: LangChain's declarative approach (@SystemMessage, AiServices) hides complexity elegantly. LangGraph's explicit node-edge model exposed too many low-level details for our domain.

  3. Code Readability Wins Long-term: Arthur's visceral reaction to the initial LangGraph code—"barely understand where the business logic is"—reminded us that clever code is harder to maintain than straightforward code (even with AI).

  4. Pragmatism Over Features: Our Batch API solution already solved resumability and scalability. Adopting a framework for features you don't need creates unnecessary technical debt.

  5. Pure Language + Focused Libraries: Combining plain Java + LangChain gave us the best of both worlds: explicit control over algorithms and clean AI abstraction.

When LangGraph Makes Sense

Before we dismiss LangGraph entirely, it's worth noting when it might be the right choice:

  • Truly distributed systems where processes run on different machines and need to resume
  • Long-running, unattended workflows that span days or weeks and need checkpointing (though native java implementation gave us flexibility on checkpoints)
  • Complex branching logic with many conditional paths that benefit from visual representation
  • Systems requiring audit trails of every state transition

For our use case—batch processing with intermediate results we can manage explicitly—LangGraph was overkill.

Conclusion

After working through these explorations, we reached a nuanced but clear conclusion:

  • LangChain - Excellent. Provides clean abstractions for AI integration without forcing architectural decisions.
  • LangGraph - Not a fit for our use cases. Its complexity and explicit state serialization overhead outweigh the benefits for batch processing. For truly distributed, long-running workflows, it might be appropriate, but we have simpler solutions.

The Better Way Forward

We re-implemented several processes that used the OpenAI Batch API in pure Java + LangChain, and even extended the logic to multi-step AI calls. The results:

  • Cleaner code than the original Batch API implementation
  • More powerful (support for complex multi-turn conversations)
  • Faster execution (parallel processing without batching delays)
  • Easier to maintain (straightforward Java instead of graph abstractions)

Thus, we believe our decision to explore and eventually adopt the Java + LangChain pattern was the right one. We gained the benefits of modern AI frameworks without sacrificing the simplicity and maintainability that Arthur and I both prioritize.

Sunday, May 24, 2026 1:17:03 PM UTC  #    Comments [0] -
AI | Thinking aloud | Tips and tricks
# Wednesday, April 10, 2024

Would you like to smile a little? Then read this dialog that occured today, April 10, 2024:

dialog
Wednesday, April 10, 2024 9:56:26 AM UTC  #    Comments [0] -

# Friday, January 26, 2024

Introduction

We migrate code out of MF to Azure. Tool we use produces plain good functionally equivalent C# code. But it turns it's not enough!

So, what's the problem?

Converted code is very slow, especially for batch processing, where MF completes job, say in 30 minutes, while converted code finishes in 8 hours.

At this point usually someone appears and whispers in the ear:

Look, those old technologies are proven by the time. It worth to stick to old good Cobol, or better to Assembler if you want to do the real thing.

We're curious though: why is there a difference?

Turns out the issue lies in differences of network topology between MF and Azure solutions. On MF all programs, database and file storage virtually sit in a single box, thus network latency is negligible.

It's rather usual to see chatty SQL programs on MF that are doing a lot of small SQL queries.

In Azure - programs, database, file storage are different services most certainly sitting in different phisical boxes. You should be thankfull if they are co-located in a single datacenter. So, network latency immediately becomes a factor. Even if it just adds 1 millisecond per SQL roundtrip, it adds up in loops, and turns in the showstopper.

There is no easy workaround on the hardware level.

People advice to write programs differently: "Tune applications and databases for performance in Azure SQL Database".

That's a good advice for a new development but discouraging for migration done by a tool.

So, what is the way forward?

Well, there is one. While accepting weak sides of Azure we can exploit its strong sides.

Parallel refactoring

Before continuing let's consider a code demoing the problem:

  public void CreateReport(StringWriter writer)
  {
    var index = 0;

    foreach(var transaction in dataService.
      GetTransactions().
      OrderBy(item => (item.At, item.SourceAccountId)))
    {
      var sourceAccount = dataService.GetAccount(transaction.SourceAccountId);
      var targetAccount = transaction.TargetAccountId != null ?
        dataService.GetAccount(transaction.TargetAccountId) : null;

      ++index;

      if (index % 100 == 0)
      { 
        Console.WriteLine(index);
      }

      writer.WriteLine($"{index},{transaction.Id},{
        transaction.At},{transaction.Type},{transaction.Amount},{
        transaction.SourceAccountId},{sourceAccount?.Name},{
        transaction.TargetAccountId},{targetAccount?.Name}");
    }
  }

This cycle queries transactions, along with two more small queries to get source and target accounts for each transaction. Results are printed into a report.

If we assume query latency just 1 millisecond, and try to run such code for 100K transactions we easily come to 200+ seconds of execution.

Reality turns to be much worse. Program spends most of its lifecycle waiting for database results, and iterations don't advance until all work of previous iterations is complete.

We could do better even without trying to rewrite all code! Let's articulate our goals:

  1. To make code fast.
  2. To leave code recognizable.

The idea is to form two processing pipelines:

  • (a) one that processes data in parallel out of order;
  • (b) other that processes data serially, in original order;

Each pipeline may post sub-tasks to the other, so (a) runs its tasks in parallel unordered, while (b) runs its tasks as if everything was running serially.

So, parallel plan would be like this:

  1. Queue parallel sub-tasks (a) for each transaction.
  2. Parallel sub-task in (a) reads source and target accounts, and queues serial sub-task (b) passing transaction and accounts.
  3. Serial sub-task (b) increments index, and writes report record.
  4. Wait for all tasks to complete.

To reduce burden of task piplelines we use Dataflow (Task Parallel Library), and encapsulate everything in a small wrapper.

Consider refactored code:

  public void CreateReport(StringWriter writer)
  {
    using var parallel = new Parallel(options.Value.Parallelism); //     ⬅️ 1
    var index = 0;

    parallel.ForEachAsync( //     ⬅️ 2
      dataService.
        GetTransactions().
        OrderBy(item => (item.At, item.SourceAccountId)),
      transaction => //     ⬅️ 3
      {
        var sourceAccount = dataService.GetAccount(transaction.SourceAccountId);
        var targetAccount = transaction.TargetAccountId != null ?
          dataService.GetAccount(transaction.TargetAccountId) : null;

        parallel.PostSync(  //     ⬅️ 4
          (transaction, sourceAccount, targetAccount),  //     ⬅️ 5
          data =>
          {
            var (transaction, sourceAccount, targetAccount) = data; //     ⬅️ 6

            ++index;

            if (index % 100 == 0)
            {
              Console.WriteLine(index);
            }

            writer.WriteLine($"{index},{transaction.Id},{
              transaction.At},{transaction.Type},{transaction.Amount},{
              transaction.SourceAccountId},{sourceAccount?.Name},{
              transaction.TargetAccountId},{targetAccount?.Name}");
          });
      });
  }

Consider ⬅️ points:

  1. We create Parallel utility class passing degree of parallelism requested.
  2. We iterate transactions using parallel.ForEachAsync() that queues parallel sub-tasks for each transaction, and then waits until all tasks are complete.
  3. Each parallel sub-task recieves a transaction. It may be called from a different thread.
  4. Having recieved required accounts we queue a sub-task for synchronous execution using parallel.PostSync(), and
  5. Pass there data collected in parallel sub-task: transaction and accounts.
  6. We deconstruct data passed into variables, and then proceed with serial logic.

What we achieve with this refactoring:

  1. Top level query that brings transactions is done and iterated serially.
  2. But each iteration body is run in parallel. By default we set it up to allow up to 100 parallel executions. All those parallel sub-task do not wait on each other so their waitings do not add up.
  3. Sync sub-tasks are queued and executed in order of their serial appearance, so increments and report records are not a subject of race conditions, nor a subject of reordering of output records.

We think that such refactored code is still recognizible.

As for performance this is what log shows:

Serial test
100
...
Execution time: 00:01:33.8152540

Parallel test
100
...
Execution time: 00:00:05.8705468

Reference

Please take a look at project to understand implementation details, and in particular Parallel class implementing API to post parallel and serial tasks, run cycles and some more.

Please continue reading on GitHub.

Friday, January 26, 2024 1:27:16 PM UTC  #    Comments [0] -
.NET | Thinking aloud | Tips and tricks
# Monday, January 1, 2024

As we wrote some time ago, we started to use AI and ML APIs in our applications, but this time we've tried to use Bing chat as a tool.

The initial task was to collect sequences of integer numbers and return a list of pairs integers where the first number is a range's start and the second one is a count of values in the range. For example, for sequence 1, 2, 3, 5, 8, 9 we'd like to get the following results: 1, 3 5, 1 8, 2

We both started to solve this issue. My brother started to play with SSMS using his deep knowledges in SQL and analytic functions, whereas me started to play with Bing chat. Looking ahead, I can state that we both solved the issue using almost the same SQL statement almost in the same time.

Here are my prompts and Bing's answers:

Prompt:
Act as database analyst and software engineer. Given the table (T) with a numeric field (N), which values are orderd ranges of integers. In a range each next value is greater than previous one on 1. When value differs from the previous one more than on 1 then in belongs to another range. Generate select statement that returns rows with two fields. The first field (R) is a number from which a range starts and the second field (C) is count elements of that range:
Answer:
Sure, I can help with that. Here's a SQL query that should do the trick. This query uses a self-join to identify the start of each range, and then groups by the start of the range to count the number of elements. ```sql SELECT start_of_range AS R, COUNT(*) AS C FROM ( SELECT N, N - ROW_NUMBER() OVER (ORDER BY N) AS start_of_range FROM T ) subquery GROUP BY start_of_range ORDER BY start_of_range; ``` In this query, `start_of_range` is calculated as the difference between the current value of `N` and its row number (when ordered by `N`). This difference will be the same for all `N` in the same range. Then we group by `start_of_range` to get the count of elements in each range. The outer query selects the start of each range (`R`) and the count of elements in that range (`C`).
Me, scratching the head, hmmm...
Question:
This is a bit incorrect SQL select. For example for values 1, 2, 3, 5, 8, 9 I'd like to get the following results: 1, 3 5, 1 8, 2 What a SQL select shall I use to get such results?
Answer:
I apologize for the confusion earlier. You're right, the previous query doesn't handle the scenario you've described correctly. Here's a corrected SQL query that should give you the desired output. This query uses a window function to compare each row with the previous one and identify the start of a new range. Then it groups by the start of the range to count the elements. ```sql WITH ranges AS ( SELECT N, CASE WHEN N - LAG(N, 1, N) OVER (ORDER BY N) > 1 THEN 1 ELSE 0 END AS is_start_of_range FROM T ), range_groups AS ( SELECT N, SUM(is_start_of_range) OVER (ORDER BY N) AS range_group FROM ranges ) SELECT MIN(N) AS R, COUNT(*) AS C FROM range_groups GROUP BY range_group ORDER BY R; ``` In this query, `is_start_of_range` is a flag that indicates the start of a new range (when the difference between the current and previous `N` is more than 1). `range_group` is a running total of `is_start_of_range` that serves as a unique identifier for each range. The outer query then groups by `range_group` to get the start (`R`) and count (`C`) of each range. I hope this helps! Let me know if you have any other questions.

That answer more satisfied me, and I've checked the following example:

with T as ( select 10 N union all select 11 N union all select 30 N union all select 31 N union all select 32 N union all select 50 N union all select 80 N union all select 81 N union all select 82 N union all select 83 N union all select 90 N ), ranges AS ( SELECT N, CASE WHEN N - LAG(N, 1, N) OVER (ORDER BY N) > 1 THEN 1 ELSE 0 END AS is_start_of_range FROM T ), range_groups AS ( SELECT N, SUM(is_start_of_range) OVER (ORDER BY N) AS range_group FROM ranges ) SELECT MIN(N) AS R, COUNT(*) AS C FROM range_groups GROUP BY range_group ORDER BY R;

The result was:

R C ------------ 10 2 30 3 50 1 80 4 90 1

Conclusion:
Nowdays, using AI as a tool, you may improve your performance to the expert level and, may be, study something new...

P.S. Don't fool youself that AI can replace a developer (see the first answer of the chat), but together they can be much stornger than separatelly.

P.P.S. Another interesting solution gave us our colleague. She used an additional field to avoid using analytics function, and she reached the same result:

with T as ( select 10 ID, 1 N union all select 11 ID, 1 N union all select 30 ID, 1 N union all select 31 ID, 1 N union all select 32 ID, 1 N union all select 50 ID, 1 N union all select 80 ID, 1 N union all select 81 ID, 1 N union all select 82 ID, 1 N union all select 83 ID, 1 N union all select 90 ID, 1 N ), Groups AS ( SELECT ID, N, ROW_NUMBER() OVER (ORDER BY ID) - ID AS GroupNumber FROM T ) SELECT MIN(ID) AS R, SUM(N) AS C FROM Groups GROUP BY GroupNumber ORDER BY StartID;
Monday, January 1, 2024 2:02:01 PM UTC  #    Comments [0] -
AI | SQL Server puzzle | Thinking aloud | Tips and tricks
# Thursday, June 22, 2023

Many years ago we implemented Akinator like engine purely within SQL Server.

Today we use exactly the same technique to implement vector database.

Please see our GitHub repo: vector-database.

Thursday, June 22, 2023 10:01:45 PM UTC  #    Comments [0] -
Announce | SQL Server puzzle | Thinking aloud
# Thursday, March 23, 2023

Last few days we play with OpenAI API and out of pure interest have asked about few slogans for our team. As an input we fed info from "About us" page. And as one of the first slogans we've gotten the following slogan that catgh our eyes:

Excellence Through Experience: Nesterovsky Bros.

ChatGPT is not a bad copywriter at all...

Thursday, March 23, 2023 11:30:03 AM UTC  #    Comments [0] -
Thinking aloud
# Sunday, January 8, 2023

While doing a migration of some big xslt 3 project into plain C# we run into a case that was not obvious to resolve.

Documents we process can be from a tiny to a moderate size. Being stored in xml they might take from virtually zero to, say, 10-20 MB.

In C# we may rewrite Xslt code virtually in one-to-one manner using standard features like XDocument, LINQ, regular classes, built-in collections, and so on. Clearly C# has a reacher repertoire, so task is easily solved unless you run into multiple opportunities to solve it.

The simplest solution is to use XDocument API to represent data at runtime, and use LINQ to query it. All features like xslt keys, templates, functions, xpath sequences, arrays and maps and primitive types are natuarally mapped into C# language and its APIs.

Taking several xslt transformations we could see that xslt to C# rewrite is rather straightforward and produces recognizable functional programs that have close C# source code size to their original Xslt. As a bonus C# lets you write code in asynchronous way, so C# wins in a runtime scalability, and in a design-time support.

But can you do it better in C#, especially when some data has well defined xml schemas?

The natural step, in our opinion, would be to produce C# plain object model from xml schema and use it for runtime processing. Fortunately .NET has xml serialization attributes and tools to produce classes from xml schemas. With small efforts we have created a relevant class hierarchy for a rather big xml schema. XmlSerializer is used to convert object model to and from xml through XmlReader and XmlWriter. So, we get typed replacement of generic XDocument that still supports the same LINQ API over collections of objects, and takes less memory at runtime.

The next step would be to commit a simple test like:

  • read object model;

  • transform it;

  • write it back.

We have created such tests both for XDocument and for object model cases, and compared results from different perspectives.

Both solution produce very similar code, which is also similar to original xslt both in style and size.

Object model has static typing, which is much better to support.

But the most unexpected outcome is that object model was up to 20% slower due to serialization and deserialization even with pregenerated xmlserializer assemblies. Difference of transformation performance and memory consumption was so unnoticable that it can be neglected. These results were confirmed with multiple tests, with multiple cycles including heating up cycles.

Here we run into a case where static typing harms more than helps. Because of the nature of our processing pipeline, which is offline batch, this difference can be mapped into 10th of minutes or even more.

Thus in this particular case we decided to stay with runtime typing as a more performant way of processing in C#.

Sunday, January 8, 2023 1:28:14 PM UTC  #    Comments [0] -
.NET | xslt
# Saturday, April 16, 2022

Xslt is oftentimes thought as a tool to take input xml, and run transformation to get html or some xml on output. Our use case is more complex, and is closer to a data mining of big data in batch. Our transformation pipelines often take hour or more to run even with SSD disks and with CPU cores fully loaded with work.

So, we're looking for performance opportunities, and xml vs json might be promising.

Here are our hypotheses:

  • json is lighter than xml to serialize and deserialize;
  • json stored as map(*), array(*) and other items() are ligher than node() at runtime, in particular subtree copy is zero cost in json;
  • templates with match patterns are efficiently can be implemented with maps();
  • there is incremental way forward from use of xml to use of json.

If it pays off we might be switching xml format to json all over, even though it is a development effort.

But to proceed we need to commit an experiment to measure processing speed of xml vs json in xslt.

Now our task is to find an isolated small representative sample to prove or reject our hypotheses.

Better to start off with some existing transformation, and change it from use of xml to json.

The question is whether there is such a candidate.

Saturday, April 16, 2022 7:03:04 PM UTC  #    Comments [0] -
Thinking aloud | xslt
# Saturday, January 15, 2022
Couple of days ago, while integrating with someones C# library, we had to debug it, as something went wrong. The code is big and obscure but for the integration purposes it's rather simple: you just create and call a class, that's all. Yet, something just did not work. We had to prove that it's not our fault, as the other side is uncooperative and would not run common debug session to resolve the problem.

To simplify the matter as much as possible here is the case:

var input = ...
var x = new X();
var output = x.Execute(input);

You pass correct input, and get correct output. Simple, right? But it did not work! So, we delved into the foreign code, and this is what we have seen:

class X: Y
{
  public Output Execute(Input input)
  {
    return Perform(input);
  }

  protected override Output Run(Input input)
  { 
    ...

     return output;
  }
}

class Y: Z
{
  ...
}

class Z
{
  protected Output Perform(Input input)
  {
    return Run(Input);
  }
        
  protected virtual Output Run(Input input)
  {
    return null;
  }
}

Do you see, still flow is simple, right? We call X.Execute(), it calls Z.Perform(), which in turn calls overriden X.Run() that returns the result.

But to our puzzlement we got null on output, as if Z.Run() was called!

We stepped through the code in debugger and confirmed that Z.Perform() calls Z.Run(), even though "this" instance is of type X.

How can it be? It's a nonsence! Yet, no overriden method was ever called.

No matter how much scrunity we applied to sources X and Z it just did not work.

We verified that the signature of X.Run() matches the signature of Z.Run(), so it overrides the method.

Then what do we see here?

And then enlightenment come! Yes, X.Run() overrides the method, but what method?

We looked closely at class Y, and bingo, we can see there following:

class Y: Z
{
  ...

  protected virtual Output Run(Input input)
  {
    return null;
  }
      
  ...
}

So, X.Run() overrides Y.Run() and not Z.Run()!

Per .NET Y.Run() and Z.Run() are two independant virtual methods, where Y.Run() in addition hides Z.Run().

IDE even issued a warning that it's better declare Y.Run() as:

protected new virtual Output Run(Input input)
{
  return null;
}

So, someones code was plainly wrong: Y.Run() had to use override rather than virtual.

We won, right?

Well, it's hard to call it a win.

We spent a hour looking at someones ugly code just to prove we're still sane.

So, what is conclusion of this story?

We think here it is:

  • be cautious while looking at someones code;
  • look at IDE warnings, don't disregard them, and try to resolve all of them in your code base;
  • try to write simple code.
Saturday, January 15, 2022 1:55:08 PM UTC  #    Comments [0] -
.NET | Thinking aloud
# Wednesday, October 20, 2021

Lately we work great deal of time with Azure's CosmosDB.

This is how it's defined:

"It is schema-agnostic, horizontally scalable, and generally classified as a NoSQL database."

This, unconfident in itself, quote below is clarified as:

"The SQL API lets clients create, update and delete containers and items. Items can be queried with a read-only, JSON-friendly SQL dialect."

To be honest this SQL API made us favor CosmosDB.

So, we started a development with CosmosDB as a data storage.

The next development ingredient we learned the hard way is to try to refrain from clever techniques.

The lesson we learned is simple: after you finish with a project, provided it's not a toy, you give it to people who will be supporting it. You should think about those future developers before you're going to insert some cleverness in you code.

With this common sense we selected EF Core as a library that will serve as an interface between C# and the database.

Initialy all went well until we needed to store a list of strings as a document property and found it's not possible.

Why? - was a naive question.

Answer puzzled us a lot - because string is not an "Entity" (what ever it means), and EF is about framework of entities.

You could argue with this argument as long as you like, it just does not work. It is especially bad if you need to store a class that you do not directly control e.g. structures returned from other services.

Next pothole with EF was when we tried to run an innocent query that joins the data from document: e.g. document contains items, and you want to query some items from some documents.

Guess what?

Right, EF Core does not support it.

Why?

Because!

Later we have found that many other constructs and functions that you easily use in SQL dialect of CosmosDB are not possible or supported in EF Core.

We were very upset with those crutches and came to a conclusion that EF Core harms more than helps when you work with CosmosDB.

We went on and looked at how you work directly with CosmosDB client, and have found that it has all features ready:

  • you may give it SQL and bind parameters;
  • you may convert result items to objects;
  • you may create, delete, update and query data;

So, do we need EF Core?

We answered, no.

This does not mean we reject the value of EF Core but here our conclusion was that this API layer just complicated things instead making them simpler. It might be that EF Core for CosmosDB is not mature enough at this time.

Wednesday, October 20, 2021 4:11:39 PM UTC  #    Comments [0] -
Azure | Thinking aloud
# Tuesday, February 2, 2021

Recently we have found that BinaryFormatter.Serialize and BinaryFormatter.Deserialize methods are marked as obsolete in .NET 5.0, and are declared dangerous:

The BinaryFormatter type is dangerous and is not recommended for data processing. Applications should stop using BinaryFormatter as soon as possible, even if they believe the data they're processing to be trustworthy. BinaryFormatter is insecure and can't be made secure.

See BinaryFormatter security guide for more details.

That guide along with its links go and expand on what problems BinaryFormatter poses. The schema of dangeous use cases, we have seen so far, is like that:

  • two different sides communicate to each other;
  • one side supplies input in BinaryFormatter's format;
  • other side reads input using BinaryFormatter and instantiates classes.

A threat arises when two sides cannot trust to each other or cannot establish trusted communication chanel. In these cases malign input can be supplied to a side reading the data, which might lead to unexpected code execution, deny of service, data exposure and to other bad consequences.

Arguing like this, today's maintainers of .NET concluded that it's better to tear down BinaryFormatter and similar APIs out of the framework.

Note that they don't claim BinaryFormatter itself, or Reflection API that it uses, as a core of the problem. They blame on communication.

Spelling out clearly what are concerns could help to everyone to better understand how to address it. In the area of security of communication there are a lot of ready solutions like:

  • use signature to avoid tampering the data;
  • use encription to avoid spying the data;
  • use access rights to avoid even access to the data;
  • use secure communication channels.

We can surely state that without applying these solutions no other serialization format is reliable and is subject of the same vulnerabilities.

 

After all it looked like an attempt to throw out the baby with the bath water. The good news is that thankfully to now modular structure of .NET runtime we're able to access binary serialization library, which are (and will be) available on nugets repositories. So, it's futile effort to erase this usefull API.

Tuesday, February 2, 2021 12:39:37 PM UTC  #    Comments [0] -
.NET | Thinking aloud
# Friday, January 1, 2021

Earlier we wrote that recently we've gotten few tasks related to Machine Learning. The prerequisites to such task is to collect and prepare the input data. Usually the required data is scattered across public sites, some of them are in plain text format (or close to it), but others are accessible as output of public applications. To obtain the required data for such sites you have to navigate thourgh pages, which often requires keeping state between navigations.

In order to implement this task you need some kind of crawler/scraper of the websites. Fortunately, there are a lot of frameworks, libraries and tools in C# (and in other languages too) that allow to do this (visit this or this site to see most popular of them), for example:

  • ScrapySharp
  • ABot
  • HtmlAgilityPack
  • DotnetSpider

There are pros and cons of using these libraries. Most crucial cons is a lack of support of rich UI based on heavy client-side scripts and client-side state support. Since not all such libraries implement fully browser emulation and even more, some of them do not support Javascript execution. So, they suit for gathering information from simple web pages, but no library allows to easy navigate to some page of a web application that keeps rich client-side state. Even best of them, like ScrapySharp, require heavy programming to achieve the result.

Then, suddenly, we've recalled that already for several years we're using Selenium and web drivers to automate web tests for AngularJS/Angular projects. After short discussion we came to conclusion that there is no big difference between testing web application and collecting data, since one of testing stages is collecting of actual results (data) from the tested page, and usually our tests consist of chains of actions performed on consequently visited pages.

This way we came to idea to use WebDriver API implemented by Selenium project. There are implementations of this API in different languages, and in C# too.

Using WebDriver we easily implement cumbersome navigation of a complex web application and can collect required data. Moreover, it allows to run WebDriver in screenless mode. Some of its features allow to create a snapshots of virtual screen and store HTML sources that would resulted of Javascript execution. These features are very useful during run-time troubleshooting. To create a complex web application navigation we need only a bit more knowledge than usual web application's user - we need to identify somehow pages' elements for example by CSS selectors or by id of HTML elements (as we do this for tests). All the rest, like coockies, view state (if any), value of hidden fields, some Javascript events will be transparent in this case.

Although one may say that approach with Selenium is rather fat, it's ought to mention that it is rather scalable. You may either to run several threads with different WebDriver instances in each thread or run several processes simultaneously.

However, beside pros there are cons in the solution with Selenium. They will appear when you'll decide to publish it, e.g. to Azure environment. Take a note that approach with Selenium requires a browser on the server, there is also a problem with Azure itself, as it's Microsoft's platform and Selenium is a product of their main competitor Google... So, some issues aren't techincals. The only possible solution is to use PaaS approach instead of SaaS, but in this case you have to support everything by yourself...

The other problem is that if your application will implement rather aggressive crawling, so either servers where you gather data or your own host might ban it. So, be gentle, play nice, and implement delays between requests.

Also, take into account that when you're implementing any crawler some problems may appear on law level, since not all web sites allow pull anything you want. Many sites use terms & conditions that defines rules for the site users (that you cralwer should follow to), otherwise legal actions may be used against them (or their owners in case of crawler). There is very interesting article that describes many pitfalls when you implement your own crawler.

To summarize everything we told early, the Selenium project could be used in many scenarios, and one of them is to create a powerful crawler.

Friday, January 1, 2021 2:34:37 PM UTC  #    Comments [0] -
ML.NET | Thinking aloud | Tips and tricks
Archive
<November 2026>
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345
Statistics
Total Posts: 392
This Year: 5
This Month: 0
This Week: 0
Comments: 10175
Locations of visitors to this page
Disclaimer
The opinions expressed herein are our own personal opinions and do not represent our employer's view in anyway.

© 2026, Nesterovsky bros
All Content © 2026, Nesterovsky bros
DasBlog theme 'Business' created by Christoph De Baene (delarou)