Sr. Content Developer at Microsoft, working remotely in PA, TechBash conference organizer, former Microsoft MVP, Husband, Dad and Geek.
157857 stories
·
33 followers

Memory Safety's Hardest Problem

1 Share

Memory Safety’s Hardest Problem

Uplifting a lobsters comment for easier reference.

The central memory safety counter example, the hardest case to solve, doesn’t have anything to do with destructors or heap:

const std = @import("std");

const E = union(enum) {
    a: u128,
    b: []const u8,
};

pub fn main() void {
    const bad_addr: u128 = @intFromPtr(&main);

    var e: E = .{ .b = "hello" };
    const oh_no_pointer: *const []const u8 = switch (e) {
        .a => unreachable,
        .b => |*p| p,
    };
    e = .{ .a = (16 << 64) + bad_addr };
    const oh_no: []const u8 = oh_no_pointer.*;
    std.debug.print("{s}\n", .{oh_no});
}
$ zig run main.zig
��C�� �

This sort of example also breaks Ada:

https://www.enyo.de/fw/notes/ada-type-safety.html

We have a tagged union, which can hold either A or B. We initialize the union as A, take a pointer to its internals, overwrite the original with B, and then use the pointer. The pointer is still typed as A, but the bytes it points to now belong to B: a type confusion.


This being said, we care about memory unsafety primarily because it leads to exploitable software, and it’s unclear just how impactful the example above is in practice. It is a happy coincidence that by far the most exploitable memory error in practice, the infamous buffer overflow, is also trivial to fix with compiler-inserted bounds checks. The biggest miss of the industry when it comes to memory safety is not listening to Walter Bright:

https://digitalmars.com/articles/C-biggest-mistake.html

I bet that, had we got char a[..] syntax around C11, quite a few issues wouldn’t have happened!

See also What is Memory Safety?

Read the whole story
alvinashcraft
just a second ago
reply
Pennsylvania, USA
Share this story
Delete

Stop Burning Tokens to Convert your Documents

1 Share
This article covers converting your source documents to Markdown on the way in and rendering the Markdown into a polished PDF on the way out. TX Text Control handles both conversions directly in code, with no token cost, while maintaining the accuracy, pagination, and compliance that enterprise documents require.

Read the whole story
alvinashcraft
16 seconds ago
reply
Pennsylvania, USA
Share this story
Delete

Restore SQL Server Database to an OrbStack Container

1 Share

In the previous post, we’ve built a SQL Server 2025 sandbox in an OrbStack container in a Macbook. If you are like me who switched from a Windows laptop to MacBook, you are probably missing your SQL Server. Sometimes it’s just nice to have a sandbox that is separate from your all other instances for testing and learning. This is exactly what we’re trying to do here.

Download the Backup

For this exercise we want to download the full backup of Wide World Importers. Go ahead and download it from the github repo which you can find it here. And of course, take note of where you saved the .bak file.

Copy the Backup File into the Container

First, let’s create our backup directory in our cotainer. From your favorite terminal, run the following:

ShellScript

docker exec -it sql2025 mkdir -p /var/opt/mssql/backup

Then copy over the file to the directory we just created above

ShellScript

docker cp /Users/marlonribunal/Downloads/WideWorldImporters-Full.bak sql2025:/var/opt/mssql/backup/

You terminal should now say that the backup file was successfully copied.

Use VS Code to Restore the Database

Since Microsoft will never ever port SSMS to the macOS, I think VS Code with the mssql extension is a pretty much decent tool for doing work in a SQL Server.

Check the in-memory data, database, and log files contained in the backup, so we know what logical files to map to their physical paths in the container:

SQL

RESTORE FILELISTONLY
FROM DISK = N'/var/opt/mssql/backup/WideWorldImporters-Full.bak';
GO

You should see all the contained in the backup file of the WideWorldImporters database. Take note of those for the next step.

Then restore the database. Please take note that if you don’t map the path of the files to where you want to store them, the restore proccess will assume that you are restoring the files into the same directory the backup files were stored in the source. Chances are you will then get an error because those original directory don’t exist in the target container.

SQL

RESTORE DATABASE [WideWorldImporters]
FROM DISK = '/var/opt/mssql/backup/WideWorldImporters-Full.bak'
WITH 
MOVE 'WWI_Primary' TO '/var/opt/mssql/data/WideWorldImporters.mdf',
MOVE 'WWI_UserData' TO '/var/opt/mssql/data/WideWorldImporters_UserData.ndf',
MOVE 'WWI_Log' TO '/var/opt/mssql/data/WideWorldImporters_Log.ldf',
MOVE 'WWI_InMemory_Data_1' TO '/var/opt/mssql/data/WideWorldImporters_InMemory_Data_1',
REPLACE;
GO

That took about 8 seconds to complete in my container:

That’s it! Enjoy querying!

The post Restore SQL Server Database to an OrbStack Container appeared first on SQLServerCentral.

Read the whole story
alvinashcraft
57 seconds ago
reply
Pennsylvania, USA
Share this story
Delete

T-SQL Hygiene: Introducing the Covering Index

1 Share

Often in applications, we write database queries. And often, the same query is executed again and again. To make queries against large tables faster, we can add an index. This is a general improvement for anyone accessing the table. However, there is a specially designed index called a covering index that can make queries against large tables particularly faster for one specific query. We call it covering because it covers all the projections and predicates in that query.

covering index

Which query? That is up to you, the developer, to identify. Look for queries that are either 1) very important to run fast or 2) extremely frequent in your application code. Just remember, indexes are not free, so we do not create one for every query. But for the right query, we can justify a covering index, and it can make all the difference.

A little deeper

Imagine an application that shows a list of customer orders. It would frequently run this query:

SELECT
    OrderDate,
    TotalAmount,
    Status
FROM dbo.Orders
WHERE CustomerId = 42;

Let’s look at how SQL Server handles a query like this. Once the engine identifies the correct table, it applies the predicates in the WHERE clause to filter the rows. In this case, it keeps only rows where CustomerId is 42. This can reduce millions of rows, and tons of unnecessary data, to just the required few.

Finally, SQL Server applies the projection in the SELECT clause to return only OrderDate, TotalAmount, and Status. Notice that CustomerId is needed to find the rows but is not part of the final column list. This can reduce hundreds of columns, and tons of unnecessary data, to just the required few.

The mechanics of filtering rows

To make this fast, SQL Server looks for a useful index. Without one, the engine may have to step through every row in the table. With one, SQL Server can seek directly to the matching values instead of scanning the entire table. Think about finding a specific book in a large library without knowing where it is versus having its index location. It is night and day, even for a fast engine like SQL Server.

The clustered index

CREATE CLUSTERED INDEX IX_Orders_OrderId
ON dbo.Orders(OrderId);

Tables with a primary key usually have an index supporting that key. By default, SQL Server creates it as a clustered index unless the table already has one or you specify otherwise.

Imagine that same library with all its books mixed up. A clustered index is like arranging them in order, making it faster to locate a specific section. However, this is the Orders table, so its primary key is likely OrderId, not CustomerId. The primary-key index therefore does not directly help SQL Server find every order for customer 42.

The nonclustered index

CREATE NONCLUSTERED INDEX IX_Orders_CustomerId
ON dbo.Orders(CustomerId);

We could create a nonclustered index on CustomerId. Think of Battleship. When someone says E-4, you know exactly where to look. A nonclustered index works similarly: it identifies where matching rows can be found without reorganizing the entire table. It is also worth pointing out that CustomerId being a foreign key does not mean it automatically has an index. A foreign key references a key in another table, in this case Customers, but SQL Server does not automatically create an index for it.

The worst case

Without an index on CustomerId, SQL Server does what it has to do: it scans the table, tests each row, and keeps the matching ones. With a few thousand rows, this may still be fast. With a few million, it can become noticeably slow. All of this may happen in a second or so. A covering index can turn that into only a few milliseconds.

The covering index

Clustered or nonclustered is not the important part of a covering index. The query is. More specifically, the predicates in the query and the columns projected by the query are what matter. A query may benefit generically from an existing index, but a covering index is intentionally designed to match that query’s predicates and projected columns.

Including columns

CREATE NONCLUSTERED INDEX IX_Orders_CustomerId
ON dbo.Orders(CustomerId)
INCLUDE (OrderDate, TotalAmount, Status);

Now is an important time to mention that indexes can contain more than predicate columns. They can also include data.

The INCLUDE keyword adds columns to the index without making them part of the index key. If SQL Server finds the predicate value in the index and the query requests only columns included in that index, it may not need to return to the source table at all.

This combination of matching predicates and available projected columns is the heart of a covering index. Nothing could be faster than finding matching predicates in an index and, while already there, returning the included columns. This is one of the quickest ways to return query results.

Designing a covering index

To design a covering index, start with the query. Identify the columns used in the predicates, then identify the columns returned by the projection. Let’s go back to our original query:

SELECT 
    OrderDate, 
    TotalAmount, 
    Status 
FROM dbo.Orders 
WHERE CustomerId = 42;

Once you determine the hot spots in your application, the query or queries that get the most exercise, it is worth testing their performance against production-sized tables. A frequent query is not always an immediate candidate for a covering index. However, if you determine that one of these hot-path queries is impacting the user experience, it is time to think about a covering index.

Step 1: Identify the predicates

A lot of custom code dynamically adds or removes WHERE predicates through a filter interface or based on user behavior. Identify either the superset of columns used as predicates or the columns that appear in your core use cases.

In our sample, this is only CustomerId. Here is the syntax for adding that predicate to the index:

CREATE NONCLUSTERED INDEX IX_Orders_CustomerId
ON dbo.Orders(CustomerId);

The columns inside the parentheses are the index key columns. They are ordered and used by SQL Server to find matching rows.

Column order matters too.

Put equality predicates first, followed by range predicates, because SQL Server uses the leading index columns to narrow the search. Included columns do not affect the sort order, so their order is usually less important. Projection columns order usually does not matter.

Step 2: Identify the data

Pay attention when duplicating table data into an index, especially when the column data types are large. Columns containing JSON, vectors, or binary data should cause you to reconsider this step.

But perhaps the projected columns are only OrderDate, TotalAmount, and Status, as in our sample query. If you are comfortable with the additional storage, or the user experience is paramount in this equation, include all the projected columns.

Two caveats are important.

If you include all but one projected column in the index, SQL Server may still be required to return to the source table for that missing value. This eliminates much of the core value of a covering index.

On the flip side, if you include every column in the table, you have nearly duplicated the source table and introduced unnecessary storage and maintenance costs.

Here is the syntax for including the projected columns:

CREATE NONCLUSTERED INDEX IX_Orders_CustomerId
ON dbo.Orders(CustomerId)
INCLUDE (OrderDate, TotalAmount, Status);

Indexes maintain themselves. Once an index is initially built, changes to the underlying table automatically update that index and every other affected index on the table. It is worth remembering that an insert, update, or delete may not complete until the affected indexes are also updated. This means large or excessive indexes can impact the OLTP performance of your database.

Conclusion

A covering index is a kind of secret sauce when it comes to SQL performance. That is, for some queries. An army of covering indexes should be a code smell, for sure.

For the rest of your database and other queries, it often makes more sense to create general indexes that serve several queries. In fact, the automatic tuning feature in Azure SQL reviews query activity to identify queries that might benefit from additional indexes or changes to existing indexes. You can do the same thing.

Do not just add a covering index.

Test it to ensure that unwanted side effects do not creep into your workload.

In either case, the key to database performance is a smart schema, smart queries, and appropriate indexes. Think through your application and the queries you run. The next time you find a hot spot, open Copilot in SQL Server Management Studio, paste your query, and prompt:

Help me design a covering index for this query.

Then see what you can do.

The post T-SQL Hygiene: Introducing the Covering Index appeared first on Azure SQL Dev Corner.

Read the whole story
alvinashcraft
1 minute ago
reply
Pennsylvania, USA
Share this story
Delete

AI agents, meet the Azure Cosmos DB vNext emulator

1 Share

If you use the Azure Cosmos DB vNext emulator, you probably know the local development loop: start the emulator, connect to it, create some resources, load test data, run queries, and inspect the results. Each step is straightforward, but together they add setup work before you can test the application you are actually building.

How agents work with the emulator

How a developer’s intent flows through the coding agent, Agent Skill, Cosmos DB Shell, and local emulator.

 

The emulator includes the Azure Cosmos DB Shell, an open-source CLI for working with databases, containers, and items. It runs inside the emulator container and handles the local endpoint and well-known key, giving developers a direct, scriptable way to work with the emulator.

CLIs are well suited to agent workflows because they expose operations as explicit commands and return results the agent can inspect. An agent can discover commands through built-in help, run them non-interactively, respond to errors, and use the output to choose its next action. These characteristics make the CLI a practical interface for agents. Azure Cosmos DB Shell brings that model to the local emulator. For example, an agent can run Cosmos DB Shell non-interactively inside the emulator container:

docker exec <emulator-container> cosmoshell.sh -c '<command>'

It gives AI coding agents, such as GitHub Copilot CLI, Codex, and Claude Code, a straightforward way to work with the emulator. The developer describes the required outcome instead of translating the task into a sequence of shell commands. Command access is only the starting point. The agent still needs an operating procedure for finding the emulator, choosing appropriate commands, respecting safety boundaries, and verifying its work.

An Agent Skill fills that gap by packaging task-specific guidance for reuse across requests and sessions. For the local emulator, the cosmosdb-emulator-vnext skill helps the agent inspect resources, create databases and containers, load test data, and run queries through Azure Cosmos DB Shell.

From prompt to test data

Consider a developer building a multi-tenant order-processing application. The integration tests need data across multiple tenants and different stages of the order lifecycle. Creating and maintaining that data by hand can quickly become tedious.

Instead, the developer could give a coding agent this prompt:

I’m building a multi-tenant order-processing app and need realistic data
for integration testing. Set up my local Cosmos DB emulator with synthetic
orders covering two tenants and a mix of new, shipped, and cancelled orders.
Show me the data when it’s ready.

I tested this prompt with GitHub Copilot CLI while the local emulator was already running. The agent located the emulator, used the bundled Azure Cosmos DB Shell, and created OrdersDB with an Orders container partitioned by /tenantId.

It then generated a balanced set of synthetic orders for both tenants. Each order included customer details, nested line items, timestamps, shipping information, and totals. It also added status-specific fields, such as tracking information for shipped orders and cancellation reasons for cancelled ones.

The setup summary showed what the agent created:

Database: OrdersDB
Container: Orders
Partition key: /tenantId
Orders created: 12

To verify the data, the agent queried the container. Six of the 12 orders are shown below:

Order Tenant Customer Status Total
ord-a001 tenant-alpha Alice Navarro new $145.96
ord-a003 tenant-alpha Clara Mendes shipped $361.99
ord-a005 tenant-alpha Elena Vasquez cancelled $129.00
ord-b001 tenant-beta Grace Osei new $74.97
ord-b003 tenant-beta Ingrid Sorensen shipped $249.00
ord-b006 tenant-beta Luca Ferrari cancelled $101.97

Because the request is open-ended, names, values, and document counts may vary. The workflow remains the same: create the resources, load the data, and query it back. Showing the saved orders confirms that the data is in the emulator and ready for the application to use.

At this point, the developer has persisted, partitioned data for integration testing without writing a seed script or manually assembling documents.

Notice that the prompt describes the application need, not the operating procedure. It says nothing about finding the emulator, using the bundled shell, choosing non-interactive commands, or verifying changes.

Why use an Agent Skill

You could include all those operating instructions in every prompt. That works for a one-off task, but repeating the same guidance soon becomes tedious. Results can also vary when an important constraint is omitted or phrased differently.

Moving the guidance into global instructions avoids that repetition, but makes emulator-specific context available during unrelated tasks.

An Agent Skill avoids both tradeoffs. The cosmosdb-emulator-vnext skill keeps the emulator guidance in one place and makes it available when a relevant request is detected. As a markdown file, the skill can be shared, reviewed, tested, versioned, and adapted to a team’s conventions or testing workflow.

The same approach extends to other parts of Azure Cosmos DB development. The Azure Cosmos DB team maintains the Azure Cosmos DB Agent Kit, a collection of skills for AI coding agents working with Azure Cosmos DB. It includes guidance on data modeling, partition-key design, query optimization, SDK usage, indexing, throughput, security, and monitoring.

The emulator skill may also be combined into the Agent Kit and maintained there alongside other Azure Cosmos DB agent skills.

Try it yourself

Agent Skills are a lightweight, open standard that lets you reuse the same skill across coding agents.

Install the skill and put it to work with your local emulator:

npx skills add abhirockzz/cosmosdb-vnext-emulator-skill

Then run the order-processing prompt above to create your first test dataset. From there, adapt the request to the data and workflows your application needs.

Together, the local emulator, Azure Cosmos DB Shell, and the skill make this kind of setup repeatable without hiding how the work gets done. Developers can describe the data they need while the agent runs explicit commands, verifies the result, and leaves an execution trail they can inspect.

About Azure Cosmos DB

Azure Cosmos DB is a fully managed and serverless NoSQL and vector database for modern app development, including AI applications. With its SLA-backed speed and availability as well as instant dynamic scalability, it is ideal for real-time NoSQL and MongoDB applications that require high performance and distributed computing over massive volumes of NoSQL and vector data.

To stay in the loop on Azure Cosmos DB updates, follow us on XYouTube, and LinkedIn.  Join the discussion with other developers on the #nosql channel on the Microsoft Open Source Discord.

The post AI agents, meet the Azure Cosmos DB vNext emulator appeared first on Azure Cosmos DB Blog.

Read the whole story
alvinashcraft
1 minute ago
reply
Pennsylvania, USA
Share this story
Delete

A Note from Bethesda Game Studios

1 Share

The post A Note from Bethesda Game Studios appeared first on XBOX Wire.

Read the whole story
alvinashcraft
1 minute ago
reply
Pennsylvania, USA
Share this story
Delete
Next Page of Stories