Files
HomeAssistant/docs/plans/2026-03-19-nordpool-compact-prices-plan.md
2026-03-19 12:10:21 +02:00

678 lines
21 KiB
Markdown

# NordPool Compact Price Attributes Implementation Plan
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
**Goal:** Fix the HA recorder 16,384-byte attribute limit violation on `sensor.nordpool_today_tomorrow_prices` by serializing price arrays as compact `[unix_start, unix_end, price]` tuples instead of verbose `{start, end, price}` objects.
**Architecture:** A new `CompactNordPoolDayPrice` readonly struct with a custom `JsonConverter` that serializes as a JSON array. The conversion happens at the HA attribute serialization boundary in `NordPoolEntityService`. All internal code continues using `NordPoolDayPrice` unchanged.
**Tech Stack:** C# / .NET 10, System.Text.Json, xUnit, FluentAssertions, Moq
---
## Task 1: Create CompactNordPoolDayPrice Model and JsonConverter
**Files:**
- Create: `NordPool.Models/CompactNordPoolDayPrice.cs`
- Test: `NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs`
**Step 1: Write the failing tests**
Create `NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs`:
```csharp
using System.Text.Json;
using FluentAssertions;
using NordPool.Models;
namespace NordPool.Manager.Tests;
public class CompactNordPoolDayPriceTests
{
private static readonly DateTime TestStart = new(2026, 3, 19, 10, 0, 0, DateTimeKind.Utc);
private static readonly DateTime TestEnd = new(2026, 3, 19, 10, 15, 0, DateTimeKind.Utc);
private const long TestStartEpoch = 1774011600; // 2026-03-19T10:00:00Z
private const long TestEndEpoch = 1774012500; // 2026-03-19T10:15:00Z
[Fact]
public void FromDayPrice_ShouldConvertDateTimesToUnixEpochSeconds()
{
// Arrange
var dayPrice = new NordPoolDayPrice { Start = TestStart, End = TestEnd, Price = 12.35 };
// Act
var result = CompactNordPoolDayPrice.FromDayPrice(dayPrice);
// Assert
result.Start.Should().Be(TestStartEpoch);
result.End.Should().Be(TestEndEpoch);
result.Price.Should().Be(12.35);
}
[Fact]
public void FromDayPrice_WhenStartIsNull_ShouldUseZeroEpoch()
{
// Arrange
var dayPrice = new NordPoolDayPrice { Start = null, End = TestEnd, Price = 5.0 };
// Act
var result = CompactNordPoolDayPrice.FromDayPrice(dayPrice);
// Assert
result.Start.Should().Be(0L);
result.End.Should().Be(TestEndEpoch);
}
[Fact]
public void FromDayPrice_WhenEndIsNull_ShouldUseZeroEpoch()
{
// Arrange
var dayPrice = new NordPoolDayPrice { Start = TestStart, End = null, Price = 5.0 };
// Act
var result = CompactNordPoolDayPrice.FromDayPrice(dayPrice);
// Assert
result.Start.Should().Be(TestStartEpoch);
result.End.Should().Be(0L);
}
[Fact]
public void FromDayPrice_WhenPriceIsNull_ShouldPreserveNull()
{
// Arrange
var dayPrice = new NordPoolDayPrice { Start = TestStart, End = TestEnd, Price = null };
// Act
var result = CompactNordPoolDayPrice.FromDayPrice(dayPrice);
// Assert
result.Price.Should().BeNull();
}
[Fact]
public void JsonSerialization_ShouldProduceArrayFormat()
{
// Arrange
var compact = new CompactNordPoolDayPrice
{
Start = TestStartEpoch,
End = TestEndEpoch,
Price = 12.35
};
// Act
var json = JsonSerializer.Serialize(compact);
// Assert
json.Should().Be($"[{TestStartEpoch},{TestEndEpoch},12.35]");
}
[Fact]
public void JsonSerialization_WhenPriceIsNull_ShouldSerializeNullElement()
{
// Arrange
var compact = new CompactNordPoolDayPrice
{
Start = TestStartEpoch,
End = TestEndEpoch,
Price = null
};
// Act
var json = JsonSerializer.Serialize(compact);
// Assert
json.Should().Be($"[{TestStartEpoch},{TestEndEpoch},null]");
}
[Fact]
public void JsonDeserialization_ShouldRoundTrip()
{
// Arrange
var original = new CompactNordPoolDayPrice
{
Start = TestStartEpoch,
End = TestEndEpoch,
Price = 12.35
};
// Act
var json = JsonSerializer.Serialize(original);
var deserialized = JsonSerializer.Deserialize<CompactNordPoolDayPrice>(json);
// Assert
deserialized.Start.Should().Be(original.Start);
deserialized.End.Should().Be(original.End);
deserialized.Price.Should().Be(original.Price);
}
[Fact]
public void JsonSerialization_ListOfCompactPrices_ShouldProduceArrayOfArrays()
{
// Arrange
var prices = new List<CompactNordPoolDayPrice>
{
new() { Start = TestStartEpoch, End = TestEndEpoch, Price = 10.0 },
new() { Start = TestEndEpoch, End = TestEndEpoch + 900, Price = 11.0 }
};
// Act
var json = JsonSerializer.Serialize(prices);
// Assert
json.Should().Be($"[[{TestStartEpoch},{TestEndEpoch},10],[{TestEndEpoch},{TestEndEpoch + 900},11]]");
}
}
```
**Step 2: Run tests to verify they fail**
Run: `dotnet test NordPool.Manager.Tests --filter "FullyQualifiedName~CompactNordPoolDayPriceTests" --verbosity normal`
Expected: Build failure — `CompactNordPoolDayPrice` does not exist.
**Step 3: Write the implementation**
Create `NordPool.Models/CompactNordPoolDayPrice.cs`:
```csharp
using System.Text.Json;
using System.Text.Json.Serialization;
namespace NordPool.Models;
[JsonConverter(typeof(CompactNordPoolDayPriceConverter))]
public readonly struct CompactNordPoolDayPrice
{
public long Start { get; init; }
public long End { get; init; }
public double? Price { get; init; }
public static CompactNordPoolDayPrice FromDayPrice(NordPoolDayPrice dayPrice)
{
return new CompactNordPoolDayPrice
{
Start = dayPrice.Start.HasValue
? new DateTimeOffset(dayPrice.Start.Value, TimeSpan.Zero).ToUnixTimeSeconds()
: 0L,
End = dayPrice.End.HasValue
? new DateTimeOffset(dayPrice.End.Value, TimeSpan.Zero).ToUnixTimeSeconds()
: 0L,
Price = dayPrice.Price
};
}
}
internal sealed class CompactNordPoolDayPriceConverter : JsonConverter<CompactNordPoolDayPrice>
{
public override CompactNordPoolDayPrice Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartArray)
throw new JsonException("Expected start of array.");
reader.Read();
var start = reader.GetInt64();
reader.Read();
var end = reader.GetInt64();
reader.Read();
double? price = reader.TokenType == JsonTokenType.Null ? null : reader.GetDouble();
reader.Read();
if (reader.TokenType != JsonTokenType.EndArray)
throw new JsonException("Expected end of array.");
return new CompactNordPoolDayPrice { Start = start, End = end, Price = price };
}
public override void Write(Utf8JsonWriter writer, CompactNordPoolDayPrice value, JsonSerializerOptions options)
{
writer.WriteStartArray();
writer.WriteNumberValue(value.Start);
writer.WriteNumberValue(value.End);
if (value.Price.HasValue)
writer.WriteNumberValue(value.Price.Value);
else
writer.WriteNullValue();
writer.WriteEndArray();
}
}
```
**Step 4: Run tests to verify they pass**
Run: `dotnet test NordPool.Manager.Tests --filter "FullyQualifiedName~CompactNordPoolDayPriceTests" --verbosity normal`
Expected: All 8 tests PASS.
**Step 5: Commit**
```powershell
git add NordPool.Models/CompactNordPoolDayPrice.cs NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs
git commit -m "feat: add CompactNordPoolDayPrice with array-format JSON serialization"
```
---
## Task 2: Add ToCompact Extension Method
**Files:**
- Create: `NordPool.Models/NordPoolDayPriceExtensions.cs`
- Modify test: `NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs`
**Step 1: Write the failing tests**
Add these tests to `NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs`:
```csharp
[Fact]
public void ToCompact_ShouldConvertAllPrices()
{
// Arrange
var prices = new List<NordPoolDayPrice>
{
new() { Start = TestStart, End = TestEnd, Price = 10.0 },
new() { Start = TestEnd, End = TestEnd.AddMinutes(15), Price = 11.0 }
};
// Act
var result = prices.ToCompact();
// Assert
result.Should().HaveCount(2);
result[0].Start.Should().Be(TestStartEpoch);
result[0].Price.Should().Be(10.0);
result[1].Price.Should().Be(11.0);
}
[Fact]
public void ToCompact_WhenEmpty_ShouldReturnEmptyList()
{
// Arrange
var prices = Array.Empty<NordPoolDayPrice>();
// Act
var result = prices.ToCompact();
// Assert
result.Should().BeEmpty();
}
[Fact]
public void ToCompact_WhenNull_ShouldReturnEmptyList()
{
// Arrange
IEnumerable<NordPoolDayPrice>? prices = null;
// Act
var result = prices.ToCompact();
// Assert
result.Should().BeEmpty();
}
```
**Step 2: Run tests to verify they fail**
Run: `dotnet test NordPool.Manager.Tests --filter "FullyQualifiedName~CompactNordPoolDayPriceTests.ToCompact" --verbosity normal`
Expected: Build failure — `ToCompact` method does not exist.
**Step 3: Write the implementation**
Create `NordPool.Models/NordPoolDayPriceExtensions.cs`:
```csharp
namespace NordPool.Models;
public static class NordPoolDayPriceExtensions
{
public static List<CompactNordPoolDayPrice> ToCompact(this IEnumerable<NordPoolDayPrice>? prices)
{
if (prices is null)
return [];
return prices.Select(CompactNordPoolDayPrice.FromDayPrice).ToList();
}
}
```
**Step 4: Run tests to verify they pass**
Run: `dotnet test NordPool.Manager.Tests --filter "FullyQualifiedName~CompactNordPoolDayPriceTests" --verbosity normal`
Expected: All 11 tests PASS.
**Step 5: Commit**
```powershell
git add NordPool.Models/NordPoolDayPriceExtensions.cs NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs
git commit -m "feat: add ToCompact extension for NordPoolDayPrice collections"
```
---
## Task 3: Add Size Regression Test
**Files:**
- Modify: `NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs`
**Step 1: Write the size regression test**
Add to `NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs`:
```csharp
[Fact]
public void SerializedSize_WithMaxEntries_ShouldBeUnderHaAttributeLimit()
{
// Arrange — worst-case: 192 entries (96 today + 96 tomorrow)
const int maxEntries = 192;
const int haAttributeByteLimitBytes = 16_384;
var dayStart = new DateTime(2026, 3, 19, 0, 0, 0, DateTimeKind.Utc);
var prices = new List<NordPoolDayPrice>();
for (var i = 0; i < maxEntries; i++)
{
var start = dayStart.AddMinutes(i * 15);
prices.Add(new NordPoolDayPrice
{
Start = start,
End = start.AddMinutes(15),
Price = 10.0 + i * 0.01
});
}
// Act — serialize the full attribute payload shape
var compactPrices = prices.ToCompact();
var attributePayload = new
{
prices = compactPrices,
prices_count = compactPrices.Count,
friendly_name = "NordPool today and tomorrow prices",
last_updated = DateTime.UtcNow.ToString("O")
};
var json = JsonSerializer.Serialize(attributePayload);
var byteCount = System.Text.Encoding.UTF8.GetByteCount(json);
// Assert
byteCount.Should().BeLessThan(haAttributeByteLimitBytes,
$"serialized attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit");
}
```
**Step 2: Run tests to verify it passes**
Run: `dotnet test NordPool.Manager.Tests --filter "FullyQualifiedName~SerializedSize_WithMaxEntries" --verbosity normal`
Expected: PASS — compact format should be ~8,000 bytes, well under 16,384.
**Step 3: Commit**
```powershell
git add NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs
git commit -m "test: add size regression guard for compact NordPool price serialization"
```
---
## Task 4: Add MaxAttributePriceEntries Warning Constant
**Files:**
- Modify: `NordPool.Models/NordPoolConsts.cs` (line 1-16)
**Step 1: Add the constant**
Add to `NordPool.Models/NordPoolConsts.cs` after line 15:
```csharp
/// <summary>
/// Maximum expected price entries when today and tomorrow are both available
/// (96 intervals per day x 2 days). Used for logging a warning if exceeded.
/// </summary>
public const int MaxExpectedPriceEntries = 192;
```
**Step 2: Verify build succeeds**
Run: `dotnet build NordPool.Models`
Expected: Build succeeded.
**Step 3: Commit**
```powershell
git add NordPool.Models/NordPoolConsts.cs
git commit -m "feat: add MaxExpectedPriceEntries constant for oversized payload warning"
```
---
## Task 5: Update NordPoolEntityService to Use Compact Format
**Files:**
- Modify: `NordPool.Manager/NordPoolEntityService.cs` (lines 100-259)
This is the core change. Six methods need updating — 3 reset methods and 3 update methods. The pattern is identical: replace `NordPoolDayPrice` arrays/lists with their `.ToCompact()` equivalents in attribute payloads.
**Step 1: Update reset methods**
In `NordPool.Manager/NordPoolEntityService.cs`, make these changes:
**`ResetTodayPricesAsync` (line 101-110):**
Change `prices = Array.Empty<NordPoolDayPrice>()` to `prices = Array.Empty<CompactNordPoolDayPrice>()`.
**`ResetTomorrowPricesAsync` (line 112-121):**
Change `prices = Array.Empty<NordPoolDayPrice>()` to `prices = Array.Empty<CompactNordPoolDayPrice>()`.
**`ResetTodayTomorrowPricesAsync` (line 123-133):**
Change `prices = Array.Empty<NordPoolDayPrice>()` to `prices = Array.Empty<CompactNordPoolDayPrice>()`.
**Step 2: Update the update methods**
**`UpdateTodayPricesAsync` (line 228-237):**
Change:
```csharp
prices = ctx.TodayNordPoolPrice?.Prices ?? Array.Empty<NordPoolDayPrice>(),
```
To:
```csharp
prices = (ctx.TodayNordPoolPrice?.Prices).ToCompact(),
```
**`UpdateTomorrowPricesAsync` (line 239-248):**
Change:
```csharp
prices = ctx.TomorrowNordPoolPrice?.Prices ?? Array.Empty<NordPoolDayPrice>(),
```
To:
```csharp
prices = (ctx.TomorrowNordPoolPrice?.Prices).ToCompact(),
```
**`UpdateTodayTomorrowPricesAsync` (line 250-260):**
Change:
```csharp
prices = mergedPrices,
```
To:
```csharp
prices = mergedPrices.ToCompact(),
```
**Step 3: Add size warning logging**
In `UpdateEntitiesAsync` (after line 182, after `mergedPrices` is computed), add:
```csharp
if (mergedPrices.Count > NordPoolConsts.MaxExpectedPriceEntries)
{
logger.LogWarning(
"Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized",
mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries);
}
```
**Step 4: Add the `using NordPool.Models;` import if not already present**
Check that `using NordPool.Models;` is at the top of the file (it already is at line 5).
**Step 5: Verify build succeeds**
Run: `dotnet build NordPool.Manager`
Expected: Build succeeded.
**Step 6: Commit**
```powershell
git add NordPool.Manager/NordPoolEntityService.cs
git commit -m "feat: switch NordPool entity attributes to compact array serialization format"
```
---
## Task 6: Update NordPoolEntityService Tests
**Files:**
- Modify: `NordPool.Manager.Tests/NordPoolEntityServiceTests.cs`
The existing tests that verify `SetEntityAttributes` calls with `It.IsAny<object>()` will continue passing because the mock doesn't inspect attribute types. However, we should add a test verifying the compact format is actually used, and validate the combined payload size.
**Step 1: Add compact format verification test**
Add to the `UpdateEntitiesAsync` region in `NordPool.Manager.Tests/NordPoolEntityServiceTests.cs`:
```csharp
[Fact]
public async Task UpdateEntitiesAsync_TodayTomorrowPrices_ShouldUseCompactFormat()
{
// Arrange
var todayPrice = new NordPoolPrice
{
Prices = [new NordPoolDayPrice
{
Start = new DateTime(2026, 3, 19, 10, 0, 0, DateTimeKind.Utc),
End = new DateTime(2026, 3, 19, 10, 15, 0, DateTimeKind.Utc),
Price = 12.0
}]
};
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: new NordPoolPrice { Prices = [] });
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert — verify the prices attribute contains CompactNordPoolDayPrice entries (check via prices property type)
_entityManagerMock.Verify(
em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.Is<object>(o =>
o.GetType().GetProperty("prices")!.GetValue(o) is List<CompactNordPoolDayPrice>)),
Times.Once);
}
[Fact]
public async Task UpdateEntitiesAsync_WithFullDayPrices_AttributesShouldBeUnderSizeLimit()
{
// Arrange — realistic worst case: 96 today + 96 tomorrow
const int intervalsPerDay = 96;
const int haAttributeByteLimitBytes = 16_384;
var todayStart = new DateTime(2026, 3, 19, 0, 0, 0, DateTimeKind.Utc);
var tomorrowStart = new DateTime(2026, 3, 20, 0, 0, 0, DateTimeKind.Utc);
var todayPrices = Enumerable.Range(0, intervalsPerDay).Select(i => new NordPoolDayPrice
{
Start = todayStart.AddMinutes(i * 15),
End = todayStart.AddMinutes((i + 1) * 15),
Price = 5.0 + i * 0.1
}).ToList();
var tomorrowPrices = Enumerable.Range(0, intervalsPerDay).Select(i => new NordPoolDayPrice
{
Start = tomorrowStart.AddMinutes(i * 15),
End = tomorrowStart.AddMinutes((i + 1) * 15),
Price = 8.0 + i * 0.1
}).ToList();
object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"), It.IsAny<object>()))
.Returns(Task.CompletedTask);
var context = CreateDefaultContext(
todayPrice: new NordPoolPrice { Prices = todayPrices },
tomorrowPrice: new NordPoolPrice { Prices = tomorrowPrices });
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
capturedAttributes.Should().NotBeNull();
var json = System.Text.Json.JsonSerializer.Serialize(capturedAttributes);
var byteCount = System.Text.Encoding.UTF8.GetByteCount(json);
byteCount.Should().BeLessThan(haAttributeByteLimitBytes,
$"today+tomorrow attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit");
}
```
**Step 2: Run all NordPool entity service tests**
Run: `dotnet test NordPool.Manager.Tests --filter "FullyQualifiedName~NordPoolEntityServiceTests" --verbosity normal`
Expected: All tests PASS (existing + 2 new).
**Step 3: Commit**
```powershell
git add NordPool.Manager.Tests/NordPoolEntityServiceTests.cs
git commit -m "test: add compact format verification and size limit tests for NordPool entity attributes"
```
---
## Task 7: Run Full Test Suite and Verify
**Step 1: Run all tests in the solution**
Run: `dotnet test --verbosity normal`
Expected: All tests PASS across all test projects.
**Step 2: Verify build compiles cleanly**
Run: `dotnet build`
Expected: Build succeeded with no warnings.
**Step 3: Final commit if any remaining changes**
```powershell
git status
```
If clean, no commit needed. If any uncommitted files, stage and commit.
---
## Summary
| Task | Files | Tests Added |
|------|-------|-------------|
| 1. CompactNordPoolDayPrice model | `NordPool.Models/CompactNordPoolDayPrice.cs` | 8 |
| 2. ToCompact extension | `NordPool.Models/NordPoolDayPriceExtensions.cs` | 3 |
| 3. Size regression test | Tests only | 1 |
| 4. MaxExpectedPriceEntries constant | `NordPool.Models/NordPoolConsts.cs` | 0 |
| 5. Update NordPoolEntityService | `NordPool.Manager/NordPoolEntityService.cs` | 0 |
| 6. Update entity service tests | Tests only | 2 |
| 7. Full verification | None | 0 |
**Total new tests: 14**
**Total files modified: 2** (`NordPoolEntityService.cs`, `NordPoolConsts.cs`)
**Total files created: 3** (`CompactNordPoolDayPrice.cs`, `NordPoolDayPriceExtensions.cs`, `CompactNordPoolDayPriceTests.cs`)
**Post-deployment:** Update ApexCharts Lovelace card `data_generator` to:
```yaml
data_generator: |
return entity.attributes.prices.map(p => [p[0] * 1000, p[2]]);
```